MATLAB: How to dynamically set method/class setup parameters

MATLABoopparameterized testunittest

hi,
I'm trying to write a parameterized test where one class setup parameter depends on another one. I'm running it from a script.
myScript.m:
suite = matlab.unittest.TestSuite.fromClass(?myTest)
runner = matlab.unittest.TestRunner.withTextOutput();
results = runner.run(suite);
The test class is defined in a seperate file:
classdef myTest < matlab.unittest.TestCase
properties(ClassSetupParameter)
prop1 = foo();
prop2 = {1,2,3};
prop3 = bar(prop1);
end
end
function foo_result = foo()
foo_result = {3,4,5};
end
function bar_result = bar(prop1)
bar_result = prop1 -1;
end
I'm getting an error:
Error using myScript (line 1)
Invalid default value for property 'prop3' in class 'myTest':
Undefined function or variable 'prop1'.
I have also tried seperating prop1 and prop3 to Class and Method setup parameters:
classdef myTest < matlab.unittest.TestCase
properties(ClassSetupParameter)
prop1 = foo();
prop2 = {1,2,3};
end
properties(MethodSetupParameter)
prop3 = bar(prop1);
end
end
function foo_result = foo()
foo_result = {3,4,5};
end
function bar_result = bar(prop1)
bar_result = prop1 -1;
end
And I'm getting the same error
Any ideas how to overcome this? I really don't want to have another loop inside any test method.
I'm on Matlab 2017a
Thank you! Jack

Best Answer

Try this:
classdef myTest < matlab.unittest.TestCase
properties(ClassSetupParameter)
prop1 = foo();
end
properties
prop3;
end
methods(TestClassSetup)
function setup_prop3(testcase, prop1)
testcase.prop3 = computeProp3FromProp1(prop1);
end
end
methods(Test)
function displayProp3(testcase)
testcase.log(sprintf('The value of prop3 is %d.\n', testcase.prop3));
end
end
end
function y = foo()
y = {3, 4, 5};
end
function y = computeProp3FromProp1(p)
y = p-1;
end
To see that the prop3 property takes on the values 2, 3, and 4 run this with concise logging.
suite = matlab.unittest.TestSuite.fromClass(?myTest)
runner = matlab.unittest.TestRunner.withTextOutput();
L = matlab.unittest.plugins.LoggingPlugin.withVerbosity(matlab.unittest.Verbosity.Concise);
runner.addPlugin(L);
results = runner.run(suite)