Libor Tomsik
Libor Tomsik

Reputation: 718

Injecting a mock of a QTimer

I'm writing a unit test with QTest for a legacy code like:

#include <QTimer>
class MyObject: public QObject{
    public:
        void foo(){
            t1.start(500);
        }
    private:
        QTimer t1{this};
};

And want to mock a QTimer and then test if the QTimer::start(int) is properly called. I was trying several approaches. Dependency injection with template template<typename TIMER = QTimer> class MyObjecr: public QObject, but getting

Template classes not supported by Q_OBJECT

And LD_PRELOAD=libQTimerMock.so with a simple QTimer re-implementation.

class QTimer : public QObject
{
signals: 
    void onStarted(int);
public slots:
    void start(int i)
    {
        emit onStarted(i);
    }
};

Which with QMetaObject magie actually WORKS.

Is there a simpler way? Some compile time include injection? So the #include <QTimer> for MyObject.h uses the mock file and the rest of the spaghetti remains intakt?

Upvotes: 2

Views: 299

Answers (0)

Related Questions