Create a mock with defined behavior on different subsequent method calls

4 次查看(过去 30 天)
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?

回答(1 个)

David Hruska
David Hruska 2019-12-27
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

类别

Help CenterFile Exchange 中查找有关 Mock Dependencies in Tests 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by