how to import package for several tests in unittest framework?

5 views (last 30 days)
Hi,
I've created a TestCase class and I'd like to import StringDiagnostic for each of the test methods in one go - meaning without having to import it for each test desperately.
This is how it looks now:
classdef MyTestClass < matlab.unittest.TestCase
properties(ClassSetupParameter)
prop1 = num2cell(1:2);
end
properties
actual;
expected;
end
methods(TestClassSetup)
get_actual_and_expected(test_case);
end
methods(Test)
function test1(test_case,prop1)
import matlab.unittest.diagnostics.StringDiagnostic;
testCase.verifyNotEmpty(testCase.actual,StringDiagnostic('Struct is empty'));
end
function test2(test_case,prop1)
import matlab.unittest.diagnostics.StringDiagnostic;
testCase.verifyNotEmpty(testCase.expected,StringDiagnostic('Struct is empty'));
end
end
I'd like to not have to write the line "import matlab.unittest.diagnostics.StringDiagnostic;" in each test function but only once.
I've also tried to put in in TestMethodSetup block which didn't work.
Thank you!
Jack

Answers (1)

Andy Campbell
Andy Campbell on 13 Jun 2018
Edited: Andy Campbell on 13 Jun 2018
Hi Jack,
This is currently a limitation in the MATLAB language, which restricts the import scope to functions and methods. There is no way currently to import across an entire "file".
As a workaround, you can use local functions to get import-like behavior, like so:
classdef MyTestClass < matlab.unittest.TestCase
properties(ClassSetupParameter)
prop1 = num2cell(1:2);
end
properties
actual;
expected;
end
methods(TestClassSetup)
get_actual_and_expected(test_case);
end
methods(Test)
function test1(test_case,prop1)
testCase.verifyThat(testCase.actual, ~IsEmpty, StringDiagnostic('Struct is empty'));
end
function test2(test_case,prop1)
testCase.verifyThat(testCase.expected, ~IsEmpty, StringDiagnostic('Struct is empty'));
end
function test3(test_case,prop1)
testCase.verifyThat(testCase.actual, IsEqualTo(testCase.expected), ...
StringDiagnostic('Actual should be equal to expected.'));
end
end
end
% "import" functions
function d = StringDiagnostic(varargin)
d = matlab.unittest.diagnostics.StringDiagnostic(varargin{:});
end
function c = IsEmpty(varargin)
c = matlab.unittest.constraints.IsEmpty(varargin{:});
end
function c = IsEqualTo(varargin)
c = matlab.unittest.constraints.IsEqualTo(varargin{:});
end
Note, in this case though you don't need to import String Diagnostic at all. If you just use:
testCase.verifyNotEmpty(testCase.expected,'Struct is empty');
The string your provided will be converted to a StringDiagnostic automatically by the framework.
Hope that helps!
Andy

Categories

Find more on Testing Frameworks in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!