Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How should I unit test my QStateMachine?



  • Howdy. Long time C++ programmer but still new to Qt.

    I have developed a QStateMachine derived class that I would like run from a purely unit test environment - that is, from a standalone test class. It's not clear to me how I should do that.

    The unit test environment is MSTest, and no, we will not be replacing it with QTest any time soon. I understand that I need an event loop to drive transitions in a QStateMachine. Looking for examples of creating a standalone QEventLoop or QCoreApplication hasn't really clarified the issue - this seems to be an unusual request. I don't want to muddy the water here with shotgun guesses, so I'll just shut up now.

    Any good ideas? Thanks.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    I don't know MSTest but you can still follow the QTest model: create a single class that will instantiate your QStateMachine and mock whatever system should be connected to the machine and trigger the various state.



  • @SGaist Thanks.

    The state machine is driven by QStateMachine::postEvent() calls. When I call QStateMachine::start() and then check isRunning(), I get false. My assumption so far has been that I need to instantiate an event loop somehow to pump the transition events because the unit test environment is not running within a Qt app. Am I wrong?


  • Lifetime Qt Champion

    One possible way would be to have a QThread and use the worker object approach.


Log in to reply