Main Content

throwExceptionWhen

Class: matlab.mock.TestCase
Namespace: matlab.mock

Throw exception for method call or property interaction

Syntax

throwExceptionWhen(testcase,behavior)
throwExceptionWhen(testcase,behavior,exception)

Description

throwExceptionWhen(testcase,behavior) specifies that the mock should throw an exception when a method is called or a property is accessed or set.

throwExceptionWhen(testcase,behavior,exception) specifies the exception that the mock throws.

Input Arguments

expand all

Instance of the test case, specified as a matlab.mock.TestCase object.

Behavior of the mock, specified as a matlab.mock.MethodCallBehavior, matlab.mock.PropertyGetBehavior, or matlab.mock.PropertySetBehavior instance. To create an instance of matlab.mock.MethodCallBehavior, call a method of the behavior object. To create an instance of matlab.mock.PropertyGetBehavior, call the get method on a property of the behavior object. To create an instance of matlab.mock.PropertySetBehavior, call the set method on a property of the behavior object.

Example: withExactInputs(behavior.myMockedMethod)

Example: get(behavior.MyMockedProperty)

Example: set(behavior.MyMockedProperty)

Exception for the framework to throw at the method call or property interaction, specified as a scalar MException object.

Example: MException('MyProduct:myID','My exception message.')

Examples

expand all

Throw an exception when a method is called or when a property is accessed or set.

testCase = matlab.mock.TestCase.forInteractiveUse;
[mock,behavior] = testCase.createMock('AddedProperties',"PropertyFoo", ...
    'AddedMethods',"methodBar");
testCase.throwExceptionWhen(get(behavior.PropertyFoo));
testCase.throwExceptionWhen(set(behavior.PropertyFoo), ...
    MException('PropertyFoo:set', 'Do not change PropertyFoo'));
testCase.throwExceptionWhen(withAnyInputs(behavior.methodBar));

% Carry out actions
mock.PropertyFoo
mock.PropertyFoo = 123;
mock.methodBar;

Alternatives

Using the throwExceptionWhen method is functionally equivalent to using the matlab.mock.actions.ThrowException action with the when method of the MethodCallBehavior, PropertyGetBehavior, or PropertySetBehavior class. For example, the following code blocks are functionally equivalent.

% Using the throwExceptionWhen method
testCase.throwExceptionWhen(behavior.deposit(IsLessThan(0)), ...
    MException('Account:deposit:Negative', ...
    'Deposit amount must be positive.'));

% Using the ThrowException action with the when function
import matlab.mock.actions.ThrowException
when(behavior.deposit(IsLessThan(0)),ThrowException( ...
    MException('Account:deposit:Negative', ...
    'Deposit amount must be positive.')))
However, there is more functionality when you use the ThrowException action. For instance, you can specify different subsequent behavior for the same mocked object interaction.

Version History

Introduced in R2017a