doy*_*oyz 3 matlab unit-testing
我不确定在执行单元测试时如何传入变量.这些变量是从未放置在单元测试中的另一个函数创建的.
方法1:
classdef myTest < matlab.unittest.TestCase
properties
A, B, C
end
methods (Test)
function testDataCoverage(testCase)
expSol = afunction(A, B, C)
actSol = 10
testCase.verifyEqual(testCase, actSol, expSol)
end
end
end
Run Code Online (Sandbox Code Playgroud)
我接下来尝试将变量创建函数(getData)放在单元测试中但遇到此错误:
具体类myTest没有为dataCoverage方法定义名为BNew的TestParameter属性.实现属性或将类定义为Abstract.
方法2:
classdef myTest < matlab.unittest.TestCase
properties
end
methods (Test)
function testDataCoverage(testCase)
[A, B, C] = getData()
expSol = afunction(A, B, C)
actSol = 10
testCase.verifyEqual(testCase, actSol, expSol)
end
function [A, B, C] = getData()
...code here...
end
function Sol = afunction(A, BNew, C)
...code here...
end
end
end
Run Code Online (Sandbox Code Playgroud)
小智 5
我想你想要使用的是TestParameter:
classdef myTest < matlab.unittest.TestCase
properties (TestParameter)
param = {1, 2};
end
methods (Test)
function testDataCoverage(testCase, param)
testCase.verifyEqual(param, 1);
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后,Matlab将自动创建n个测试用例(对于单元格列表中的每个条目),其中param-parameter将与TestParameter的不同条目相关联.因此,您将自动循环遍历所有这些.(注意:如果每个TestCase有多个TestParamater,您可能需要在Matlab文档中查看ParameterCombination ...)
那些TestParameter也可以通过(外部)静态方法创建:classdef myTest <matlab.unittest.TestCase
properties (TestParameter)
param = myTest.getData();
end
methods (Test)
function testDataCoverage(testCase, param)
testCase.verifyEqual(param, 1);
end
end
methods (Static)
function data = getData()
data = {1,2,3};
end
end
end
Run Code Online (Sandbox Code Playgroud)
Fiy:这个外部源只会触发一次,直到解析出类.它保留在内存和matlab缓存中.如果您在此处阅读了一些外部配置文件,您可能希望clear all
强制重新创建该类.
子答案:在您的Method2 Block中,[A, B, C] = getData()
您缺少自引用myTest.getData()
.