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

8 ビュー (過去 30 日間)
Larry Jones
Larry Jones 2018 年 7 月 29 日
回答済み: Samayochita 2025 年 6 月 18 日
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 日
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!

カテゴリ

Help Center および File ExchangeMock Dependencies in Tests についてさらに検索

タグ

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by