Class-based Unit Tests: Running Specific Methods

7 次查看(过去 30 天)
I have a simple class:
MyTest < matlab.unittest.TestCase
If I create an instance of this class and use the run method, it will run every test method in MyTest. I want to run only specific test methods. How can I specify which methods to run?
If I pass all of the names to the run method, e.g. testCase.run('test1', 'test2', ...), then the interpreter complains:
Error using matlab.unittest/Test/fromTestCase
Too many input arguments.
Error in matlab.unittest.internal.RunnableTestContent/run (line 47)
suite = Test.fromTestCase(testCase, varargin{:});
Which seems strange, since it seems like this method is meant to handle a variable number of arguments.

采纳的回答

Dave B
Dave B 2021-9-29
You can use runtests for this:
runtests({'foo/test_first','foo/test_second'})
% - or -
runtests("foo","ProcedureName",["test_first" "test_third"])
classdef foo < matlab.unittest.TestCase
methods (Test)
function test_first(testCase)
end
function test_second(testCase)
end
function test_third(testCase)
end
end
end
  1 个评论
Randy Price
Randy Price 2021-9-30
编辑:Randy Price 2021-9-30
Great - that makes sense.
Now, what if I want to pass arguments to test_first, test_second, etc? For example, an "options" struct, which I'd normally add as a property of the instance of the test class (i.e. testCase.options = ...).
EDIT: Never mind, figured it out. Thanks again.

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2021-9-30
While runtests would be my first choice, you could also create a matlab.unittest.TestSuite object and either use a selector in the from* method that builds the suite or use selectIf on a TestSuite you've created earlier. For this class:
classdef example1463594 < matlab.unittest.TestCase
methods(Test, TestTags = {'positive'})
function test_onePlusOne(testcase)
testcase.verifyEqual(1+1, 2);
end
function test_onePlusTwo(testcase)
testcase.verifyEqual(1+2, 3);
end
end
methods(Test, TestTags = {'negative'})
function test_addIncompatibleSizedArrays(testcase)
testcase.verifyError(@() plus([1 2; 3 4], [1 2 3; 4 5 6; 7 8 9]), ...
'MATLAB:dimagree')
end
end
end
To run the whole test class, all three methods:
S = matlab.unittest.TestSuite.fromFile('example1463594.m') % Selects 3 tests
run(S)
To run just the two test methods with TestTags 'positive':
S2 = selectIf(S, 'Tag', 'positive') % Selects 2 tests
{S2.Name}.' % Show which test methods S2 selected
run(S2)
To run just the one test method whose name matches the pattern test_add*:
S3 = selectIf(S, 'ProcedureName', 'test_add*') % Selects 1 test
run(S3)

类别

Help CenterFile Exchange 中查找有关 Write Unit Tests 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by