How to make a mocked object property observable without superclass?

7 次查看(过去 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?

回答(1 个)

Gayatri
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!

类别

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

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by