Creating a parameterized Matlab unittest with complex properties

I am trying to create a parameterized Matlab unittest where TestParameter properties TestParameter generated β€œdynamically” by some code (for example, with a for loop).

As a simplified example, suppose my code

 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 

but in my real code I have 100 levels. I tried putting this in a separate method like

 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 

but it does not work; I get an error (Matlab 2014b):

 >> runtests partest Error using matlab.unittest.TestSuite.fromFile (line 163) The class partest has no property or method named 'getLevel'. 

I could move the getLevel() function to another file, but I would like to save it in one file.

+5
source share
1 answer

Same thing here (R2015b), it looks like the TestParameter property cannot be initialized by calling a static function ...

Fortunately, the solution is quite simple: instead of a local function :

partest.m

 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 

(Note that all of the above code is contained in one partest.m file).

Now this should work:

 >> run(matlab.unittest.TestSuite.fromFile('partest.m')) 

Note

Being a local function, it will not be visible outside the class. If you also need to expose it, just add a static function that acts like a simple wrapper:

 classdef partest < matlab.unittest.TestCase ... methods (Static) function level = GetLevelFunc() level = getLevel(); end end end function level = getLevel() ... end 
+4
source

Source: https://habr.com/ru/post/1242627/


All Articles