Main Content

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

Create a Test for the BankAccount Class

Create a test file for the BankAccount class. Create the shared fixture by specifying the SharedTestFixtures attribute for the TestCase and passing in a PathFixture.

 BankAccountTest Class Definition File

Build the Test Suite

The classes DocPolynomTest.m and BankAccountTest.m are in your working directory. Create a test suite from your current working directory. If you have additional tests, they are included in the suite when you use the TestSuite.fromFolder method. Create the test suite at the command prompt.

import matlab.unittest.TestSuite;
suiteFolder = TestSuite.fromFolder(pwd);

Run the Tests

At the command prompt, run the tests in the test suite.

result = run(suiteFolder);
Setting up PathFixture.
Description: Adds 'C:\Program Files\MATLAB\R2013b\help\techdoc\matlab_oop\examples' to the path.
__________

Running BankAccountTest
.....
Done BankAccountTest
__________

Running DocPolynomTest
...
Done DocPolynomTest
__________

Tearing down PathFixture.
Description: Restores the path to its previous state.
__________

The testing framework sets up the test fixture, runs all the tests in each file, and then tears the fixture down. If the path fixture was set up and torn down using TestClassSetup methods, the fixture is set up and torn down twice—once for each test file.

See Also

| |