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

希望对大家有帮助。

相关推荐
云烟成雨TD20 小时前
Agent Scope Java 2.x 系列【9】接入高德 MCP 服务
java·人工智能·agent
不知名的老吴20 小时前
经典算法题之行星碰撞
数据结构·算法
gaohe26AIliuzeyu20 小时前
Java内部类
java·开发语言
丘山望岳20 小时前
剑起霜华——平衡二叉树(AVL树 )精讲
开发语言·数据结构·c++
西安邮电大学20 小时前
有关数组的经典算法题
java·后端·其他·算法·面试
互联网推荐官20 小时前
上海AI Agent智能体开发公司技术选型实录:六条路径、三类架构与真实落地约束
java·人工智能·ai·架构·开发经验·上海
mikasa66720 小时前
关于Spring MVC 基于 AOP 实现的全局控制器统一处理方案@ControllerAdvice
java·spring·mvc
一 乐20 小时前
幼儿园管理系统|基于springboot + vue幼儿园管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·幼儿园管理系统
Bat U20 小时前
JavaEE|SpringMVC
java·java-ee
摇滚侠20 小时前
SpringMVC 入门到实战 SpringMVC 的执行流程 96
java·后端·spring·maven·intellij-idea