Create a mock with defined behavior on different subsequent method calls

1 view (last 30 days)
Assume a mocked class
testCase = matlab.mock.TestCase.forInteractiveUse;
[mock, behavior] = createMock(testCase, "AddedMethods", ["methodA" "methodB"]);
How do I define the following behavior?
assert(mock.methodA == 1)
assert(mock.methodB == 2)
assert(mock.methodA == 3)
How do I assign output values for different methods of the mock in a predefined order? I only find examples of defining the behavior of subsequent calls of the SAME method, but no example for defining subsequent calls including different methods of a mocked class. Something like
testCase.assignOutputsWhen(withExactInputs(behavior.methodA), 1);
testCase.assignOutputsWhen(withExactInputs(behavior.methodB), 2);
testCase.assignOutputsWhen(withExactInputs(behavior.methodA), 3);
does not work, unfortunately. Using when()/then() which allows to define subsequent actions does not work either, since the condition is used on one single method, not on several methods of a class. Are there any other possibilities?

Answers (1)

David Hruska
David Hruska on 27 Dec 2019
I know this reply is coming very late, but if it's still helpful, this is possible in R2019b using the Invoke action to define more custom mock object behaviors:
function example
import matlab.mock.actions.Invoke;
% Nested function to keep track of state between method calls
count = 0;
function out = counter(varargin)
count = count + 1;
out = count;
end
testCase = matlab.mock.TestCase.forInteractiveUse;
[mock, behavior] = createMock(testCase, "AddedMethods", ["methodA" "methodB"]);
% Both method calls invoke the counter function above:
when(withExactInputs(behavior.methodA), Invoke(@counter));
when(withExactInputs(behavior.methodB), Invoke(@counter));
assert(mock.methodA == 1)
assert(mock.methodB == 2)
assert(mock.methodA == 3)
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!