MATLAB Examples

Code Coverage Test Generation

This example shows how to use Simulink® Design Verifier™ to generate test cases to obtain complete code coverage.

You first collect code coverage for an example model configured for Software-in-the-Loop (SIL) simulation mode. Then you use Simulink® Design Verifier™ to create a new test suite that generates tests cases to achieve the missing coverage. Finally, you execute the generated test cases in Software-In-the-Loop (SIL) simulation mode to verify the complete coverage.

Contents

Check Product Availability

This example requires valid Simulink® Coder™ and Embedded Coder™ licenses.

if ~(license('test', 'Real-Time_Workshop') && ...
    license('test','RTW_Embedded_Coder'))
    return
end

Initial Setup

Make sure an unedited version of the model is open.

model = 'sldvdemo_cruise_control';
close_system(model, 0)
open_system(model)

Configure the Model to Measure Code Coverage

Before running the simulation, set the model parameters to run in SIL mode and to collect code coverage metrics with Simulink® Coverage™.

set_param(model,...
    'SimulationMode', 'Software-in-the-Loop (SIL)',...
    'SystemTargetFile', 'ert.tlc',...
    'LaunchReport', 'off',...
    'PortableWordSizes', 'on',...
    'CovEnable', 'on');

% Remove any existing build folders.
buildFolder = RTW.getBuildDir(model);
if exist(buildFolder.BuildDirectory, 'dir')
    rmdir(buildFolder.BuildDirectory, 's');
end

Run Simulations in SIL Mode

Collect code coverage results using the cvsim command and produce a coverage report. The cvhtml function produces a coverage report that indicates the initial coverage of the sldvdemo_cruise_control model.

initialCov = cvsim(model);

cvhtml('sil_initial_coverage', initialCov);

Find Test Cases for Missing Coverage

Analyze the sldvdemo_cruise_control model with Simulink® Design Verifier™ to generate a test suite that achieves increased code coverage. Set the Simulink® Design Verifier™ options to generate test cases to achieve MCDC coverage for the top model.

opts = sldvoptions;
opts.TestgenTarget = 'GenCodeTopModel';
opts.Mode = 'TestGeneration';
opts.ModelCoverageObjectives = 'MCDC';
opts.SaveHarnessModel = 'off';
opts.SaveReport = 'off';
[~, files] = sldvrun(model, opts, true, initialCov);

Verify Complete Coverage

The sldvruntest function simulates the model with the generated test suite. The cvhtml function produces a coverage report that indicates the final coverage of the sldvdemo_cruise_control model.

[~, finalCov] = sldvruntest(model, files.DataFile, [], true);
cvhtml('sil_final_coverage', finalCov);
close_system(model, 0);