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

希望对大家有帮助。

相关推荐
麦兜*1 小时前
Spring Boot 企业级动态权限全栈深度解决方案,设计思路,代码分析
java·spring boot·后端·spring·spring cloud·性能优化·springcloud
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
Hellyc6 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
hdsoft_huge6 小时前
SpringBoot 与 JPA 整合全解析:架构优势、应用场景、集成指南与最佳实践
java·spring boot·架构
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
程序员的世界你不懂7 小时前
基于Java+Maven+Testng+Selenium+Log4j+Allure+Jenkins搭建一个WebUI自动化框架(2)对框架加入业务逻辑层
java·selenium·maven
有没有没有重复的名字8 小时前
线程安全的单例模式与读者写者问题
java·开发语言·单例模式
程序员的世界你不懂10 小时前
基于Java+Maven+Testng+Selenium+Log4j+Allure+Jenkins搭建一个WebUI自动化框架(4)集成Allure报表
java·selenium·maven
isNotNullX10 小时前
数据中台架构解析:湖仓一体的实战设计
java·大数据·数据库·架构·spark