Main Content

Write Unit Tests

Write tests using scripts, functions, or classes; apply fixtures; parameterize tests

Write tests using the MATLAB® unit testing framework to check that the outputs of MATLAB scripts, functions, or classes are as you expect. For example, you can test that actual output values match expected values, or you can test that outputs have the expected size and type.

The unit testing framework lets you write tests using scripts, functions, or classes:

  • Script-based tests provide basic test authoring functionality. You can perform basic qualifications by using the assert function in your test scripts.

  • Function-based tests follow the xUnit testing philosophy and provide extensive test authoring functionality. For example, you can use advanced qualification capabilities, including constraints, tolerances, and test diagnostics.

  • Class-based tests give you access to the full framework functionality. For example, you can use shared test fixtures, parameterize tests, and reuse test content.

For more information, see Ways to Write Unit Tests.

Functions

assertThrow error if condition false
functiontestsCreate array of tests from handles to local functions

Classes

matlab.unittest.FunctionTestCaseTest case for function-based tests
matlab.unittest.TestCaseSuperclass of all test classes
matlab.automation.diagnostics.DiagnosticFundamental interface for diagnostics
matlab.automation.VerbosityVerbosity level enumeration class

Namespaces

matlab.unittestSummary of classes and namespaces in MATLAB unit testing framework
matlab.unittest.constraintsSummary of classes in MATLAB constraints interface
matlab.unittest.fixturesSummary of classes in MATLAB fixtures interface
matlab.unittest.parametersSummary of classes associated with MATLAB unit testing parameters
matlab.unittest.qualificationsSummary of classes in MATLAB qualifications interface

Topics

Write Class-Based Tests

Write Parameterized Tests

Write Function-Based Tests

  • Function-Based Unit Tests
    A 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.
  • Write Simple Test Case Using Functions
    Write function-based unit tests to determine the correctness of your program.
  • Write Test Using Setup and Teardown Functions
    Write a function-based test with setup and teardown functions that run once in your test file and before and after each test function in the file.
  • Extend Function-Based Tests
    Access additional functionality using function-based tests, including application of fixtures, test selection, programmatic access of test diagnostics, and test runner customization.

Write Script-Based Tests