MATLAB Answers

BdS
0

How to unit test with verifyWarning?

Asked by BdS
on 8 Nov 2018
Latest activity Answered by Steven Lord
on 8 Nov 2018
Hello, I am trying to apply the function verifyWarning on the following function: function [adjdate] = AdjStartDate(startDate) if ~strcmp(startDate,datestr(datetime('01-Feb-2000','InputFormat','dd-MMM-yyyy'),'yyyy-mm-dd')) adjdate=datestr(datetime('01-Feb-2000','InputFormat','dd-MMM-yyyy'),'yyyy-mm-dd'); warning('DATE:StartDateChanged','Start date has been modified'); else adjdate=startDate; end
My test function looks like this: % test if the function issues a warning ----- function testYesWarning(testCase) verifyWarning(testCase,@() testYesWarning('2000-01-01'),'DATE:StartDateChanged') end
However, the test result is negativ:
--------- Error ID: --------- 'MATLAB:UndefinedFunction'
--------------
Error Details:
--------------
Undefined function 'verifyWarning' for input arguments of type 'function_handle'.
I would appreciate your assistance. Thank you in advance.

  1 Comment

Jan
on 8 Nov 2018
@BdS: Please format your code properly. See How to format code in the forum.

Sign in to comment.

2 Answers

Answer by Jan
on 8 Nov 2018

You did not post how testCase is defined in your case. According to the error message it is a function handle, but the command verifyWarning expects a matlab.unittest.TestCase instance.
The function AdjStartDate is not called anywhere in the shown code, but what testYesWarning calls itself recursively with the argument '2000-01-01' as testCase.

  0 Comments

Sign in to comment.


Answer by Steven Lord
on 8 Nov 2018

Your test function is:
function testYesWarning(testCase)
verifyWarning(testCase,@() testYesWarning('2000-01-01'),'DATE:StartDateChanged')
end
You should not call verifyWarning on a function handle to the test function itself. If that hadn't failed (if you'd tried to verify that testYesWarning(testCase) issues a warning, for example) you would have received an error about the recursion limit. As it is, the second time testYesWarning is called testCase is a char array.
Because of MATLAB precedence rules, MATLAB tries to find a verifyWarning function that is defined for function handles. But verifyWarning is only defined for test case objects. MATLAB will create and pass a test case object into your test function when you run the test, assuming your test is a Test method in a test class or the main function in your function-based test is written like the main function shown on this documentation page. This is why the test fails only the second time testYesWarning is called, when it is called by verifyWarning evaluating the anonymous function.
You're testing the AdjStartDate function, so call it in your verifyWarning statement.
function testYesWarning(testCase)
verifyWarning(testCase,@() AdjStartDate('2000-01-01'),'DATE:StartDateChanged')
end

  0 Comments

Sign in to comment.