如何使用MATLAB写测试(2)Negative Test

如何使用MATLAB写测试(2)Negative Test

原文:如何使用MATLAB写测试(2)Negative Test - 知乎 (zhihu.com)

上一篇请参见

如何使用MATLAB写测试(1) - 知乎专栏

上一篇中,我们的实习生(来自俄罗斯)开发了知名的foo程序

复制代码
function out = foo(in)
    validateattributes(in,{'numeric'},{'nonempty'}); 
    % Returns zero
    out = 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的methods
    methods (Test)
        % 定义你自己的测试
        function testSingle(test) %function唯一的参数test是你的测试对象
            % Verifies single input case
            in        = single(10);             %输入
            expOut    = zeros(1,'single');      %期待的输出
            actualOut = foo(in);                %调用待测程序
            test.verifyEqual(actualOut,expOut); %比较实际输出与期待输出
        end
        
        % Negative test case
        function testEmptyError(test)
            % Verifies error on empty input
            in         = [];
            expErrorId = 'MATLAB:expectedNonempty';
            %传入function handle, 给出期待的error id
            test.verifyError(@()foo(in),expErrorId);            
        end
    end
end

跑test

复制代码
>> result = runtests('myTest')
Running myTest
..
Done myTest
__________


result = 

  1x2 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
    Details

Totals:
   2 Passed, 0 Failed, 0 Incomplete.
   0.044067 seconds testing time.

实习生很开心,实习生回家睡觉了。睡前他默念,MATLAB unittest大法好......

希望对大家有帮助。

相关推荐
_院长大人_8 分钟前
设计模式-工厂模式
java·开发语言·设计模式
MATLAB代码顾问10 分钟前
MATLAB实现决策树数值预测
开发语言·决策树·matlab
凌波粒44 分钟前
MyBatis完整教程IDEA版(2)--ResultMap/注解/一对多/多对一/lombok/log4j
java·intellij-idea·mybatis
蓝-萧1 小时前
【玩转全栈】----Django基本配置和介绍
java·后端
priority_key1 小时前
排序算法:堆排序、快速排序、归并排序
java·后端·算法·排序算法·归并排序·堆排序·快速排序
汤姆yu2 小时前
基于SpringBoot的动漫周边商场系统的设计与开发
java·spring boot·后端
皮皮林5512 小时前
快速解决 Maven 版本冲突指南 !
java·maven
灰小猿2 小时前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
算法与编程之美3 小时前
理解Java finalize函数
java·开发语言·jvm·算法
怕什么真理无穷3 小时前
C++面试4-线程同步
java·c++·面试