gpt4 book ai didi

matlab - 如何编写一个单元测试断言来检查具有指定标识符和特定消息的错误?

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:06 27 4
gpt4 key购买 nike

我正在使用新的 unit testing framework对于在 R2013a 中引入的 MATLAB,matlab.unittest。我想写一个断言,以下两种情况都会发生:

  1. 引发了具有指定标识符的异常。
  2. 该异常的消息满足某些条件。

我找到了 verifyError方法,但这似乎只允许我检查标识符或错误元类。

另一个选项似乎是 verifyThatThrows约束。这似乎更有希望,但 Throws 的文档似乎有些稀疏,我不知道如何让它做我想做的事。

我意识到我可以将消息文本添加到错误标识符中,但我真的不想这样做。消息文本来自使用 mex 文件调用的 native 库。文本用空格等格式化。文本可能会很长,并且会弄乱错误标识符。

那么,是否有可能实现我想要的,如果可以,如何实现?

最佳答案

没有现成的功能可以做到这一点。这是破解它的一种方法。

考虑我们正在测试的以下功能。它在非数字输入上抛出特定错误:

增量.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 block 的使用受到旧 xUnit Test Framework 中的 assertExceptionThrown 函数的启发。由史蒂夫埃丁斯。(更新:该框架似乎已从文件交换中删除,我想鼓励改用新的内置框架。如果您感兴趣,这里是旧 xUnit 的一个流行分支: psexton/matlab-xunit ).

如果您想更灵活地测试错误消息,请使用 verifyMatches而是使用正则表达式匹配字符串。


此外,如果您喜欢冒险,可以研究 matlab.unittest.constraints.Throws类并创建你的 own version除错误 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 的代码我实现了一个 custom 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 ,我们必须实现接口(interface)的两个功能:satisfiedBygetDiagnosticFor .另请注意,我们改为继承自另一个抽象类 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。如果您想要旧版本,请查看修订历史。

关于matlab - 如何编写一个单元测试断言来检查具有指定标识符和特定消息的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17401971/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com