Main Content

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 namespaces 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 r = 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

r(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a);
r(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);
        end
    end
    
end

Import TestSuite Class

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.

Create Suite from SolverTest Class

The fromClass method creates a suite from all Test methods in the SolverTest class.

suiteClass = TestSuite.fromClass(?SolverTest);
result = run(suiteClass);

Create Suite from SolverTest Class Definition File

The fromFile method creates a suite using the name of the file to identify the class.

suiteFile = TestSuite.fromFile('SolverTest.m');
result = run(suiteFile);

Create Suite from All Test Case Files in Current Folder

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);

Create Suite from Single Test Method

The fromMethod method creates a suite from a single test method.

suiteMethod = TestSuite.fromMethod(?SolverTest,'testRealSolution')'
result = run(suiteMethod);

See Also

Related Topics