如何使用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大法好......

希望对大家有帮助。

相关推荐
天天向上291几秒前
Spring AI 实战:14 个踩坑记录,其中一个让我的测试全绿但产品是坏的
java·开源
正在走向自律10 分钟前
从只写接口到独立交付前后端,飞算JavaAI能给Java后端工程师多少溢价?
java·springboot·ai编程·全栈开发·java求职·飞算javaai·金九银十
a努力。41 分钟前
LangChain Agent消息链路全解析
java·前端·javascript
SL_staff1 小时前
物模型是设备的数字身份证:属性、事件、服务如何决定IoT系统扩展性
java·物联网·全栈
资深技术分享员1 小时前
Geejing WebBuilder 日志、在线用户、系统监控,出问题时的三个第一现场
java·运维·数据库
卓怡学长1 小时前
w202springboot基于B_S架构的图书信息管理系统
java·spring boot·spring·intellij-idea
Bruce_Liuxiaowei1 小时前
Python 字典默认值完全指南:从 KeyError 到 defaultdict
开发语言·数据结构·python·字典
走到天涯海角1 小时前
用springBoot写几个简单的接口
java·spring boot·intellij-idea
troy1281 小时前
Java 技术栈全景指南:从基础到微服务的完整知识体系
java·开发语言·微服务
Escalating_xu1 小时前
【C 语言】深入理解指针(2):数组名、数组传参、二级指针与指针数组
java·c语言·开发语言