Unable to use setContextProperty() with testable unit test framework



  • Re: Testable - QML Unit Test Utilities

    Hi !
    Thanks a lot for sharing this framework.

    I have an issue trying to set custom property from test.cpp while running tests with testable.

    In my app.cpp, i'm using the following code to set properties. Unfortunatly I'm unable to find a way to do the same with testable since I'm note instanciating a QQuickView.

    QQuickView view;
    view.engine()->rootContext()->setContextProperty();
    

    Am I missing something ?

    [Moved to QML and Qt Quick ~kshegunov]


  • Qt Champions 2016

    Ping @benlau


  • Qt Champions 2016

    @ephelip Hello,

    Do you mean to set a context property for the test case in tst_xxxx.qml ?

    Testable uses Qt Quick Tests to execute QML unit test and unfortunately that Qt Quick Tests does not support to setup context property.

    Usually, it is suggested to not use context property for QML unit tests, and change to a singleton object then register it by qmlRegisterSingletonType.

    It is a bit troublesome as you need to modify your code. There has a dirty hack by Testable, but personally, I don't really like this solution.

    You may register a context property by using the engine hook function call by TestRunner object.

    void callback(QQmlEngine* engine) {
        Q_UNUSED(engine);
    
        QVariantMap property;
        property["value1"] = 1;
        engine->rootContext()->setContextProperty("CustomProperty", property);
    
        // You may register image provider here for QtTest
    }
    

    Reference:
    testable/main.cpp at master · benlau/testable

        TestRunner runner;
        runner.add(QString(SRCDIR));
    
        runner.addImportPath("qrc:///");
        runner.setEngineHook(callback);
    

    Then in your unit test, call TestRunner.prepare("")

    import Testable 1.0
    
    .....
    
            function test_available() {
                TestRunner.prepare("");
                // CustomProperty is registered by engine hook
                compare(CustomProperty.value1, 1);
            }
    

    Reference:
    testable/tst_ContextProperty.qml at master · benlau/testable

    TestRunner.prepare is a dummy function which does nothing by itself. But once a TestRunner singleton object is created, it will trigger the engine hook function to register a context property.



  • Thanks for the exemple,
    this works great !


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.