how to import package for several tests in unittest framework?

조회 수: 3 (최근 30일)
Jack German
Jack German 2018년 6월 10일
편집: Andy Campbell 2018년 6월 13일
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

답변 (1개)

Andy Campbell
Andy Campbell 2018년 6월 13일
편집: Andy Campbell 2018년 6월 13일
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

카테고리

Help CenterFile Exchange에서 Testing Frameworks에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by