Write Simple Test Case Using Functions
This example shows how to write a unit test for a MATLAB function,
quadraticSolver.m.
Create quadraticSolver.m Function
This MATLAB function solves quadratic equations. Create this function in a folder on your
MATLAB path.
function roots = quadraticSolver(a, b, c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2 + b*x + c = 0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputMustBeNumeric', ...
'Coefficients must be numeric.');
end
roots(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a);
roots(2) = (-b - sqrt(b^2 - 4*a*c)) / (2*a);
end
Create solverTest Function
Create this function in a folder on your MATLAB path.
function tests = solverTest
tests = functiontests(localfunctions);
end
A call to functiontests using localfunctions as input creates an array of tests from
each local function in the solverTest.m file. Each test is a local function that follows the
naming convention of having ’test’ at the beginning or end of the function name. Local
functions that do not follow this convention are not included in the test array. Test
functions must accept a single input argument into which the test framework passes a
function test case object. The function uses this object for verifications, assertions,
assumptions, and fatal assertions. It contains a TestData structure that allows data to be
passed between setup, test, and teardown functions.
33 Unit Testing