【问题标题】:Test for one of multiple exceptions in Matlab unittests测试 Matlab 单元测试中的多个异常之一
【发布时间】:2016-07-13 07:47:45
【问题描述】:

我正在使用 Matlab 的 unittest 来测试对无效参数的处理。

在测试中我有一条线

t.verifyError(@myObject.myMethod, 'MATLAB:nonStrucReference');

在 Matlab R2014a 中工作正常,但在 Matlab R2016a 中失败并显示消息

---------------------
Framework Diagnostic:
---------------------
verifyError failed.
--> The function threw the wrong exception.

    Actual Exception:
        'MATLAB:structRefFromNonStruct'
    Expected Exception:
        'MATLAB:nonStrucReference'

我想知道是否可以测试是否抛出了异常之一。

我知道可以写

t.verifyError(@myObject.myMethod, ?MException);

但更具体的会更好。

【问题讨论】:

    标签: matlab unit-testing exception-handling


    【解决方案1】:

    您可能希望编写一个自定义验证方法,该方法接受异常元胞数组作为输入。

    function verifyOneOfErrors(testcase, func, identifiers, varargin)
    
        % Ensure that a cell array was passed rather than a string
        if ischar(identifiers)
            identifiers = {identifiers};
        end
    
        % If the function succeeds with no errors, then we want a failure
        threw_correct_error = false;
    
        try
            func()
        catch ME
            % Check if the identifier is in our list of approved identifiers
            threw_correct_error = ismember(ME.identifier, identifiers);
        end
    
        % Do the actual verification
        testcase.verifyTrue(threw_correct_error, varargin{:})
    end
    

    另一种选择是通过显式导致错误并检索标识符来在测试用例中动态获取错误消息标识符。

    % Get a version-specific identifier for this specific error
    try; a = []; a.field; catch ME; end;
    
    % Verify that your method throws this error
    t.verifyError(@myObject.myMethod, ME.identifier)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 2012-06-05
      • 2013-01-21
      • 2013-10-10
      相关资源
      最近更新 更多