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 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 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); end end end
At the command prompt, add the matlab.unittest.TestSuite
class to the current import list.
import matlab.unittest.TestSuite
Make sure the SolverTest
class definition file is on your MATLAB® path.
The fromClass
method creates a suite from all Test
methods in the SolverTest
class.
suiteClass = TestSuite.fromClass(?SolverTest); result = run(suiteClass);
The fromFile
method creates a suite using the name of the file to identify the class.
suiteFile = TestSuite.fromFile('SolverTest.m');
result = run(suiteFile);
The fromFolder
method creates a suite from all test case files in the specified folder. For example, the following files are in the current folder:
BankAccountTest.m
DocPolynomTest.m
FigurePropertiesTest.m
IsSupportedTest.m
SolverTest.m
suiteFolder = TestSuite.fromFolder(pwd); result = run(suiteFolder);
The fromMethod
method creates a suite from a single test method.
suiteMethod = TestSuite.fromMethod(?SolverTest,'testRealSolution')'
result = run(suiteMethod);