Main Content

Write Test Using Setup and Teardown Functions

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

Create axesPropertiesTest.m File

Create a file containing the main function that tests figure properties and include two test functions. One function verifies that thex-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, createaxesPropertiesTest.m. In the main function of this file, havefunctiontestscreate an array of tests from each local function inaxesPropertiesTest.mwith a call to thelocalfunctionsfunction.

functiontests = 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 toaxesPropertiesTest. 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 toaxesPropertiesTest.

functionf = createFigure f = figure; ax = axes('Parent',f); cylinder(ax,10) h = findobj(ax,'Type','surface'); h.FaceColor = [1 0 0];end

You must name the setup and teardown functions of a file test fixturesetupOnceandteardownOnce, respectively. These functions take a single input argumenttestCaseinto which the testing framework automatically passes a function test case object. This test case object contains aTestDatastructure that allows data to pass between setup, test, and teardown functions. In this example, theTestDatastructure uses assigned fields to store the original path, the temporary folder name, and the figure file name.

Create the setup and teardown functions as local functions toaxesPropertiesTest.

functionsetupOnce(testCase)% Create and change to temporary foldertestCase.TestData.origPath = pwd; testCase.TestData.tmpFolder ="tmpFolder"+...string(datetime('now','Format',“名称不'HHmmss”)); mkdir(testCase.TestData.tmpFolder) cd(testCase.TestData.tmpFolder)% Create and save a figuretestCase.TestData.figName ='tmpFig.fig'; aFig = createFigure; saveas(aFig,testCase.TestData.figName) close(aFig)endfunctionteardownOnce(testCase) delete(testCase.TestData.figName) cd(testCase.TestData.origPath) rmdir(testCase.TestData.tmpFolder)end

Create Fresh Fixture Functions

Fresh fixtures are function-level setup and teardown code that runs before and after each test function in your file. In this example, the functions open the saved figure and find the handles. After testing, the framework closes the figure.

You must name fresh fixture functionssetupandteardown, respectively. Similar to the file fixture functions, these functions take a single input argumenttestCase. In this example, these functions create a new field in theTestDatastructure that includes handles to the figure and to the axes. This allows information to pass between setup, test, and teardown functions.

Create the setup and teardown functions as local functions toaxesPropertiesTest. Open the saved figure for each test to ensure test independence.

functionsetup(testCase) testCase.TestData.Figure = openfig(testCase.TestData.figName); testCase.TestData.Axes = findobj(testCase.TestData.Figure,...'Type','Axes');endfunctionteardown(testCase) close(testCase.TestData.Figure)end

In addition to custom setup and teardown code, the testing framework provides some classes for creating fixtures. For more information, seematlab.unittest.fixtures.

Create Test Functions

Each test is a local function that follows the naming convention of having ‘test’ at the beginning or end of the function name. The test array does not include local functions that do not follow this convention. Similar to setup and teardown functions, individual test functions must accept a single input argumenttestCase. Use this test case object for verifications, assertions, assumptions, and fatal assertions.

ThetestDefaultXLimfunction verifies that the x-axis limits are large enough to display the cylinder. The lower limit needs to be less than-10, and the upper limit needs to be greater than10. These values come from the figure generated in the helper function — a cylinder with a10unit radius centered on the origin. This test function opens the figure created and saved in thesetupOncefunction, queries the axes limit, and verifies the limits are correct. The qualification functionsverifyLessThanOrEqualandverifyGreaterThanOrEqualtake as inputs the test case, the actual value, the expected value, and optional diagnostic information to display in the case of failure.

Create thetestDefaultXLim作为本地函数axesPropertiesTest.

functiontestDefaultXLim(testCase) xlim = testCase.TestData.Axes.XLim; verifyLessThanOrEqual(testCase,xlim(1),-10,...'Minimum x-limit was not small enough') verifyGreaterThanOrEqual(testCase,xlim(2),10,...'Maximum x-limit was not large enough')end

ThesurfaceColorTestfunction accesses the figure that you created and saved in thesetupOncefunction.surfaceColorTestqueries the face color of the cylinder and verifies that it is red. The color red has an RGB value of[1 0 0]. The qualification functionverifyEqualtakes as inputs the test case, the actual value, the expected value, and optional diagnostic information to display in the case of failure. Typically when usingverifyEqualon floating-point values, you specify a tolerance for the comparison. For more information, seematlab.unittest.constraints.

Create thesurfaceColorTest作为本地函数axesPropertiesTest.

functionsurfaceColorTest(testCase) h = findobj(testCase.TestData.Axes,'Type','surface'); co = h.FaceColor; verifyEqual(testCase,co,[1 0 0],'Face color is incorrect')end

Now theaxesPropertiesTest.mfile is complete with a main function, a helper function, file fixture functions, fresh fixture functions, and two test functions. You are ready to run the tests.

Run Tests

The next step is to run the tests using theruntestsfunction. In this example, the call toruntestsresults in the following steps:

  1. The main function creates a test array.

  2. The file fixture setup records the working folder, creates a temporary folder, sets the temporary folder as the working folder, then generates and saves a figure.

  3. The fresh fixture setup opens the saved figure and finds the handles.

  4. ThetestDefaultXLimtest runs.

  5. The fresh fixture teardown closes the figure.

  6. The fresh fixture setup opens the saved figure and finds the handles.

  7. ThesurfaceColorTesttest runs.

  8. The fresh fixture teardown closes the figure.

  9. The file fixture teardown deletes the saved figure, changes back to the original path, and deletes the temporary folder.

At the command prompt, generate and run the test suite.

results = runtests('axesPropertiesTest.m')
Running axesPropertiesTest .. Done axesPropertiesTest __________
results = 1×2 TestResult array with properties: Name Passed Failed Incomplete Duration Details Totals: 2 Passed, 0 Failed, 0 Incomplete. 0.5124 seconds testing time.

Create Table of Test Results

To access functionality available to tables, create one from theTestResultobjects.

rt = table(results)
rt=2×6 table名字传递失败的不完整的时间细节_______________________________________ ______ ______ __________ ________ ____________ {'axesPropertiesTest/testDefaultXLim' } true false false 0.35239 {1×1 struct} {'axesPropertiesTest/surfaceColorTest'} true false false 0.16001 {1×1 struct}

Sort the test results by increasing duration.

sortrows(rt,'Duration')
ans=2×6 table名字传递失败的不完整的时间细节_______________________________________ ______ ______ __________ ________ ____________ {'axesPropertiesTest/surfaceColorTest'} true false false 0.16001 {1×1 struct} {'axesPropertiesTest/testDefaultXLim' } true false false 0.35239 {1×1 struct}

Export the test results to an Excel® spreadsheet.

writetable(rt,'myTestResults.xls')

See Also

|

Related Topics