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'))
