Unittesting Matlab System Block

15 views (last 30 days)
Tim david
Tim david on 23 Feb 2022
Answered: Altaïr on 3 Feb 2025
I want to develop some "Matlab System Blocks". For testing their functionality and debugging their code I would like to Unittest them. The method, that I want to test is the "stepImpl" method of the "Matlab System Block".
Unfortunately the "stepImpl" method is a protected method so I can't Unittest them. I know an alternative is to implement the method in other file as a public method or in the "Matlab System Block" as public Method and use this method in the "stepImpl" Method. I already tried to make the "stepImpl" Method public, but this gave me an error.
However I'm hoping for a better way of Unittesting the "Matlab System Block". Are their any best practises or guidelines?

Answers (1)

Altaïr
Altaïr on 3 Feb 2025
Since the stepImpl function is protected, creating an inherited subclass and using a class-based unit test can be a good approach. Here is an example using the MySystemBlock system block:
classdef MySystemBlock < matlab.System
% Example MATLAB System block that doubles the input value
methods (Access = protected)
function y = stepImpl(obj, x)
y = 2 * x;
end
end
end
The stepImpl method is protected and cannot be tested directly. Therefore, a subclass TestableMySystemBlock can be created:
classdef TestableMySystemBlock < MySystemBlock
methods (Access = public)
function y = testStepImpl(obj, x)
% Directly call the protected stepImpl method
y = stepImpl(obj, x);
end
end
end
A class-based unit test can then be written for this inherited class:
classdef TestMySystemBlockSubclass < matlab.unittest.TestCase
methods (Test)
function testStepImpl(testCase)
% Create an instance of the testable subclass
sysObj = TestableMySystemBlock;
% Define test cases
testInputs = [1, 2, 3, 0, -1, -2];
expectedOutputs = [2, 4, 6, 0, -2, -4];
% Loop through each test case
for i = 1:length(testInputs)
% Call the testStepImpl in the inherited class
actualOutput = sysObj.testStepImpl(testInputs(i));
% Verify the output
testCase.verifyEqual(actualOutput, expectedOutputs(i), ...
'AbsTol', 1e-10, ...
sprintf('Failed for input: %d', testInputs(i)));
end
end
end
end
To run the tests, execute the following commands in the MATLAB Command Window:
resultsSubclassMethod = runtests('TestMySystemBlockSubclass');
disp(resultsSubclassMethod);
For more information on writing unit tests, the following command can be executed in the MATLAB Command Window:
web(fullfile(docroot, 'matlab/matlab_prog/ways-to-write-unit-tests.html'))

Categories

Find more on Create System Objects in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!