在您的工作文件夹中,创建包含以下测试类的文件 ExampleTest.m。
classdef ExampleTest < matlab.unittest.TestCase
methods(Test)
function testOne(testCase) % Test fails
testCase.verifyEqual(5, 4, 'Testing 5==4')
end
function testTwo(testCase) % Test passes
testCase.verifyEqual(5, 5, 'Testing 5==5')
end
function testThree(testCase)
% test code
end
end
end
testOne 中的 verifyEqual 验证导致测试失败。testOne 和 testTwo 中的验证包括 matlab.unittest.diagnostics.StringDiagnostic 实例。
在命令提示符下,基于 ExampleTest 类创建测试套件。
import matlab.unittest.TestRunner
import matlab.unittest.TestSuite
import matlab.unittest.plugins.TAPPlugin
import matlab.unittest.plugins.ToFile
suite = TestSuite.fromClass(?ExampleTest);
创建一个将输出显示到命令行窗口中的测试运行程序。
runner = TestRunner.withTextOutput;
创建一个 TAPPlugin,它显式指定其输出应定向到 MyTapOutput.tap 文件。
filename = 'MyTapOutput.tap';
plugin = TAPPlugin.producingOriginalFormat(ToFile(filename));
将该插接添加到 TestRunner 并运行套件。
runner.addPlugin(plugin)
result = runner.run(suite);
Running ExampleTest
================================================================================
Verification failed in ExampleTest/testOne.
----------------
Test Diagnostic:
----------------
Testing 5==4
---------------------
Framework Diagnostic:
---------------------
verifyEqual failed.
--> The values are not equal using "isequaln".
--> Failure table:
Actual Expected Error RelativeError
______ ________ _____ _____________
5 4 1 0.25
Actual double:
5
Expected double:
4
------------------
Stack Information:
------------------
In C:\work\ExampleTest.m (ExampleTest.testOne) at 4
================================================================================
...
Done ExampleTest
__________
Failure Summary:
Name Failed Incomplete Reason(s)
==================================================================
ExampleTest/testOne X Failed by verification.
只有测试失败才在屏幕上产生输出。默认情况下,TestRunner.withTextOutput 使用 DiagnosticsOutputPlugin 在屏幕上显示输出。
观察该插件创建的文件中的内容。
disp(fileread(filename))
1..3
not ok 1 - ExampleTest/testOne
# ================================================================================
# Verification failed in ExampleTest/testOne.
#
# ----------------
# Test Diagnostic:
# ----------------
# Testing 5==4
#
# ---------------------
# Framework Diagnostic:
# ---------------------
# verifyEqual failed.
# --> The values are not equal using "isequaln".
# --> Failure table:
# Actual Expected Error RelativeError
# ______ ________ _____ _____________
#
# 5 4 1 0.25
#
# Actual double:
# 5
# Expected double:
# 4
#
# ------------------
# Stack Information:
# ------------------
# In C:\work\ExampleTest.m (ExampleTest.testOne) at 4
# ================================================================================
#
ok 2 - ExampleTest/testTwo
ok 3 - ExampleTest/testThree