functionality if you use the WasCalled constraint. For example, you can verify that a
mocked method was called a specified number of times.
import matlab.unittest.constraints.IsAnything
testCase.verifyThat(brokerBehavior.buy("FOO",IsAnything), ...
WasCalled('WithCount',2))
Interactive verification passed.
Verify that the buy method was not called requesting 100 shares of the BAR stock.
testCase.verifyNotCalled(brokerBehavior.buy("BAR",100))
Interactive verification passed.
Although the trader function was called requesting 100 shares of BAR stock, the stub
defined yesterday's price for BAR to return a higher value than all days prior to yesterday.
Therefore, the broker never buys stock "BAR".
Test Class for trader Function
The interactive test case is convenient to experiment with at the command prompt.
However, it is typical to create and use mocks within a test class. In a file in your current
working folder, create the following test class that incorporates the interactive testing
from this example.
classdef TraderTest < matlab.mock.TestCase
methods(Test)
function buysStockWhenDrops(testCase)
import matlab.unittest.constraints.IsLessThan
import matlab.unittest.constraints.IsAnything
import matlab.mock.constraints.WasCalled
yesterday = datetime('yesterday');
% Create mocks
[stubDataService,dataServiceBehavior] = createMock(testCase, ...
?DataService);
[spyBroker,brokerBehavior] = createMock(testCase, ...
'AddedMethods',{'buy'});
% Set up behavior
testCase.assignOutputsWhen(dataServiceBehavior.lookupPrice(...
"FOO",yesterday),123);
testCase.assignOutputsWhen(dataServiceBehavior.lookupPrice(...
33 Unit Testing