Create a mock with defined behavior on different subsequent method calls

조회 수: 1 (최근 30일)
Markus Leuthold
Markus Leuthold 2019년 8월 12일
답변: David Hruska 2019년 12월 27일
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