MATLAB Answers

Create a mock with defined behavior on different subsequent method calls

조회 수: 13(최근 30일)
Markus Leuthold
Markus Leuthold 12 Aug 2019
답변: David Hruska 27 Dec 2019
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?

  댓글 수: 0

댓글을 달려면 로그인하십시오.

답변(1개)

David Hruska
David Hruska 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

  댓글 수: 0

댓글을 달려면 로그인하십시오.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by