没有现成的功能可以做到这一点。这是破解它的一种方法。
考虑我们正在测试的以下函数。它在非数字输入上引发特定错误:
增量.m
function out = increment(x)
if ~isa(x,'numeric')
error('increment:NonNumeric', 'Input must be numeric.');
end
out = x + 1;
end
这是单元测试代码:
增量测试.m
classdef IncrementTest < matlab.unittest.TestCase
methods (Test)
function testOutput(t)
t.verifyEqual(increment(1), 2);
end
function testClass(t)
t.verifyClass(increment(1), class(2));
end
function testErrId(t)
t.verifyError(@()increment('1'), 'increment:NonNumeric');
end
function testErrIdMsg(t)
% expected exception
expectedME = MException('increment:NonNumeric', ...
'Input must be numeric.');
noErr = false;
try
[~] = increment('1');
noErr = true;
catch actualME
% verify correct exception was thrown
t.verifyEqual(actualME.identifier, expectedME.identifier, ...
'The function threw an exception with the wrong identifier.');
t.verifyEqual(actualME.message, expectedME.message, ...
'The function threw an exception with the wrong message.');
end
% verify an exception was thrown
t.verifyFalse(noErr, 'The function did not throw any exception.');
end
end
end
使用 try/catch 块的灵感来自于Steve EddinsassertExceptionThrown
的旧xUnit 测试框架中的函数。(更新:该框架似乎已从文件交换中删除,我想鼓励使用新的内置框架。如果您有兴趣,这里是旧 xUnit 的一个流行分支:psexton/matlab-xunit)。
如果您想在测试错误消息时提供更多的灵活性,请verifyMatches
使用正则表达式来匹配字符串。
此外,如果您喜欢冒险,您可以学习该matlab.unittest.constraints.Throws
课程并创建您自己的版本,该版本除了检查错误 ID 之外还检查错误消息。
ME = MException('error:id', 'message');
import matlab.unittest.constraints.Throws
%t.verifyThat(@myfcn, Throws(ME));
t.verifyThat(@myfcn, ThrowsWithId(ME));
ThrowsWithId
你的扩展版本在哪里
编辑:
好的,所以我浏览了代码matlab.unittest.constraints.Throws
并实现了一个自定义 Constraint
类。
该类类似于Throws
. 它接受一个MException
实例作为输入,并检查被测试的函数句柄是否抛出了类似的异常(检查错误 ID 和消息)。它可以与任何断言方法一起使用:
testCase.assertThat(@fcn, ThrowsErr(ME))
testCase.assumeThat(@fcn, ThrowsErr(ME))
testCase.fatalAssertThat(@fcn, ThrowsErr(ME))
testCase.verifyThat(@fcn, ThrowsErr(ME))
要从抽象类创建子类matlab.unittest.constraints.Constraint
,我们必须实现接口的两个功能:satisfiedBy
和getDiagnosticFor
。另请注意,我们改为从另一个抽象类继承,FunctionHandleConstraint
因为它提供了一些辅助方法来处理函数句柄。
构造函数采用预期的异常(作为MException
实例)和一个可选输入,指定输出参数的数量,用于调用正在测试的函数句柄。
编码:
classdef ThrowsErr < matlab.unittest.internal.constraints.FunctionHandleConstraint
%THROWSERR Constraint specifying a function handle that throws an MException
%
% See also: matlab.unittest.constraints.Throws
properties (SetAccess = private)
ExpectedException;
FcnNargout;
end
properties (Access = private)
ActualException = MException.empty;
end
methods
function constraint = ThrowsErr(exception, numargout)
narginchk(1,2);
if nargin < 2, numargout = 0; end
validateattributes(exception, {'MException'}, {'scalar'}, '', 'exception');
validateattributes(numargout, {'numeric'}, {'scalar', '>=',0, 'nonnegative', 'integer'}, '', 'numargout');
constraint.ExpectedException = exception;
constraint.FcnNargout = numargout;
end
end
%% overriden methods for Constraint class
methods
function tf = satisfiedBy(constraint, actual)
tf = false;
% check that we have a function handle
if ~constraint.isFunction(actual)
return
end
% execute function (remembering that its been called)
constraint.invoke(actual);
% check if it never threw an exception
if ~constraint.HasThrownAnException()
return
end
% check if it threw the wrong exception
if ~constraint.HasThrownExpectedException()
return
end
% if we made it here then we passed
tf = true;
end
function diag = getDiagnosticFor(constraint, actual)
% check that we have a function handle
if ~constraint.isFunction(actual)
diag = constraint.getDiagnosticFor@matlab.unittest.internal.constraints.FunctionHandleConstraint(actual);
return
end
% check if we need to execute function
if constraint.shouldInvoke(actual)
constraint.invoke(actual);
end
% check if it never threw an exception
if ~constraint.HasThrownAnException()
diag = constraint.FailingDiagnostic_NoException();
return
end
% check if it threw the wrong exception
if ~constraint.HasThrownExpectedException()
diag = constraint.FailingDiagnostic_WrongException();
return
end
% if we made it here then we passed
diag = PassingDiagnostic(constraint);
end
end
%% overriden methods for FunctionHandleConstraint class
methods (Hidden, Access = protected)
function invoke(constraint, fcn)
outputs = cell(1,constraint.FcnNargout);
try
[outputs{:}] = constraint.invoke@matlab.unittest.internal.constraints.FunctionHandleConstraint(fcn);
constraint.ActualException = MException.empty;
catch ex
constraint.ActualException = ex;
end
end
end
%% private helper functions
methods (Access = private)
function tf = HasThrownAnException(constraint)
tf = ~isempty(constraint.ActualException);
end
function tf = HasThrownExpectedException(constraint)
tf = metaclass(constraint.ActualException) <= metaclass(constraint.ExpectedException) && ...
strcmp(constraint.ActualException.identifier, constraint.ExpectedException.identifier) && ...
strcmp(constraint.ActualException.message, constraint.ExpectedException.message);
end
function diag = FailingDiagnostic_NoException(constraint)
import matlab.unittest.internal.diagnostics.ConstraintDiagnosticFactory;
import matlab.unittest.internal.diagnostics.DiagnosticSense;
subDiag = ConstraintDiagnosticFactory.generateFailingDiagnostic(...
constraint, DiagnosticSense.Positive);
subDiag.DisplayDescription = true;
subDiag.Description = 'The function did not throw any exception.';
subDiag.DisplayExpVal = true;
subDiag.ExpValHeader = 'Expected exception:';
subDiag.ExpVal = sprintf('id = ''%s''\nmsg = ''%s''', ...
constraint.ExpectedException.identifier, ...
constraint.ExpectedException.message);
diag = constraint.generateFailingFcnDiagnostic(DiagnosticSense.Positive);
diag.addCondition(subDiag);
end
function diag = FailingDiagnostic_WrongException(constraint)
import matlab.unittest.internal.diagnostics.ConstraintDiagnosticFactory;
import matlab.unittest.internal.diagnostics.DiagnosticSense;
if strcmp(constraint.ActualException.identifier, constraint.ExpectedException.identifier)
field = 'message';
else
field = 'identifier';
end
subDiag = ConstraintDiagnosticFactory.generateFailingDiagnostic(...
constraint, DiagnosticSense.Positive, ...
sprintf('''%s''',constraint.ActualException.(field)), ...
sprintf('''%s''',constraint.ExpectedException.(field)));
subDiag.DisplayDescription = true;
subDiag.Description = sprintf('The function threw an exception with the wrong %s.',field);
subDiag.DisplayActVal = true;
subDiag.DisplayExpVal = true;
subDiag.ActValHeader = sprintf('Actual %s:',field);
subDiag.ExpValHeader = sprintf('Expected %s:',field);
diag = constraint.generateFailingFcnDiagnostic(DiagnosticSense.Positive);
diag.addCondition(subDiag);
end
function diag = PassingDiagnostic(constraint)
import matlab.unittest.internal.diagnostics.ConstraintDiagnosticFactory;
import matlab.unittest.internal.diagnostics.DiagnosticSense;
subDiag = ConstraintDiagnosticFactory.generatePassingDiagnostic(...
constraint, DiagnosticSense.Positive);
subDiag.DisplayExpVal = true;
subDiag.ExpValHeader = 'Expected exception:';
subDiag.ExpVal = sprintf('id = ''%s''\nmsg = ''%s''', ...
constraint.ExpectedException.identifier, ...
constraint.ExpectedException.message);
diag = constraint.generatePassingFcnDiagnostic(DiagnosticSense.Positive);
diag.addCondition(subDiag);
end
end
end
这是一个示例用法(使用与以前相同的功能):
t = matlab.unittest.TestCase.forInteractiveUse;
ME = MException('increment:NonNumeric', 'Input must be numeric.');
t.verifyThat(@()increment('5'), ThrowsErr(ME))
ME = MException('MATLAB:TooManyOutputs', 'Too many output arguments.');
t.verifyThat(@()increment(5), ThrowsErr(ME,2))
更新:
自从我发布此答案以来,某些类的内部结构发生了一些变化。我更新了上面的代码以使用最新的 MATLAB R2016a。如果您想要旧版本,请查看修订历史记录。