Code covered by the BSD License  

Highlights from
MATLAB xUnit Test Framework

image thumbnail

MATLAB xUnit Test Framework

by

 

31 Jan 2009 (Updated )

MATLAB xUnit is a unit test framework for MATLAB code.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

MATLAB xUnit Test Framework: How to Write and Run Tests

MATLAB xUnit Test Framework: How to Write and Run Tests

This example shows how to write and run a couple of test cases for the MATLAB fliplr function.

Contents

Make a folder for your tests

To get started, create a folder (directory) that will contain your tests, and then make that your working folder. The test directory in this example is example_quick_start.

cd example_quick_start

Write each test case as a simple M-file

Write each test case as an M-file function that returns no output arguments. The function name should start or end with "test" or "Test". The test case passes if the function runs with no error.

Here's a test-case M-file that verifies the correct output for a vector input.

type testFliplrVector
function testFliplrVector
%testFliplrVector Unit test for fliplr with vector input

in = [1 4 10];
out = fliplr(in);
expected_out = [10 4 1];

if ~isequal(out, expected_out)
    error('testFliplrVector:notEqual', 'Incorrect output for vector.');
end

The function testFliplrVector calls the function being tested and checks the output against the expected output. If the output is different than expected, the function calls error.

Here's another test-case M-file that verifies the correct fliplr output for a matrix input.

type testFliplrMatrix
function testFliplrMatrix
%testFliplrMatrix Unit test for fliplr with matrix input

in = magic(3);
assertEqual(fliplr(in), in(:, [3 2 1]));

This function is simpler than testFliplrVector because it uses the utility testing function assertEqual. assertEqual checks to see whether its two inputs are equal. If they are equal, assertEqual simply returns silently. If they are not equal, assertEqual calls error.

Run all the tests using runtests

To run all your test cases, simply call runtests. runtests automatically finds all the test cases in the current directory, runs them, and reports the results to the Command Window.

runtests
Starting test run with 2 test cases.
..
PASSED in 0.002 seconds.

Back to MATLAB xUnit Test Framework

Contact us