2016-07-13 53 views
1

我正在使用Matlab的unittest来测试无效参数的处理。在Matlab中测试多个异常中的一个例外测试

在测试中我有一个线

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); 

,但更具体的东西会更好。

回答

2

您可能想要编写自定义验证方法,该方法接受异常的单元数组作为输入。

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) 
相关问题