Assign value to property of mock object when method is called

55 次查看(过去 30 天)
Hi, is there a way to assign a value to a property of a mock object when a method of the same object is called?
Let's say I create the following mock:
[mock, behavior] = createMock('AddedMethods', "doSomething", 'AddedProperties', "propA");
Now I would like to do something like:
when(withAnyInputs(behavior.doSomething), set(mock.propA, true));
Obviously, that's no valid code, but I think you get what I mean. Thanks for your help!
  2 个评论
Houman Rastegarfar
Houman Rastegarfar 2020-12-2
Hi Ralf,
You can set the mock object property to the value returned by the mock object method. To achieve this, specify separate behaviors for the method and the property. You can specify one behavior at a time.
import matlab.mock.actions.*
testCase = matlab.mock.TestCase.forInteractiveUse;
[mock,behavior] = testCase.createMock('AddedMethods',"doSomething",'AddedProperties',"propA");
%Set up behavior when the method is called
when(withAnyInputs(behavior.doSomething),AssignOutputs(true))
%Set up behavior when the property is set
when(set(behavior.propA),StoreValue)
% Invoke the method and set the property
mock.propA = mock.doSomething
For more information about mock object behavior, see Specify Mock Object Behavior.
-Houman
Ralf Ritter
Ralf Ritter 2020-12-3
Hi Houman,
Thank you for your suggestions. However, this is not the behavior I wanted to achieve. If I understand correctly, I would still have to manually assign the value to the property as in your last line:
% Invoke the method and set the property
mock.propA = mock.doSomething
I could also do this by simply assigning the value directly to the property:
mock.propA = true;
But I would like the mocking framework to do this by itself, whenever the doSomething method of the mock object is called by the class under test.
To give an example, the class definition of the mocked object could look like this:
classdef ClassA < handle
properties (SetAccess = private)
propA logical = false
end
methods
function obj = ClassA
end
function doSomething(obj)
% Some code
if someConditionIsTrue
obj.propA = true;
end
end
end
end
Cheers
Ralf

请先登录,再进行评论。

采纳的回答

David Hruska
David Hruska 2020-12-10
If you're using R2018b or later, you can use the Invoke action to set this up. Here's an example:
function example
import matlab.mock.actions.Invoke;
testCase = matlab.mock.TestCase.forInteractiveUse;
[mock, behavior] = testCase.createMock('AddedMethods', "doSomething", 'AddedProperties', "propA");
when(withAnyInputs(behavior.doSomething), Invoke(@setPropA));
function obj = setPropA(obj)
obj.propA = true;
end
mock = mock.doSomething;
disp(mock);
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mock Dependencies in Tests 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by