Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

verifyError

类: matlab.unittest.qualifications.Verifiable
命名空间: matlab.unittest.qualifications

确认函数遇到指定异常

说明

示例

verifyError(testCase,actual,identifier) 验证 actual 是引发由 identifier 指定的异常的函数句柄。

示例

verifyError(testCase,actual,identifier,diagnostic) 还将 diagnostic 中的诊断信息与验证相关联。

示例

[output1,...,outputN] = verifyError(___) 还返回函数句柄产生的输出值。使用此语法控制调用函数句柄时请求的输出数目。如果函数句柄引发异常,则所有输出都将显示为 <missing>。您可以使用以前语法中的任意输入参数组合。

输入参数

全部展开

测试用例,指定为 matlab.unittest.qualifications.Verifiable 对象。由于 matlab.unittest.TestCase 类会子类化 matlab.unittest.qualifications.Verifiable 并继承其方法,因此 testCase 通常是 matlab.unittest.TestCase 对象。

要测试的值,指定为任何数据类型的值。虽然您可以提供任何数据类型的值,但如果 actual 不是函数句柄,测试将失败。

示例: @() myFunction(1,2)

示例: @() rmdir("myFolder")

错误标识符,指定为字符串标量、字符向量或 meta.class 实例。

如果 identifiermeta.class 实例,则引发的异常必须为指定类或其子类之一的实例。

示例: "MATLAB:UndefinedFunction"

示例: ?MException

当验证通过或失败时显示的诊断信息,指定为字符串数组、字符数组、函数句柄或 matlab.automation.diagnostics.Diagnostic 对象数组。

根据测试运行器的配置,测试框架可能会在验证通过或失败时显示诊断信息。默认情况下,框架仅在鉴定失败时显示诊断信息。您可以通过自定义测试运行器来覆盖默认行为。例如,使用 DiagnosticsOutputPlugin 实例来显示失败和通过事件诊断信息。

示例: "My Custom Diagnostic"

示例: @dir

属性

Sealedtrue

要了解方法的属性,请参阅方法属性

示例

全部展开

使用 verifyError 测试函数是否对无效输入作出正确响应。

在当前文件夹的一个文件中创建 add5 函数。该函数接受数值输入,并将其增加 5。如果使用非数值输入调用该函数,该函数将引发由 "add5:InputMustBeNumeric" 指定的异常。

function y = add5(x)
% add5 - Increment input by 5
if ~isa(x,"numeric")
    error("add5:InputMustBeNumeric","Input must be numeric.")
end
y = x + 5;
end

为交互式测试创建一个测试用例,然后验证如果使用输入 '0' 调用 add5,它是否会引发指定的异常。

testCase = matlab.unittest.TestCase.forInteractiveUse;
verifyError(testCase,@() add5('0'),"add5:InputMustBeNumeric")
Verification passed.

测试 actual 值是否为引发指定异常的函数句柄。

创建一个供交互测试的测试用例。

testCase = matlab.unittest.TestCase.forInteractiveUse;

验证 error 函数引发具有预期标识符的异常。

verifyError(testCase,@() error("SOME:error:id","Error!"),"SOME:error:id")
Verification passed.

使用 "OTHER:error:id" 作为预期的错误标识符重复该测试。测试失败。

verifyError(testCase,@() error("SOME:error:id","Error!"), ...
    "OTHER:error:id","Error identifiers must match.")
Verification failed.
    ----------------
    Test Diagnostic:
    ----------------
    Error identifiers must match.
    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyError failed.
    --> The function threw the wrong exception.
        
        Actual Exception:
            'SOME:error:id'
        Expected Exception:
            'OTHER:error:id'
    --> Actual Error Report:
            Error using
            VerifyErrorTestForSpecifiedExceptionsExample>@()error("SOME:error:id","Error!")
            (line 20)
            Error!
    
    Evaluated Function:
      function_handle with value:
    
        @()error("SOME:error:id","Error!")
    ------------------
    Stack Information:
    ------------------
    In C:\work\TestForSpecifiedExceptionsExample.m (TestForSpecifiedExceptionsExample) at 20

测试 rand 函数,并检查函数的输出。测试失败,因为 rand 没有引发任何异常。

r = verifyError(testCase,@rand,?MException)
Verification failed.
    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyError failed.
    --> The function did not throw any exception.
        
        Expected Exception:
            ?MException
    
    Evaluated Function:
      function_handle with value:
    
        @rand
    ------------------
    Stack Information:
    ------------------
    In C:\work\TestForSpecifiedExceptionsExample.m (TestForSpecifiedExceptionsExample) at 26

r =

    0.8147

验证在 actual 值并非函数句柄时测试是否失败。

verifyError(testCase,5,?MException)
Verification failed.
    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyError failed.
    --> The value must be an instance of the expected type.
        
        Actual Class:
            double
        Expected Type:
            function_handle
    
    Actual Value:
         5
    ------------------
    Stack Information:
    ------------------
    In C:\work\TestForSpecifiedExceptionsExample.m (TestForSpecifiedExceptionsExample) at 30

验证在带过多的输出调用函数时是否引发指定的异常。

在当前文件夹内的文件中,创建 variableNumArguments 函数,该函数接受可变数目的输入和输出。如果输出数目大于输入数目,函数将引发异常。否则,它返回输入的类。

function varargout = variableNumArguments(varargin)
if nargout > nargin
    error("variableNumArguments:TooManyOutputs", ...
        "Number of outputs must not exceed the number of inputs.")
end
varargout = cell(1,nargout);
for i = 1:nargout
    varargout{i} = class(varargin{i});
end
end

创建一个供交互测试的测试用例。然后,通过向 variableNumArguments 提供两个输入并请求相同数目的输出,对其进行测试。测试失败,因为函数没有引发指定的异常。

testCase = matlab.unittest.TestCase.forInteractiveUse;
[c1,c2] = verifyError(testCase,@() variableNumArguments(1,'2'), ...
    "variableNumArguments:TooManyOutputs")
Verification failed.
    ---------------------
    Framework Diagnostic:
    ---------------------
    verifyError failed.
    --> The function did not throw any exception.
        
        Expected Exception:
            'variableNumArguments:TooManyOutputs'
    
    Evaluated Function:
      function_handle with value:
    
        @()variableNumArguments(1,'2')
    ------------------
    Stack Information:
    ------------------
    In C:\work\TestFunctionWithVariableNumberOfInputsAndOutputsExample.m (TestFunctionWithVariableNumberOfInputsAndOutputsExample) at 22

c1 =

    'double'


c2 =

    'char'

验证在带过多的输出调用 variableNumArguments 时,它是否引发标识符为 "variableNumArguments:TooManyOutputs" 的异常。

[c1,c2,c3] = verifyError(testCase,@() variableNumArguments(1,'2'), ...
    "variableNumArguments:TooManyOutputs")
Verification passed.

c1 = 

  missing

    <missing>


c2 = 

  missing

    <missing>


c3 = 

  missing

    <missing>

提示

  • verifyError 方法非常方便。例如,verifyError(testCase,actual,identifier) 在功能上等效于以下代码。

    import matlab.unittest.constraints.Throws
    testCase.verifyThat(actual,Throws(identifier))
    

    当直接通过 verifyThat 使用 Throws 约束时,可利用更多功能。

  • 使用此确认在不引发异常的条件下生成和记录失败。由于确认不会引发异常,因此即使出现确认失败的情形,依然会完成所有的测试内容。通常,确认指的是对单元测试的主要验证,因为这些确认一般不要求提前从测试中退出。使用其他验证类型来测试是否违反先决条件或测试安装是否正确:

    • 使用断言验证确保测试环境满足无论如何都不会导致测试失败的先决条件。假设失败会生成已过滤的测试,且测试框架会将测试设为 Incomplete。有关详细信息,请参阅 matlab.unittest.qualifications.Assumable

    • 当失败条件导致当前测试内容的剩余部分都失效,但不会阻止后续测试正确执行时,使用断言验证。断言点处的失败会将当前测试展现为 FailedIncomplete。有关详细信息,请参阅 matlab.unittest.qualifications.Assertable

    • 使用致命断言验证在失败时中止测试会话。当失败涉及根本以致继续测试已经没有意义时,这些验证非常有用。当脚手架拆解不能正确还原环境状态,适合中止测试并启动一个新会话时,致命断言也很有用。有关详细信息,请参阅 matlab.unittest.qualifications.FatalAssertable

版本历史记录

在 R2013a 中推出