How to make a mocked object property observable without superclass?
5 views (last 30 days)
Show older comments
I need to test a class which listents for property changes of another object, for example
classdef MyClass
methods
function obj = MyClass(observedObject)
addlistener(observedObject, 'propertyA', 'PostSet', @obj.doSomething);
end
end
end
In order to test MyClass, I would create a mock for observedObject to inject into the constructor of MyClass, like
observedObjectMock = tc.createMock(?handle, 'AddedProperties', "propertyA");
myObject = MyClass(observedObjectMock);
However, this is not allowed and I recieve the following error message:
While adding a PostSet listener, property 'propertyA' in class 'matlab.mock.classes.handleMock' is not defined to be SetObservable.
I know that this can be fixed by creating a superclass for observedObject which has an observable abstract propertyA:
classdef ObservableSuperClass < handle
properties (Abstract, SetObservable)
propertyA
end
end
% Mock would then be created like this
observedObjectMock = tc.createMock(?ObservableSuperClass);
Is there a way to make this work using Matlab's Mocking Framework without having to create an extra superclass?
0 Comments
Answers (1)
Gayatri
on 30 Jan 2024
Hi,
It seems that you are encountering an error while adding a “PostSet” listener: property “propertyA” in class “matlab.mock.classes.handleMock” is not defined to be “SetObservable”.
When creating a mock object for testing in MATLAB, ensure that the properties you want to listen to are observable.
This is because the MATLAB mocking framework requires that the properties of the object being mocked have the “SetObservable” attribute if you intend to add a “PostSet” listener to them.
There is no direct way to add the “SetObservable” attribute to a property in a mock object without defining it in a superclass.
The approach of creating a superclass with the “SetObservable” attribute is the correct way to ensure that the property is observable in the mock.
I hope this helps!
0 Comments
See Also
Categories
Find more on Mock Dependencies in Tests in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!