Create a mock with behavior based on specific input
8 次查看(过去 30 天)
显示 更早的评论
I'm trying to write a mock test for a class, and want to mock the output based on specific input.
Here is my Test Class
classdef MyClass
methods
function [out1, out2] = myMethod(obj, in1, in2, in3)
out1 = in1 + in2 + in3;
out2 = in1 * in2 * in3;
end
end
end
Based on MATLAB help section withExactInput and withAnyInputs doesnt take any inputs, Attempting to do so raises the error
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1729346/image.jpeg)
So how to mock a test where same methods needs to be called with 2 differnet inputs and check the outputs.
classdef MyTest < matlab.mock.TestCase
methods (Test)
function testMultiInputOutputMethod(testCase)
% Create a mock object and its behavior controller
[mock, behavior] = testCase.createMock(?MyClass);
% Define the behavior of the mock object's method for specific inputs
testCase.assignOutputsWhen(withExactInput(behavior.myMethod(1, 2, 3)), {6, 6}); % Errors out
testCase.assignOutputsWhen(withAnyInputs(behavior.myMethod(2, 3, 4)), {9, 24}); % Errors out
% Use the mock object as if it were the real object
[out1a, out2a] = mock.myMethod(1, 2, 3);
[out1b, out2b] = mock.myMethod(2, 3, 4);
% Verify the results
testCase.verifyEqual(out1a, 6);
testCase.verifyEqual(out2a, 6);
testCase.verifyEqual(out1b, 9);
testCase.verifyEqual(out2b, 24);
% Verify that the mock object's methods were called with specific arguments
testCase.verifyCalled(behavior.myMethod(1, 2, 3));
testCase.verifyCalled(behavior.myMethod(2, 3, 4));
end
end
end
I know the above 'MyClass' doesnt need a mock, Any solution to the above problem would be helpful...
0 个评论
采纳的回答
Ayush Singh
2024-7-8
Hey Jeevraj!
To test the myMethod of MyClass with different inputs using mocks in MATLAB, you can use the MATLAB Unit Test Framework to create a mock object and define its behavior for different inputs.
However, since you want to test the actual method implementation with different inputs, you don't need to mock the method itself as you stated in your question. Instead, you can directly call the method with different inputs in your test case and verify the outputs.
classdef MyClassTest < matlab.unittest.TestCase
methods (Test)
function testMultiInputOutputMethod(testCase)
% Create an instance of MyClass
obj = MyClass();
% Test 1: Call myMethod with first inputs
[out1, out2] = obj.myMethod(1, 2, 3);
testCase.verifyEqual(out1, 6);
testCase.verifyEqual(out2, 6);
% Test 2: Call myMethod with second inputs
[out1, out2] = obj.myMethod(4, 5, 6);
testCase.verifyEqual(out1, 15);
testCase.verifyEqual(out2, 120);
end
end
end
I hope it answers your question!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Mocking Framework 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!