How to make a mocked object property observable without superclass?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Gayatri
2024-1-30
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Mock Dependencies in Tests 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!