Create a mock with defined behavior on different subsequent method calls
조회 수: 1 (최근 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?
댓글 수: 0
답변 (1개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Mock Dependencies in Tests에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!