MATLAB: How to pass values from inside a TestRunner run

MATLABooptestcasetestrunnerunittest

hi,
I have a class inheriting from matlab.unittest.TestCase. This class runs through various test functions (test1, test2) which utilize matlab's unittest qualification methods. I'm recreating the class and running 'foo' for each idx.
However, I want to run some statistics on the data ITSELF across idx. This means , I need some way of either storing or passing 'MyData' for each run outside.
I thought about saving it locally and using it afterwards, but I would like something built-in.
classdef MyTest < matlab.unittest.TestCase
properties (ClassSetupParameter)
idx = num2cell(1:3);
end
properties
MyData;
end
methods(TestClassSetup)
function runfoo(testCase,idx)
testCase.MyData = foo(testCase,idx);
end
end
methods(Test)
function runtestsonfoo(testCase)
test1(testCase);
test2(testCaes);
end
end
end
Thank you!

Best Answer

You can use a TestRunnerPlugin to store data from the test run. I've included some example code below to show how this might work. The basic outline is as follows:
  1. The test logs information using a Diagnostic subclass and TestCase.log
  2. A plugin listens to the DiagnosticLogged event and stores the logged data on itself
  3. After running the test, you can then access the data on the plugin
Example test code:
classdef MyTest < matlab.unittest.TestCase
properties (ClassSetupParameter)
idx = num2cell(1:3);
end
properties
MyData;
end
methods(TestClassSetup)
function createData(testCase,idx)
testCase.MyData = idx;
testCase.log(4, DataDiagnostic(testCase.MyData));
end
end
methods(Test)
function a(testCase)
end
end
end
Plugin code:
classdef MyPlugin < matlab.unittest.plugins.TestRunnerPlugin
properties(SetAccess=private)
Data = {};
end
methods(Access=protected)
function testCase = createTestClassInstance(plugin, pluginData)
testCase = createTestClassInstance@matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
testCase.addlistener('DiagnosticLogged', @plugin.logDiagnostic);
end
end
methods(Access=private)
function logDiagnostic(plugin, src, evd)
if isa(evd.Diagnostic, 'DataDiagnostic')
plugin.Data{end+1} = evd.Diagnostic.Data;
end
end
end
end
Diagnostic class code:
classdef DataDiagnostic < matlab.unittest.diagnostics.Diagnostic
properties(SetAccess=immutable)
Data;
end
methods
function diag = DataDiagnostic(data)
diag.Data = data;
end
function diagnose(~)
end
end
end
Usage:
>> suite = testsuite('MyTest');
>> runner = matlab.unittest.TestRunner.withTextOutput;
>> plugin = MyPlugin;
>> runner.addPlugin(plugin);
>> runner.run(suite);
Running MyTest
...
Done MyTest
__________
>> plugin.Data
ans =
1×3 cell array
{[1]} {[2]} {[3]}
References: