Important: Please read the Qt Code of Conduct -

Is there a canonical way to set up QApplication and Google Test together?

  • When testing anything using QWidget stuff, one obviously needs to set up a QApplication. However, it's not clear how to actually run the tests within this QApplication.
    Specifically, it seems to me like I would want QApplication::exec to start the RUN_ALL_TESTS() macro, and then for the result of that macro to go into a QApplication::exit(return) statement. Naively, I tried to connect QApplication::applicationStateChanged to a function that would call RUN_ALL_TESTS and exit, but that signal doesn't appear to be sent when QApplication::exec is called.
    Seemingly, with the increased compatibility with Google test framework (Qt Creator support, autotest, eg), there should be some kind of canonical way to spin up both QApplication and execute the tests.

    My existing, kind of working setup is one that creates a QApplication in a test fixture that needs it, spins it up, and then exits. But we know that QApplication should be a singleton, and I would guess that calling exec/exit multiple times on such an object would be problematic. It turns out that this setup does crash in a seemingly non-deterministic way, but I haven't investigated too deeply since I suspect it's already broken by the above.

  • After many iterations, I've finally found what I think works well here:

    int main(int argc, char *argv[])
        QCoreApplication app{argc, argv};
        QTimer::singleShot(0, [&]()
            ::testing::InitGoogleTest(&argc, argv);
            auto testResult = RUN_ALL_TESTS();
        return app.exec();

  • Lifetime Qt Champion


    If you have a recent Qt Creator, there's a template project for that.

Log in to reply