Tobia Tesan
Tobia Tesan

Reputation: 1936

Integration testing: making C++ components visible to `qmltestrunner`

Suppose I have a number of QML components.

They work with a component or a QObject (suppose it's a data source,but could be anything, even the old Horse/Animal/Dog with the method bark()) that I wrote in C++ and I expose in my main.cpp somehow.

While a proper unit test would, of course, stub it, I may want to write an integration test to see that they play nice together.

How would I then render them visible to qmltestrunner?

If it's not possible at all, how would one best approach integration testing of QML and C++ components?

Upvotes: 1

Views: 535

Answers (1)

pmf
pmf

Reputation: 7759

I've solved the problem of integration testing (which, in addition to the problem you have described, for me also had the issue of QML files requiring stuff in the resource file that will not be found if I require components via file based access, as qmltestrunner does) by having a flag TEST_RUNNER in my main.cpp that determines whether the regular application should be started or whether quick_test_main should be started (quick_test_main being the programmatically accessible core or qmltestrunner). It looks as follows:

// define to enable the test harness
#define TEST_RUNNER
#ifdef TEST_RUNNER
#include <QtQuickTest/quicktest.h>
#endif

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    // register components here as you're already doing

#ifndef TEST_RUNNER
    // not defined: regular application start
    QQmlApplicationEngine engine;

    engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

    return app.exec();
#else
    // adapt path accordingly
    return quick_test_main(argc, argv, "MyTests", "../my_qmltests_path/");
#endif
}

A test case looks like this (note that I'm loading the component via a resource path because that's how my application works; loading via file would fail to load resources that are required for the QML files ...):

import QtQuick 2.0
import QtTest 1.0

TestCase {
    name: "MainMenu"

    Loader {
        id: main_loader
        source: "qrc:/qml/main.qml"
    }

    function test_on_off(){
        wait(3000);
    }
}

Upvotes: 1

Related Questions