如何使用MATLAB寫測試(2)Negative Test
原文:如何使用MATLAB寫測試(2)Negative Test - 知乎 (zhihu.com)
上一篇請參見
如何使用MATLAB寫測試(1) - 知乎專欄
上一篇中,我們的實習生(來自俄羅斯)開發了知名的foo程序
function out = foo(in)validateattributes(in,{'numeric'},{'nonempty'}); % Returns zeroout = zeros(size(in),'like',in);
end
并加入了positive test case,接下來他想測試各種錯誤輸入,期待有正確的錯誤反應。于是他發現了MATLAB Unittest中verifyError這個神奇的method. 閱讀verifyError的文檔后,實習生發現他需要一個error的identifier,作為一名合格的實習生,他知道用lasterr來獲取這個id:
>>foo([])
Error using foo (line 2)
Expected input to be nonempty.
>>[~,id] = lasterr
id =MATLAB:expectedNonempty
于是他更新了自己的測試,加入了testEmptyError這個新的negative test case.
%% 所有的單元測試都需要從matlab.unittest.TestCase繼承
classdef myTest < matlab.unittest.TestCase%% 定義以Test為attribute的methodsmethods (Test)% 定義你自己的測試function testSingle(test) %function唯一的參數test是你的測試對象% Verifies single input casein = single(10); %輸入expOut = zeros(1,'single'); %期待的輸出actualOut = foo(in); %調用待測程序test.verifyEqual(actualOut,expOut); %比較實際輸出與期待輸出end% Negative test casefunction testEmptyError(test)% Verifies error on empty inputin = [];expErrorId = 'MATLAB:expectedNonempty';%傳入function handle, 給出期待的error idtest.verifyError(@()foo(in),expErrorId); endend
end
跑test
>> result = runtests('myTest')
Running myTest
..
Done myTest
__________result = 1x2 TestResult array with properties:NamePassedFailedIncompleteDurationDetailsTotals:2 Passed, 0 Failed, 0 Incomplete.0.044067 seconds testing time.
實習生很開心,實習生回家睡覺了。睡前他默念,MATLAB unittest大法好……
希望對大家有幫助。