I am trying to implement a basic testing framework in Matlab as my first attempt at Test-Driven-Development. One of the tests I am trying to create is intended to verify that my function throws a specific warning under certain input conditions. My code is passing the warning-related tests as intended, however there is a huge annoyance.
When running (and passing) tests involving the "assertWarning" or "verifyWarning" functions, the warnings that are supposed to be triggered are printed to the command window and visually disrupt the printout of my test suite. Is there a way to prevent the (desired) warning from printing to the console only when being run in the tests, while still verifying that the warning is triggered? A sample test function which causes this annoying warning printout is below.
function testAcceleratorMax(testCase)
% Validate that acceleration input is forced to be <=1 and throws warning
state = [0,0,0,0]; input = [2,0];
xd = getPointMass2D_dot(state,input);
assert(isequal(xd,[0,0,1,0]),'Acceleration not ceiled correctly');
verifyWarning(testCase,@(x) getPointMass2D_dot(state,input),...
'MATLAB:CommandedAccelOutOfBounds');
end
While it may not be the most elegant solution, I have found a much less intrusive method!
Step 1: Turn the specific warnings you are deliberately triggering to off in the test suite setup function. You could also do this and step 2 within each test function individually if needed. Even when the warning is turned off and won't print to the command window, you can access the suppressed warning using "lastwarn".
function setup(testCase)
warning('off','MATLAB:CommandedAccelOutOfBounds');
warning('off','MATLAB:CommandedSteerOutOfBounds');
end
Step 2: Turn the specific warnings back on in the test suite teardown function to reset matlab to the correct state after running the test suite.
function teardown(testCase)
warning('on','MATLAB:CommandedAccelOutOfBounds');
warning('on','MATLAB:CommandedSteerOutOfBounds');
end
Step 3: Instead of using the "verifyWarning" or "assertWarning" functions for your test, use "lastwarn" and "strcmp".
function testAcceleratorMax(testCase)
% Validate that acceleration input is forced to be <=1 and throws warning
state = [0,0,0,0]; input = [2,0];
xd = getPointMass2D_dot(state,input);
assert(isequal(xd,[0,0,1,0]),'Acceleration not ceiled correctly');
[~,warnID] = lastwarn; % Gets last warning, even though it was "off"
assert(strcmp(warnID,'MATLAB:CommandedAccelOutOfBounds'), 'Correct warning not thrown')
end