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