Write Function-Based Unit Tests
In this section...
“Create Test Function” on page 33-25
“Run the Tests” on page 33-28
“Analyze the Results” on page 33-28
Create Test Function
Your test function is a single MATLAB file that contains a main function and your
individual local test functions. Optionally, you can include file fixture and fresh fixture
functions. File fixtures consist of setup and teardown functions shared across all the tests
in a file. These functions are executed once per test file. Fresh fixtures consist of setup
and teardown functions that are executed before and after each local test function.
Create the Main Function
The main function collects all of the local test functions into a test array. Since it is the
main function, the function name corresponds to the name of your .m file and follows the
naming convention of starting or ending in the word ‘test’, which is case-insensitive. In
this sample case, the MATLAB file is exampleTest.m. The main function needs to make a
call to functiontests to generate a test array, tests. Use localfunctions as the
input to functiontests to automatically generate a cell array of function handles to all
the local functions in your file. This is a typical main function.
function tests = exampleTest
tests = functiontests(localfunctions);
end
Create Local Test Functions
Individual test functions are included as local functions in the same MATLAB file as the
main (test-generating) function. These test function names must begin or end with the
case-insensitive word, ‘test’. Each of the local test functions must accept a single input,
which is a function test case object, testCase. The Unit Test Framework automatically
generates this object. For more information on creating test functions, see “Write Simple
Test Case Using Functions” on page 33-30 and “Types of Qualifications” on page 33-60.
This is a typical example of skeletal local-test functions.
Write Function-Based Unit Tests