Write Tests Using Shared Fixtures
This example shows how to use shared fixtures when creating tests. You can share test
fixtures across test classes using the SharedTestFixtures attribute of the TestCase
class. To exemplify this attribute, create multiple test classes in a subdirectory of your
current working folder. The test methods are shown only at a high level.
The two test classes used in this example test the DocPolynom class and the
BankAccount class. You can access both classes in MATLAB, but you must add them to
the MATLAB path. A path fixture adds the directory to the current path, runs the tests,
and removes the directory from the path. Since both classes require the same addition to
the path, the tests use a shared fixture.
Create a Test for the DocPolynom Class
Create a test file for the DocPolynom class. Create the shared fixture by specifying the
SharedTestFixtures attribute for the TestCase and passing in a PathFixture.
DocPolynomTest Class Definition File
classdef (SharedTestFixtures={matlab.unittest.fixtures.PathFixture( ...
fullfile(matlabroot,'help','techdoc','matlab_oop','examples'))}) ...
DocPolynomTest < matlab.unittest.TestCase
% Tests the DocPolynom class.
properties
msgEqn = 'Equation under test: ';
end
methods (Test)
function testConstructor(testCase)
p = DocPolynom([1, 0, 1]);
testCase.verifyClass(p, ?DocPolynom)
end
function testAddition(testCase)
p1 = DocPolynom([1, 0, 1]);
p2 = DocPolynom([5, 2]);
actual = p1 + p2;
expected = DocPolynom([1, 5, 3]);
msg = [testCase.msgEqn,...
33 Unit Testing