Модульный тест для вывода inputParser в Matlab

Я только начинаю погружаться в тестирование в Matlab и пытаюсь написать тест, который проверит, правильно ли inputParser улавливает неправильные значения аргументов функции. Например:

function [imageNamesForImport] = imageFileSearch(fileList, stringToMatch)

iP = inputParser;
iP.addRequired('fileList', @isstruct);
iP.addRequired('stringToMatch', @ischar);
iP.parse(fileList, stringToMatch);

выдаст ошибку, если я передам переменную как fileList, которая не является структурой

fileList = 'foo'
stringToMatch = 'bar'
imageNamesForImport = imageFileSearch(fileList, stringToMatch)

Error using imageFileSearch (line 7)
The value of 'fileList' is invalid. It must satisfy the function: isstruct.

Можно ли написать модульный тест для проверки этого вывода без использования серии операторов try/catch для назначения пользовательских ошибок для verifyError?


person Community    schedule 01.12.2015    source источник
comment
Что вы имеете в виду под отсутствием необходимости использовать серию операторов try/catch для назначения пользовательских ошибок для verifyError? Вы пытаетесь использовать verifyError, но не заботитесь об идентификаторах ошибок, потому что они могут измениться? Как бы вы использовали try/catch вместе с verifyError? Мне кажется, что эти двое никогда не встретятся (try-catch находится внутри verifyError).   -  person Andy Campbell    schedule 07.12.2015


Ответы (2)


Вы можете настроить свою собственную среду модульного тестирования и использовать один блок try-catch внутри цикла for:

% Set up test cases
test(1).fileList = 'foo';
test(2).fileList.a = 12;
test(3).fileList.a = 'bar';

test(1).stringToMatch = 'bar';
test(2).stringToMatch = 5;
test(3).stringToMatch = 'bar';

% Run tests
myerrs = [];
for ii = 1:length(test)
    try
        imageNamesForImport = imageFileSearch(test(ii).fileList, test(ii).stringToMatch);
    catch err
        myerrs = [myerrs err];
        % Any other custom things here
    end
end

Что в данном случае дает нам структуру ошибок 1x2, которую мы можем исследовать.


Вы также можете использовать среду модульного тестирования MATLAB. Вот простой пример для модульного теста на основе сценариев. :

imageFileSearch.m

function [imageNamesForImport] = imageFileSearch(fileList, stringToMatch)

iP = inputParser;
iP.addRequired('fileList', @isstruct);
iP.addRequired('stringToMatch', @ischar);
iP.parse(fileList, stringToMatch);
imageNamesForImport = 'hi';

testtrial.m

%% Test 1
fileList = 'foo';
stringToMatch = 'bar';
imageNamesForImport = imageFileSearch(fileList, stringToMatch);

%% Test 2
fileList.a = 12;
stringToMatch = 5;
imageNamesForImport = imageFileSearch(fileList, stringToMatch);

%% Test 3
fileList.a = 'bar';
stringToMatch = 'bar';
imageNamesForImport = imageFileSearch(fileList, stringToMatch);

Что дает нам следующий вывод командного окна:

Running testtrial

================================================================================
Error occurred in testtrial/Test1 and it did not run to completion.

    --------------
    Error Details:
    --------------
    The value of 'fileList' is invalid. It must satisfy the function: isstruct.

================================================================================
.
================================================================================
Error occurred in testtrial/Test2 and it did not run to completion.

    --------------
    Error Details:
    --------------
    The value of 'stringToMatch' is invalid. It must satisfy the function: ischar.

================================================================================
..
Done testtrial
__________

Failure Summary:

     Name             Failed  Incomplete  Reason(s)
    ================================================
     testtrial/Test1    X         X       Errored.
    ------------------------------------------------
     testtrial/Test2    X         X       Errored.
person excaza    schedule 01.12.2015

См. мой уточняющий вопрос, если это не отвечает на ваш вопрос, но вы должны просто иметь возможность использовать verifyError с конкретным идентификатором inputParser:

fileList = 'foo'
stringToMatch = 'bar'
testCase.verifyError(@() imageFileSearch(fileList, stringToMatch), ...
    'MATLAB:InputParser:ArgumentFailedValidation');

Если вы хотите проверить, произошла ли более конкретная ошибка, вы можете вместо этого проверить с помощью функции, которая выдает ваше собственное сообщение и идентификатор:

function [imageNamesForImport] = imageFileSearch(fileList, stringToMatch)

iP = inputParser;
iP.addRequired('fileList', @validateStruct);
iP.addRequired('stringToMatch', @ischar);
iP.parse(fileList, stringToMatch);


function validateStruct(s)
assert(isstruct(s), 'ImageFileSearch:IncorrectInput:FileListMustBeStruct', ...
    'fileList must be a struct.'); % Can also just be inlined in addRequired call

Затем вы можете протестировать его с помощью:

fileList = 'foo'
stringToMatch = 'bar'
testCase.verifyError(@() imageFileSearch(fileList, stringToMatch), ...
    'ImageFileSearch:IncorrectInput:FileListMustBeStruct');
person Andy Campbell    schedule 07.12.2015