TEST_NO_ERROR
Test to ensure an error is NOT thrown.
Back to Simple Unit Testing Toolbox Documentation.
Contents
Syntax
TEST_NO_ERROR(f) TEST_NO_ERROR(f,args) TEST_NO_ERROR(__,name,print,color) outputs = TEST_NO_ERROR(__)
Description
TEST_NO_ERROR(f) tests if the function f (that has no inputs) does not throw an error.
TEST_NO_ERROR(f,args) tests if the function f does not throw an error when subject to the input arguments args.
TEST_NO_ERROR(...,name,print,color) does the same as the syntaxes above, but also allows the user to specify a test name, whether or not to print the test results to the Command Window, and whether or not to print those test results in color. This syntax is primarily used when defining unit test classes.
outputs = TEST_NO_ERROR(...) also returns the test outputs. Again, this syntax is primarily used when defining unit test classes.
Inputs
Variable | Description | Format |
f | function handle assigned to function you want to test | 1×1 function_handle |
args | (OPTIONAL) input arguments to f (defaults to empty cell array) | cell array |
name | (OPTIONAL) test name (defaults to empty string) | char array |
(OPTIONAL) true if test result should be printed to Command Window, false otherwise (defaults to true) | 1×1 logical |
|
color | (OPTIONAL) true if test result should be printed in color, false otherwise (defaults to true) | 1×1 logical |
Outputs
Variable | Description | Format | ||||||||||||
output | test outputs
|
1×1 struct |
Example #1: Passed test.
MATLAB's mod function requires to inputs Therefore, we expect mod to execute successfully and not throw an error when given 2 inputs. First, we assign a function handle to the mod function.
f = @(x,y) mod(x,y);
Next, let's test to make sure the mod function does not throw an error when we give it 2 real-valued inputs.
TEST_NO_ERROR(f,{5,5});
Passed.
Note that we don't have to define the function handle separately; we can also define it within the call on TEST_NO_ERROR.
TEST_NO_ERROR(@(x,y)mod(x,y),{5,5});
Passed.
Example #2: Failed test.
Let's once again use MATLAB's mod function (which requires 2 inputs) as an example. This time around, let's incorrectly pass it only 1 input. Now, the mod function will not execute correctly, and testing for no error should result in a failed test (since the function will throw an error).
TEST_NO_ERROR(@(x,y)mod(x,y),{5});
FAILED. >>>> Function threw the following error: Not enough input arguments.
Example #3: User-defined function raising custom error.
Let's consider a user-defined divide_safe function that safeguards against division by 0. If we try dividing 5 by 0 using the divide_safe function, we should get an error. If we test for no error, then we will get a failed test result.
TEST_NO_ERROR(@(a,b)divide_safe(a,b),{5,0}); function c = divide_safe(a,b) if b == 0 error('Divide-by-zero error.') end c = a/b; end
FAILED. >>>> Function threw the following error: Divide-by-zero error.