repeat

Class: matlab.mock.actions.ThrowException
Package: matlab.mock.actions

Repeat throwing exception

Syntax

repeat(n,action)

Description

repeat(n,action) repeats the same action multiple times.

Input Arguments

expand all

Number of times to repeat action, specified as an integer.

Example: 5

Defined action, specified as an instance of matlab.mock.actions.ThrowException.

Example: ThrowException

Example: ThrowException(MException('Account:deposit:Negative','Deposit amount must be positive.'))

Examples

expand all

Create a mock for a bank account class.

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

Specify behavior.

import matlab.mock.actions.ThrowException
import matlab.mock.actions.AssignOutputs
when(withExactInputs(behavior.isOpen),then(repeat(2,ThrowException), ...
    then(AssignOutputs(false))));

Use the mock.

isAccountOpen = mock.isOpen
Error using matlab.mock.internal.MockContext>mockMethodCallback (line 663)
The following method call was specified to throw an exception:
	isOpen([1×1 matlab.mock.classes.Mock])

Error in matlab.mock.internal.MockContext>@(data)mockMethodCallback(data,catalog) (line 282)
            methodCallback = @(data)mockMethodCallback(data, catalog);
isAccountOpen = mock.isOpen
Error using matlab.mock.internal.MockContext>mockMethodCallback (line 663)
The following method call was specified to throw an exception:
	isOpen([1×1 matlab.mock.classes.Mock])

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

  logical

   0

Tips

  • If you repeat an action, and do not follow it with a call to the then method, the mock continues to return the repeated value. For example, consider the following mock of a bank account class.

    import matlab.mock.actions.ThrowException
    testCase = matlab.mock.TestCase.forInteractiveUse;
    [mock, behavior] = testCase.createMock('AddedProperties',"IsJointAccount");

    If you repeat an action to throw an exception twice, the framework continues to throw an exception in the following code, which goes on to get the property value a third time.

    when(get(behavior.IsJointAccount),then(repeat(2,ThrowException)));
    tf = mock.IsJointAccount
    tf = mock.IsJointAccount
    tf = mock.IsJointAccount

    But the following code throws an exception twice and the returns false.

    import matlab.mock.actions.AssignOutputs
    when(get(behavior.IsJointAccount),then(repeat(2,ThrowException), ...
        then(AssignOutputs(false))));
    tf = mock.IsJointAccount
    tf = mock.IsJointAccount
    tf = mock.IsJointAccount

Introduced in R2017a