Class-based Unit Tests: Running Specific Methods

11 views (last 30 days)
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.

Accepted Answer

Dave B
Dave B on 29 Sep 2021
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 Comment
Randy Price
Randy Price on 30 Sep 2021
Edited: Randy Price on 30 Sep 2021
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.

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 30 Sep 2021
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)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!