How to make a mocked object property observable without superclass?

7 Ansichten (letzte 30 Tage)
Ralf Ritter
Ralf Ritter am 3 Feb. 2022
Beantwortet: Gayatri am 30 Jan. 2024
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?

Antworten (1)

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

Kategorien

Mehr zu Mock Dependencies in Tests finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by