Injecting a mock of a QTimer

独自空忆成欢 提交于 2021-02-10 14:48:41

问题


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?

来源:https://stackoverflow.com/questions/62811965/injecting-a-mock-of-a-qtimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!