matlab.coverage.Result.generateCoberturaReport - Generate Cobertura XML report from coverage results - MATLAB (original) (raw)
Run a suite of tests and collect the code coverage result. Then, generate a Cobertura XML code coverage report from the result.
In a file named quadraticSolver.m
in your current folder, create the quadraticSolver
function. The function takes as inputs the coefficients of a quadratic polynomial and returns the roots of that polynomial. If the coefficients are specified as nonnumeric values, the function throws an error.
function r = quadraticSolver(a,b,c) % quadraticSolver returns solutions to the % quadratic equation ax^2 + bx + 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 - 4ac)) / (2a); r(2) = (-b - sqrt(b^2 - 4ac)) / (2a);
end
To test the quadraticSolver
function, create the SolverTest
class in a file named SolverTest.m
in your current folder. Define three Test
methods that test the function against real solutions, imaginary solutions, and nonnumeric inputs.
classdef SolverTest < matlab.unittest.TestCase methods (Test) function realSolution(testCase) actSolution = quadraticSolver(1,-3,2); expSolution = [2 1]; testCase.verifyEqual(actSolution,expSolution) end function imaginarySolution(testCase) actSolution = quadraticSolver(1,2,10); expSolution = [-1+3i -1-3i]; testCase.verifyEqual(actSolution,expSolution) end function nonnumericInput(testCase) testCase.verifyError(@()quadraticSolver(1,"-3",2), ... "quadraticSolver:InputMustBeNumeric") end end end
Import the classes used in this example.
import matlab.unittest.plugins.CodeCoveragePlugin import matlab.unittest.plugins.codecoverage.CoverageResult
Create a test suite from the SolverTest
class.
suite = testsuite("SolverTest");
Create a test runner and customize it using a plugin that provides programmatic access to the code coverage information for the source code in the file quadraticSolver.m
.
runner = testrunner("textoutput"); format = CoverageResult; p = CodeCoveragePlugin.forFile("quadraticSolver.m",Producing=format); runner.addPlugin(p)
Run the tests. After the test run, the Result
property of format
holds the coverage result. In this example, all the tests pass and the source code receives full coverage.
Running SolverTest ... Done SolverTest
Generate a Cobertura XML code coverage report from the coverage result and save it as coverageReport.xml
in your current folder.
result = format.Result; filename = "coverageReport.xml"; generateCoberturaReport(result,filename)
You can process the generated code coverage report on continuous integration (CI) platforms. You also can view its contents with commands such as open(filename)
or disp(fileread(filename))
.