MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Write Setup and Teardown Code Using Classes


In this section...
“Test Fixtures” on page 33-56
“Test Case with Method-Level Setup Code” on page 33-56
“Test Case with Class-Level Setup Code” on page 33-57

Test Fixtures


Test fixtures are setup and teardown code that sets up the pretest state of the system and
returns it to the original state after running the test. Setup and teardown methods are
defined in the TestCase class by the following method attributes:


  • TestMethodSetup and TestMethodTeardown methods run before and after each
    test method.

  • TestClassSetup and TestClassTeardown methods run before and after all test
    methods in the test case.


The testing framework guarantees that TestMethodSetup and TestClassSetup
methods of superclasses are executed before those in subclasses.

It is good practice for test authors to perform all teardown activities from within the
TestMethodSetup and TestClassSetup blocks using the addTeardown method
instead of implementing corresponding teardown methods in the TestMethodTeardown
and TestClassTeardown blocks. This guarantees the teardown is executed in the
reverse order of the setup and also ensures that the test content is exception safe.

Test Case with Method-Level Setup Code


The following test case, FigurePropertiesTest, contains setup code at the method
level. The TestMethodSetup method creates a figure before running each test, and
TestMethodTeardown closes the figure afterwards. As discussed previously, you should
try to define teardown activities with the addTeardown method. However, for illustrative
purposes, this example shows the implementation of a TestMethodTeardown block.

classdef FigurePropertiesTest < matlab.unittest.TestCase

properties

33 Unit Testing

Free download pdf