Can I put two mocks of same class in an array?

I am using the mock testing framework to create mocks.
I create two different mock instances of the same class, for example, `obj1 = testCase.createMock(?Foo)` and `obj2 = testCase.createMock(?Foo)`. (The two instances play two different roles in my test.) When I attempt to put these instances in an array, `[obj1 obj2`, Matlab reports any '...error converting from `FooMock_1`to `FooMock`'.
How do I create two different mock instances of the same mocked type?

답변 (1개)

Samayochita
Samayochita 2025년 6월 18일

0 개 추천

Hi Larry Jones,
In unit testing framework of MATLAB, when we use “createMock”, it dynamically generates a new class type for each mock. So even if we mock the same original class (e.g., Foo), the resulting mock objects are not of the same class, which means we cannot place them in a standard array like [obj1 obj2].
To handle this:
  1. Use matlab.mock.TestCase (not the default matlab.unittest.TestCase) to access mocking capabilities.
  2. Store multiple mocks in a cell array rather than a standard MATLAB array.
  3. Use AddedMethods, AddedProperties, or a real class/interface to mock specific behaviors.
Here is a code snippet to illustrate the approach:
% Create two separate mocks of the same method signature
[mock1, behavior1] = testCase.createMock('AddedMethods', "doSomething");
[mock2, behavior2] = testCase.createMock('AddedMethods', "doSomething");
% Store mocks in a cell array (important!)
mocks = {mock1, mock2};
% Set different return values for each mock (optional)
import matlab.mock.actions.AssignOutputs
testCase.assignOutputsWhen(withAnyInputs(behavior1.doSomething), "Response from mock 1");
testCase.assignOutputsWhen(withAnyInputs(behavior2.doSomething), "Response from mock 2");
We can now use mocks{1}.doSomething() and mocks{2}.doSomething() separately, each returning its own mocked behavior.
For more information please refer to the following documentation links:
Hope this is helpful!

카테고리

도움말 센터File Exchange에서 Mock Dependencies in Tests에 대해 자세히 알아보기

제품

릴리스

R2018a

태그

질문:

2018년 7월 29일

답변:

2025년 6월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by