MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Create Simple Test Suites


This example shows how to combine tests into test suites, using the SolverTest test
case. Use the static from* methods in the matlab.unittest.TestSuite class to
create suites for combinations of your tests, whether they are organized in packages and
classes or files and folders, or both.

Create Quadratic Solver Function

Create the following function that solves roots of the quadratic equation in a file,
quadraticSolver.m, in your working folder.

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 Test for Quadratic Solver Function

Create the following test class in a file, SolverTest.m, in your working folder.

classdef SolverTest < matlab.unittest.TestCase
% SolverTest tests solutions to the quadratic equation
% a*x^2 + b*x + c = 0

methods (Test)
function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2,1];
testCase.verifyEqual(actSolution,expSolution);
end
function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i, -1-3i];
testCase.verifyEqual(actSolution,expSolution);

33 Unit Testing

Free download pdf