How to muffle / mock Qt classes?

I am new to testing and TDD, but decided to try and learn. I'm currently trying to develop a SettingsManager class that will handle my application settings. It will save the state of the application, and when it closes the SettingsManager, it will save the state using QSettings (and will read when it starts). Now I want to mock QSettings, so my tests will not depend on a random state. However, I could not find a reasonable way to mock / wrap it up, because the method (QSettings :: value ()) I need is not virtual.

Perhaps I'm doing something conceptually wrong? Or is there a way to make fun of this non-virtual method call?

Example: suppose I have this class:

class SettingsManager { private: /* app state variables */ QSettings *settings; bool m_objectsVisible; public: SettingsManager(QSettings *settings) { this->settings = settings; } void readSettings() { m_objectsVisible = settings.value("Settings/ObjectsVisible").toBool(); } bool objectsVisible() { return m_objectsVisible; } }; 

And I want to test it this way (I used the Hippomocks syntax just to give an idea)

 void TestObjectsAreVisible() { MockRepository mocks; QSettings *settingsMock = mocks.ClassMock<QSettings>(); mocks.ExpectCall(settingsMock , QSettings::value).With("Settings/ObjectsVisible").Return(true); SettingsManager *sManager = new SettingsManager(settingsMock); sManager->readSettings(); assertTrue(sManager->objectsVisible); } 
+4
source share
1 answer

I think you are testing a QSettings device, but this is not a unit testing point.

If you want to learn TDD, start with something simpler. For example, try creating a triad of MVP classes (the model and presenter must have interfaces, and view must have the qt class type). Then completely unit test model and presenter. There should be no logic in the view - only qt calls.

Something like that:

 struct View : (some qt object ) { View( PresenterIface &p_ ) : p(p_) {} void buttonClicked() { p.buttonClicked(); } PresenterIface p; }; struct Presenter : PresenterIface { Presenter( ModelIface &m_ ) : m(m){} void buttonClicked() { m.setValue(); } ModelIface &m; }; struct Model : ModelIface { void setValue() { // do something } }; 
+2
source

Source: https://habr.com/ru/post/1347229/


All Articles