inputParser输出matlab的单元测试

时间:2015-12-01 21:12:41

标签: matlab unit-testing input-sanitization

我刚刚开始深入研究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分配自定义错误?

2 个答案:

答案 0 :(得分:1)

如果这不能回答您的问题,请参阅我的澄清问题,但您应该能够将verifyError与inputParser特定ID一起使用:

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

如果您想验证更具体的错误,可以使用抛出您自己的消息和ID的函数进行验证:

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');

答案 1 :(得分:0)

您可以设置自己的单元测试框架,并在gets()循环内使用单个try-catch块:

for

在这种情况下,我们可以调查1x2错误结构。

您还可以使用MATLAB's Unit Testing Framework。以下是Script-Based Unit Test的简单示例:

<强> imageFileSearch.m

% 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

<强> testtrial.m

function [imageNamesForImport] = imageFileSearch(fileList, stringToMatch)

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

这为我们提供了以下命令窗口输出:

%% 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);