创建具有复杂属性的参数化Matlab单元测试
我正在尝试创建一个参数化的Matlab unittest,其中创建具有复杂属性的参数化Matlab单元测试,matlab,unit-testing,parameterized-unit-test,Matlab,Unit Testing,Parameterized Unit Test,我正在尝试创建一个参数化的Matlab unittest,其中TestParameter属性由一些代码“动态”生成(例如,使用for循环) 作为一个简化的示例,假设我的代码是 classdef partest < matlab.unittest.TestCase properties (TestParameter) level = struct('level1', 1, 'level2', 2, 'level3', 3, 'level4', 4) end
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
我可以将getLevel()
函数移动到另一个文件中,但我希望将其保存在一个文件中。此处相同(R2015b),它看起来像是无法使用静态函数调用初始化TestParameter
属性
幸运的是,解决方案非常简单,请改用:
partest.m
注意: 作为一个局部函数,它在类外不可见。如果还需要公开它,只需添加一个充当简单包装器的静态函数:
classdef partest < matlab.unittest.TestCase
...
methods (Static)
function level = GetLevelFunc()
level = getLevel();
end
end
end
function level = getLevel()
...
end
classdef partest
我不能运行你的代码,因为我的matlab版本太旧了,但是你可以在你原来的类中尝试level=cell2struct(num2cell(1:n),arrayfun(@(x)(['level',num2str(x)]),1:n,'uni',false),2)
。@Daniel当然我的真实例子更复杂:)我的Java背景很傻,我从未意识到我可以在classdef
中生成本地函数。文档中有一条关于它的条目:这是一个bug:您应该能够通过调用类的静态方法定义TestParameter
。我已经向开发团队报告了这个bug,将在将来的版本中修复。同时,正如Amro所建议的那样,使用本地函数是一个很好的解决办法。@FrankMeulenaar:下面是错误报告:这个错误从R2016b开始已经修复。
>> runtests partest
Error using matlab.unittest.TestSuite.fromFile (line 163)
The class partest has no property or method named 'getLevel'.
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(matlab.unittest.TestSuite.fromFile('partest.m'))
classdef partest < matlab.unittest.TestCase
...
methods (Static)
function level = GetLevelFunc()
level = getLevel();
end
end
end
function level = getLevel()
...
end