This example shows how to analyze the information returned by a test runner created from the SolverTest
test case.
Create the following function that solves roots of the quadratic equation in a file, quadraticSolver.m
, in your working folder.
type quadraticSolver.m
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.
type SolverTest.m
classdef SolverTest < matlab.unittest.TestCase 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 function testNonNumericInput(testCase) testCase.verifyError(@()quadraticSolver(1,'-3',2), ... 'quadraticSolver:InputMustBeNumeric') end end end
SolverTest
Test CaseCreate a test suite, quadTests
.
quadTests = matlab.unittest.TestSuite.fromClass(?SolverTest); result = run(quadTests);
Running SolverTest ... Done SolverTest __________
All tests passed.
result
The output argument, result
, is a matlab.unittest.TestResult
object. It contains information of the two tests in SolverTest
.
whos result
Name Size Bytes Class Attributes result 1x3 7277 matlab.unittest.TestResult
To see the information for one value, type:
result(1)
ans = TestResult with properties: Name: 'SolverTest/testRealSolution' Passed: 1 Failed: 0 Incomplete: 0 Duration: 0.3695 Details: [1x1 struct] Totals: 1 Passed, 0 Failed, 0 Incomplete. 0.3695 seconds testing time.
To access functionality available to tables, create one from the TestResult
object.
rt = table(result)
rt=3×6 table
Name Passed Failed Incomplete Duration Details
____________________________________ ______ ______ __________ ________ ____________
{'SolverTest/testRealSolution' } true false false 0.3695 {1x1 struct}
{'SolverTest/testImaginarySolution'} true false false 0.014128 {1x1 struct}
{'SolverTest/testNonNumericInput' } true false false 0.15644 {1x1 struct}
Sort the test results by duration.
sortrows(rt,'Duration')
ans=3×6 table
Name Passed Failed Incomplete Duration Details
____________________________________ ______ ______ __________ ________ ____________
{'SolverTest/testImaginarySolution'} true false false 0.014128 {1x1 struct}
{'SolverTest/testNonNumericInput' } true false false 0.15644 {1x1 struct}
{'SolverTest/testRealSolution' } true false false 0.3695 {1x1 struct}
Export test results to a CSV file.
writetable(rt,
'myTestResults.csv'
,
'QuoteStrings'
,true)