- Use matlab.mock.TestCase (not the default matlab.unittest.TestCase) to access mocking capabilities.
- Store multiple mocks in a cell array rather than a standard MATLAB array.
- Use AddedMethods, AddedProperties, or a real class/interface to mock specific behaviors.
Can I put two mocks of same class in an array?
    8 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
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?
0 comentarios
Respuestas (1)
  Samayochita
 el 18 de Jun. de 2025
        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:
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:
assignOutputsWhen: https://www.mathworks.com/help/matlab/ref/matlab.mock.testcase.assignoutputswhen.html
withAnyInputs: https://www.mathworks.com/help/matlab/ref/matlab.mock.methodcallbehavior.withanyinputs.html
Hope this is helpful!
0 comentarios
Ver también
Categorías
				Más información sobre Mock Dependencies in Tests en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

