Main Content

Function-Based Unit Tests

You can test your MATLAB® source code by creating unit tests as local functions in a test file. In a function-based test file, each local test function executes a portion of the software and qualifies the correctness of the produced result. Optionally, your test file can include local fixture functions to specify setup and teardown actions for your tests.

Create Tests

To create function-based tests, write a test file that includes a main function and one or more local functions. Use the local functions to specify your unit tests and optional fixtures.

Note

The name of the test file must start or end with the word “test,” which is case insensitive. If the filename does not start or end with the word “test,” the testing framework might ignore the tests.

For a test file template that includes the signatures of the main, test, and fixture functions, see Test File Template.

Add Main Function

The main function of a function-based test file is responsible for combining all the tests from local test functions into a test array (matlab.unittest.Test array). The name of the main function must correspond to the name of the test file and start or end with the word "test," which is case insensitive.

The main function does not require an input, but it must return the test array as an output. Produce this output using a call to the functiontests function. Because functiontests requires a cell array of function handles as its input, use the localfunctions function to automatically create a cell array of function handles to the local test functions in your file. For example, in a test file named exampleTest.m, implement the main function of the test file.

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

Add Local Test Functions

To create a unit test, add a local test function to the test file. The name of a local test function must start or end with the word “test,” which is case insensitive. The test function must accept a single input, which is represented as testCase in this topic. This input is a matlab.unittest.FunctionTestCase object, which the testing framework automatically creates. The test function uses the object to perform qualifications. For example, these local test functions specify two unit tests. Because unit tests must be independent, the order of the test functions within the test file does not matter.

function test1(testCase)
% Test code
end

function test2(testCase)
% Test code
end

Unit tests typically include qualifications for testing values and responding to failures. For example, to test a function, a unit test can specify the actual and expected returned values of the function and then use a qualification method to test for their equality. For illustrative purposes, the following implementation of the test1 test function tests the plus function. (In practice, you test user-defined code.) The test function calls the verifyEqual qualification method to verify that plus(2,3) produces the expected value 5.

function test1(testCase)
actual = plus(2,3);
expected = 5;
verifyEqual(testCase,actual,expected)
end

For a simple example of how to write and run function-based unit tests, see Write Simple Test Case Using Functions.

Add Local Fixture Functions (Optional)

To set up the pretest state of the system and return it to the original state after testing, you can add file fixtures and fresh fixtures to your test file. 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:

  • File fixture functions — Use file fixture functions to run setup and teardown code a single time for all the tests in the test file. File fixture functions corresponding to the setup and teardown actions must be named as setupOnce and teardownOnce, respectively. The testing framework automatically runs the setupOnce function once before running the first test and the teardownOnce function once after running the last test in the test suite.

  • Fresh fixture functions — Use fresh fixture functions to run setup and teardown code for each individual test in the test file. Fresh fixture functions corresponding to the setup and teardown actions must be named as setup and teardown, respectively. The testing framework automatically runs the setup function before running each test and the teardown function after running each test. In general, it is preferable to use fresh fixtures over file fixtures to increase unit test encapsulation.

Note

If you add code to your test file for setting up the test environment, also include code to restore the environment to its original state by performing teardown actions symmetrically, in the reverse order of their corresponding setup actions.

Like test functions, fixture functions must accept a matlab.unittest.FunctionTestCase object, which the testing framework automatically creates. You can use the TestData property of this object to pass data from setup functions to test or teardown functions. For example, suppose that you need to make changes to the MATLAB path before running your tests. Add the setupOnce function to set the path, and add the teardownOnce function to restore the path to its original state once the test run is complete.

function setupOnce(testCase)  % Do not change function name
testCase.TestData.OriginalPath = path;
addpath("mySource")
end

function teardownOnce(testCase)  % Do not change function name
path(testCase.TestData.OriginalPath)
end

Now suppose that each of your unit tests must have access to a new figure. Add the setup function to obtain a new figure before each test, and add the teardown function to close the figure after testing.

function setup(testCase)  % Do not change function name
testCase.TestData.TestFigure = figure;
end

function teardown(testCase)  % Do not change function name
close(testCase.TestData.TestFigure)
end

For an example of how to use setup and teardown code in function-based tests, see Write Test Using Setup and Teardown Functions.

How Function-Based Tests Run

When you run function-based tests, the testing framework follows these steps:

  1. Create an array of tests that are specified by local test functions.

  2. If the test file includes a setupOnce function, set up the pretest state of the system by running the function.

  3. For each test, run the corresponding local test function. If the test file includes a setup function, run it before running the local test function. If the test file includes a teardown function, run it after running the local test function.

  4. If the test file includes a teardownOnce function, return the system to its original state by running the function.

This diagram summarizes how the testing framework runs the tests.

Run Test and Analyze Results

You can run function-based tests either interactively or programmatically. For example:

  • With the test code visible in the Editor or Live Editor, run the tests from the Run Tests section on the MATLAB Toolstrip. For more information, see Run Tests in Editor.

  • Open the Test Browser app, add the tests to the test bowser, and then run the tests. For more information, see Run Tests Using Test Browser.

  • Run the tests using the runtests function in the Command Window. The function returns the test results as a matlab.unittest.TestResult array. For instance, to run the function-based tests defined in a file named exampleTest.m, execute this statement.

    results = runtests("exampleTest.m");

    For additional ways to run tests programmatically, see Run Tests for Various Workflows.

To analyze the test results, inspect the properties of the TestResult objects. Each TestResult object contains the name of the test function, whether it passed, failed, or did not complete, and the time spent running the test. For more information, see Analyze Test Case Results and Analyze Failed Test Results.

Features of Function-Based Tests

Function-based tests follow the xUnit testing philosophy and give you access to a rich set of test authoring features. With function-based tests, you can:

For more information, see Extend Function-Based Tests.

Test File Template

This code serves as a template for writing function-based tests. To add unit tests, implement the local test functions or add new ones. To add setup and teardown code, implement the fixture functions.

%% Main function to generate tests
function tests = exampleTest
tests = functiontests(localfunctions);
end

%% Local test functions
function test1(testCase)
% Test code
end

function test2(testCase)
% Test code
end

%% Optional file fixtures  
function setupOnce(testCase)  % Do not change function name
% Setup code
end

function teardownOnce(testCase)  % Do not change function name
% Teardown code
end

%% Optional fresh fixtures  
function setup(testCase)  % Do not change function name
% Setup code
end

function teardown(testCase)  % Do not change function name
% Teardown code
end

See Also

Apps

Functions

Classes

Topics