Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

matlab.mock.actions.ThrowException class

Package: matlab.mock.actions

Throw exception when method is called or when property is set or accessed

Description

To specify that the framework throws an exception when a mock object method is invoked or when a mock object property is set or accessed, use the ThrowException class. You can use this action to inject error conditions into the system under test.

Construction

action = ThrowException throws an exception when a method is called or a property is set or accessed.

action = ThrowException(exception) specifies the exception that the mock throws.

Input Arguments

expand all

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

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

Methods

repeatRepeat same action multiple times
thenSpecify action

Copy Semantics

Value. To learn how value classes affect copy operations, see Copying Objects.

Examples

expand all

Create a mock for a bank account class.

testCase = matlab.mock.TestCase.forInteractiveUse;
[mock,behavior] = testCase.createMock('AddedMethods',"deposit");

Set up behavior.

import matlab.mock.actions.ThrowException;
import matlab.unittest.constraints.IsLessThan;
when(behavior.deposit(IsLessThan(0)), ...
    ThrowException(MException('Account:deposit:Negative', ...
    'Deposit amount must be positive.')));

Use the mock.

mock.deposit(10)
mock.deposit(-10)
Error using matlab.mock.internal.MockContext>mockMethodCallback (line 663)
Deposit amount must be positive.

Error in matlab.mock.internal.MockContext>@(data)mockMethodCallback(data,catalog) (line 282)
            methodCallback = @(data)mockMethodCallback(data, catalog);

Alternatives

For simple definition of outputs, you can use the throwExceptionWhen method of the matlab.mock.TestCase class. However, there is more functionality when you use the ThrowException action.

Introduced in R2017a

Was this topic helpful?