TExcelTAD
Home › MATLAB / Octave › Unit Testing

Unit Testing

A unit test is a small piece of code that calls one function with known inputs and checks that the result is what you expect. A collection of tests lets you change code with confidence: run them after every change, and if they all still pass, you haven't broken anything they cover.

Approach Runs in Good for
assert-based test functions + a small runner MATLAB and Octave Learning, small projects, portable code
matlab.unittest (function- or class-based tests, runtests) MATLAB Real projects: reports, fixtures, CI integration
%!test blocks inside function files Octave Tests that live next to the code they test

The function under test

All examples test this small function, saved in its own file:

matlab · try it yourself
fprintf('%g\n', to_fahrenheit([0 100 -40]));

% --- file: to_fahrenheit.m
function f = to_fahrenheit(c)
%TO_FAHRENHEIT  Convert degrees Celsius to Fahrenheit.
if ~isnumeric(c)
    error('temp:notNumeric', 'Input must be numeric.');
end
if any(c(:) < -273.15)
    error('temp:belowZero', 'Temperature below absolute zero.');
end
f = c * 9/5 + 32;
end
32
212
-40

Tests with assert

The simplest test is an assert that fails loudly when a condition is false. Give each check a message that says what was expected:

matlab · try it yourself
assert(to_fahrenheit(0) == 32, 'freezing point should be 32 F');
assert(to_fahrenheit(100) == 212, 'boiling point should be 212 F');
assert(isequal(size(to_fahrenheit(zeros(2, 3))), [2 3]), 'shape must be kept');
disp('all checks passed')

% --- file: to_fahrenheit.m
function f = to_fahrenheit(c)
if ~isnumeric(c)
    error('temp:notNumeric', 'Input must be numeric.');
end
if any(c(:) < -273.15)
    error('temp:belowZero', 'Temperature below absolute zero.');
end
f = c * 9/5 + 32;
end
all checks passed

Two details matter for numerical code:

  • Compare floating-point results with a tolerance, not ==: abs(actual - expected) < 1e-10. Results that are mathematically equal often differ in the last bits.
  • Use isequal for arrays. assert(a == b) on arrays checks only that all elements are equal, and errors if the sizes differ; isequal handles both cleanly.

(Octave's assert also accepts assert(observed, expected, tol) and prints a detailed table on failure, but MATLAB's assert only takes a condition and a message, so the portable form is assert(condition, message).)

A tiny test runner

Stopping at the first failing assert hides the other failures. A runner calls every test function, catches failures, and prints a summary. Each test is a local function; the runner receives a cell array of handles to them:

matlab · try it yourself
tests = {@test_freezing, @test_body_temperature, @test_vector_input, ...
         @test_rejects_text, @test_rejects_too_cold, @test_deliberately_wrong};
run_tests(tests);

function run_tests(tests)
passed = 0;
for k = 1:numel(tests)
    name = func2str(tests{k});
    try
        tests{k}();
        passed = passed + 1;
        fprintf('PASS  %s\n', name);
    catch err
        fprintf('FAIL  %s: %s\n', name, err.message);
    end
end
fprintf('%d of %d tests passed\n', passed, numel(tests));
end

function test_freezing()
assert(to_fahrenheit(0) == 32, 'expected 32');
end

function test_body_temperature()
f = to_fahrenheit(37);
assert(abs(f - 98.6) < 1e-10, 'expected 98.6, got %.15g', f);
end

function test_vector_input()
assert(isequal(to_fahrenheit([-40 0 100]), [-40 32 212]), 'vector conversion is wrong');
end

function test_rejects_text()
expect_error(@() to_fahrenheit('hot'), 'temp:notNumeric');
end

function test_rejects_too_cold()
expect_error(@() to_fahrenheit(-300), 'temp:belowZero');
end

function test_deliberately_wrong()
% A failing test, to show what a failure looks like
assert(to_fahrenheit(10) == 51, 'expected 51, got %g', to_fahrenheit(10));
end

function expect_error(fn, expected_id)
% Passes only if fn() raises an error with the given identifier.
try
    fn();
catch err
    assert(strcmp(err.identifier, expected_id), ...
           'expected error %s, got %s', expected_id, err.identifier);
    return
end
error('test:noError', 'expected error %s, but none was raised', expected_id);
end

% --- file: to_fahrenheit.m
function f = to_fahrenheit(c)
if ~isnumeric(c)
    error('temp:notNumeric', 'Input must be numeric.');
end
if any(c(:) < -273.15)
    error('temp:belowZero', 'Temperature below absolute zero.');
end
f = c * 9/5 + 32;
end
PASS  test_freezing
PASS  test_body_temperature
PASS  test_vector_input
PASS  test_rejects_text
PASS  test_rejects_too_cold
FAIL  test_deliberately_wrong: expected 51, got 50
5 of 6 tests passed

expect_error shows how to test the error paths: calling the function with bad input must raise the right error. Testing by identifier rather than message keeps the test stable when the wording changes (see Error Handling).

Table-driven tests

When many inputs exercise the same logic, list them in a table of cases and loop. Adding a case is then one line:

matlab · try it yourself
cases = [
%   input   expected
    -40     -40
      0      32
     20      68
     37      98.6
    100     212
];
failures = 0;
for k = 1:size(cases, 1)
    actual = to_fahrenheit(cases(k, 1));
    if abs(actual - cases(k, 2)) > 1e-9
        fprintf('case %d: to_fahrenheit(%g) = %g, expected %g\n', ...
                k, cases(k, 1), actual, cases(k, 2));
        failures = failures + 1;
    end
end
fprintf('%d cases, %d failures\n', size(cases, 1), failures);

% --- file: to_fahrenheit.m
function f = to_fahrenheit(c)
f = c * 9/5 + 32;
end
5 cases, 0 failures

The MATLAB unit test framework

MATLAB's matlab.unittest framework adds test discovery, detailed failure reports, setup/teardown, and integration with continuous-integration servers. It has two styles.

Function-based tests: a file whose main function collects its local test functions. Each test receives a testCase object and uses verify* methods:

matlab
% File: test_to_fahrenheit.m
function tests = test_to_fahrenheit
tests = functiontests(localfunctions);
end

function test_freezing(testCase)
verifyEqual(testCase, to_fahrenheit(0), 32);
end

function test_body_temperature(testCase)
verifyEqual(testCase, to_fahrenheit(37), 98.6, 'AbsTol', 1e-10);
end

function test_rejects_text(testCase)
verifyError(testCase, @() to_fahrenheit('hot'), 'temp:notNumeric');
end

Class-based tests: a class that inherits from matlab.unittest.TestCase, with test methods in a methods (Test) block. This style supports shared fixtures and parameterised tests:

matlab
% File: TemperatureTest.m
classdef TemperatureTest < matlab.unittest.TestCase
    methods (Test)
        function boilingPoint(testCase)
            testCase.verifyEqual(to_fahrenheit(100), 212);
        end
        function keepsShape(testCase)
            testCase.verifySize(to_fahrenheit(zeros(2, 3)), [2 3]);
        end
    end
end

runtests finds and runs them (a file, a folder, or the whole project), and table(results) summarises the outcome:

matlab
>> results = runtests({'test_to_fahrenheit', 'TemperatureTest'});
Running test_to_fahrenheit
...
Done test_to_fahrenheit
__________

Running TemperatureTest
..
Done TemperatureTest
__________

>> disp(results)
  1×5 TestResult array with properties:

    Name
    Passed
    Failed
    Incomplete
    Duration
    Details

Totals:
   5 Passed, 0 Failed, 0 Incomplete.
   0.042 seconds testing time.

(MATLAB output, sample timing. Octave 11 has no matlab.unittest, functiontests or runtests.)

The framework offers four families of checks, differing in what happens on failure:

Prefix On failure Use for
verify* Records the failure and continues the test Most checks
assert* Stops the current test Checks later code depends on
fatalAssert* Stops the whole test run Broken environment
assume* Marks the test as skipped (incomplete) Missing prerequisites

Common ones: verifyEqual (with 'AbsTol'/'RelTol'), verifyTrue, verifyError, verifyWarning, verifySize, verifyClass, verifyEmpty.

Tests inside Octave function files

Octave has its own lightweight system: special comment blocks at the end of a function file, which MATLAB ignores as ordinary comments. Run them with test to_fahrenheit:

matlab
% At the end of to_fahrenheit.m (Octave only)
%!assert (to_fahrenheit (0), 32)
%!assert (to_fahrenheit (37), 98.6, 1e-10)
%!test
%! f = to_fahrenheit ([-40 100]);
%! assert (f, [-40 212]);
%!error <numeric> to_fahrenheit ('hot')
text
>> test to_fahrenheit
PASSES 4 out of 4 tests

(Octave output.) Octave's own functions are tested this way.

Writing good tests

  • One behaviour per test, named after what it checks: test_rejects_text tells you what broke without reading the code.
  • Cover the edges: empty input, a single element, negative numbers, NaN, the boundaries of valid ranges, and invalid input that must raise errors.
  • Deterministic: no unseeded random numbers, no dependence on the current time or on other tests having run first.
  • Fast: tests that run in a second get run often.
  • Every bug becomes a test. When you fix a bug (see Debugging), add the failing case first; it guards against the bug coming back.

Learn more: Input Validation for the errors these tests check, and Writing Functions for designing functions that are easy to test (inputs in, outputs out, no printing).

Test yourself

Why should a test of 0.1 * 3 compare against 0.3 with a tolerance?

  1. MATLAB rounds to 4 digits
  2. Floating-point results that are mathematically equal can differ in the last bits
  3. == doesn't work on decimals
  4. Tolerances make tests faster

In matlab.unittest, how does verifyEqual differ from assertEqual when the check fails?

  1. There is no difference
  2. verify records the failure and continues the test; assert stops the test
  3. verify stops the whole run
  4. assert skips the test

What should a test for invalid input check?

  1. That the function prints a message
  2. That the function raises the expected error, ideally by identifier
  3. That the function returns 0
  4. Nothing; invalid input can't be tested