Main Content

Types of Code Coverage for MATLAB Source Code

When you run tests, you can collect and access code coverage information for your MATLAB® source code by adding an instance of the CodeCoveragePlugin class to the test runner. As the tests run, the plugin collects information that shows the parts of the source code that were executed by the tests. You can access this information either programmatically or as a code coverage report.

If you create a CodeCoveragePlugin instance using a CoverageResult or CoverageReport format object, the plugin supports the following coverage types, which let you perform a detailed analysis of the source code covered by your tests.

Statement Coverage

Statement coverage identifies the source code statements that execute when the tests run. Use this type of coverage to determine whether every statement in your source code is executed at least once.

To report statement coverage, MATLAB divides the source code into statements that are separated by a comma, semicolon, or newline character. For example, this code has three statements.

b = 1, a = 2 * (b + 10);
x = (b ~= 0) && (a/b > 18.5)

MATLAB divides control flow statements into smaller units for code coverage reporting. For example, in the following control flow statement code, MATLAB reports coverage for these five units: if x > 0, elseif x < 0, and three calls to the disp function. To achieve 100% statement coverage, you need tests that execute each of these units.

if x > 0
    disp("x is positive.")
elseif x < 0
    disp("x is negative.")
else
    disp("x is either zero or NaN.")
end

A keyword followed by an expression forms a unit for which MATLAB reports statement coverage. Among keywords that do not require an expression, MATLAB reports coverage for break, catch, continue, return, and try. It ignores keywords such as else, end, and otherwise.

In general, MATLAB reports coverage for statements that perform some action on program data or affect the flow of the program. It ignores code that defines functions, classes, or class members, such as function [y1,...,yN] = myfun(x1,...,xM) or classdef MyClass.

Function Coverage

Function coverage identifies the functions defined in the source code that execute when the tests run. Use this type of coverage to determine whether every function in your source code was called at least once.

For example, this code contains three defined functions: f, root, and square. To achieve 100% function coverage, you need tests that result in each of these functions being called.

function f(x)
if x >= 0
    root
else
    square
end
disp(x)

    function root
        x = sqrt(x);
    end
    function square
        x = x.^2;
    end
end

See Also

Classes

Related Topics