Assign value to property of mock object when method is called

62 views (last 30 days)
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 Comments
Houman Rastegarfar
Houman Rastegarfar on 2 Dec 2020
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 on 3 Dec 2020
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

Sign in to comment.

Accepted Answer

David Hruska
David Hruska on 10 Dec 2020
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

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!