您可以设置自己的单元测试框架并在循环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 的单元测试框架。这是一个基于脚本的单元测试的简单示例:
图像文件搜索.m
function [imageNamesForImport] = imageFileSearch(fileList, stringToMatch)
iP = inputParser;
iP.addRequired('fileList', @isstruct);
iP.addRequired('stringToMatch', @ischar);
iP.parse(fileList, stringToMatch);
imageNamesForImport = 'hi';
测试.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.