Fra*_*aar 5 matlab unit-testing parameterized-unit-test
我正在尝试创建一个参数化的Matlab单元测试,其中TestParameter属性由某些代码"动态地"生成(例如,使用for循环).
作为一个简化的例子,假设我的代码是
classdef partest < matlab.unittest.TestCase
properties (TestParameter)
level = struct('level1', 1, 'level2', 2, 'level3', 3, 'level4', 4)
end
methods (Test)
function testModeling(testCase, level)
fprintf('Testing level %d\n', level);
end
end
end
Run Code Online (Sandbox Code Playgroud)
但在我的真实代码中,我有100个级别.我试着将它放在一个单独的方法中,比如
classdef partest < matlab.unittest.TestCase
methods (Static)
function level = getLevel()
for i=1:100
level.(sprintf('Level%d', i)) = i;
end
end
end
properties (TestParameter)
level = partest.getLevel()
end
methods (Test)
function testModeling(testCase, level)
fprintf('Testing level %d\n', level);
end
end
end
Run Code Online (Sandbox Code Playgroud)
但这不起作用; 我收到错误(Matlab 2014b):
>> runtests partest
Error using matlab.unittest.TestSuite.fromFile (line 163)
The class partest has no property or method named 'getLevel'.
Run Code Online (Sandbox Code Playgroud)
我可以将getLevel()函数移动到另一个文件,但我想将它保存在一个文件中.
同样在这里(R2015b),看起来TestParameter属性无法通过静态函数调用来初始化......
幸运的是,解决方案非常简单,使用本地函数即可:
classdef partest < matlab.unittest.TestCase
properties (TestParameter)
level = getLevel()
end
methods (Test)
function testModeling(testCase, level)
fprintf('Testing level %d\n', level);
end
end
end
function level = getLevel()
for i=1:100
level.(sprintf('Level%d', i)) = i;
end
end
Run Code Online (Sandbox Code Playgroud)
(请注意,上述所有代码都包含在一个文件中partest.m)。
现在这应该可以工作:
>> run(matlab.unittest.TestSuite.fromFile('partest.m'))
Run Code Online (Sandbox Code Playgroud)
笔记:
作为本地函数,它在类之外不可见。如果您还需要公开它,只需添加一个静态函数作为简单的包装器:
classdef partest < matlab.unittest.TestCase
...
methods (Static)
function level = GetLevelFunc()
level = getLevel();
end
end
end
function level = getLevel()
...
end
Run Code Online (Sandbox Code Playgroud)