MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Write Test Using Setup and Teardown Functions


This example shows how to write a unit test for a couple of MATLAB® figure axes
properties using fresh fixtures and file fixtures.

Create axesPropertiesTest File

Create a file containing the main function that tests figure axes properties and include
two test functions. One function verifies that the x-axis limits are correct, and the other
one verifies that the face color of a surface is correct.

In a folder on your MATLAB path, create axesPropertiesTest.m. In the main function
of this file, have functiontests create an array of tests from each local function in
axesPropertiesTest.m with a call to the localfunctions function.

% Copyright 2015 The MathWorks, Inc.

function tests = axesPropertiesTest
tests = functiontests(localfunctions);
end

Create File Fixture Functions

File fixture functions are setup and teardown code that runs a single time in your test file.
These fixtures are shared across the test file. In this example, the file fixture functions
create a temporary folder and set it as the current working folder. They also create and
save a new figure for testing. After tests are complete, the framework reinstates the
original working folder and deletes the temporary folder and saved figure.

In this example, a helper function creates a simple figure — a red cylinder. In a more
realistic scenario, this code is part of the product under test and is computationally
expensive, thus motivating the intent to create the figure only once and to load
independent copies of the result for each test function. For this example, however, you
want to create this helper function as a local function to axesPropertiesTest. Note
that the test array does not include the function because its name does not start or end
with ‘test’.

Write a helper function that creates a simple red cylinder and add it as a local function to
axesPropertiesTest.

Write Test Using Setup and Teardown Functions
Free download pdf