MATLAB: How to use Matlab’s unit test framework component verifyError to verify an error from a MEX function

MATLABmexverifyerror

Let's say I've written a MEX function, foo, that when given the number 5 throws an error.
Inside the mex function, the code would look something like:
if (inputValue == 5)
{
char errMsg[250];
sprintf_s(errMsg, "ERROR: input was %d, and so I'll throw an error", inputValue);
mexErrMsgTxt(errMsg);
}
Now, if I call foo(5), this error will be thrown.
I cannot seem to figure out how to write a unit test to verify this!
function Verify_Foo_Throws_Error(testCase)
err_msg = 'ERROR';
testCase.verifyError(@()foo(5), err_msg);
end % Verify_Foo_Throws_Error()
I cannot seem to substitute anything in for the 'err_msg' variable in my example to get the test to pass!
Interestingly enough, when err_msg has some string, the test throws the feedback:
Actual Identifier:
''
Expected Identifier:
ERROR (<- whatever the value of the variable 'err_msg' is from my example)
Yet when I make err_msg an empty string, the test fails as incomplete with the messages:
================================================================================
Uncaught error occurred in Foo_Test/Verify_Foo_Throws_Error.
The remainder of the test method will not run to completion.
--------------
Error Details:
--------------
Error using matlab.unittest.constraints.Throws (line 161)
Expected exception to be a row vector.
Error in matlab.unittest.internal.qualifications.QualificationDelegate/qualifyError (line 152)
throws = delegate.decorateConstraintAlias(Throws(errorClassOrID),'Error');
Error in matlab.unittest.qualifications.Verifiable/verifyError (line 687)
qualifyError(verifiable.VerificationDelegate, ...
Error in Foo_Test/Verify_Foo_Throws_Error (line 138)
testCase.verifyError(@()foo(5), err_msg);
================================================================================
Any assistance would be most appreciated. Thanks!

Best Answer

Hi Vincent,
The verifyError function requires that the error thrown is an error with an error identifier. The identifier argument described in the verifyError documentation is not the error message but is rather this error identifier.
In order to test against this error, you'll need to change the mex file's implementation to use mexErrMsgIdAndTxt instead of mexErrMsgTxt in order to throw the error with an ID that can be tested against.
Hope that helps!
Andy