How to mock a QML component

I'm actually trying to run some test on a QML component that embeds C ++ objects . Unfortunately, I get some errors while running my tests. C ++ objects are not recognized by the QML file. This also makes sense, since C ++ objects are defined in the main.cpp file.

My question is: how can I tempt the context property to run QML tests? Or others said how can I do a unit test with a mix of Qt / QML code?

+7
c ++ unit-testing qt5 mocking qml
source share
2 answers

As I understand it, you are right, you have the same problem as me. Some time ago I wrote this layout: https://bitbucket.org/troyane/qml-cpp-template (you can use this code free for your purposes).

Take a look at main.cpp , there you will see two ways to do something:

 // 1 case: // Register type and create object at QML side qmlRegisterType<CppClass>("CppClassModule", 1, 0, "CppClass"); QQmlApplicationEngine engine(QUrl("qrc:///qml/main.qml")); qDebug() << "Qt version: " << qVersion(); // 2 case: // Create object here and "move it up" to QML side // engine.rootContext()->setContextProperty("cppClass", new CppClass); 

Good luck

0
source share

I have QML tests that work for me without compilation in any C ++ code.

In my case, I have a C ++ object controller with the left_motor property, which is another object and has a property speed.

Please note that the speed is readable but not writable. Any updates will occur through the slots. In QML, it looks like this: controller.left_motor.onGuiSpeedChanged (speed)

I was able to mock this in QML using components, properties and some javascript.

 Item { // mock of controller id: controller property alias left_motor: left_motor Item { id: left_motor property int speed: 0 function onGuiSpeedChanged(arg) { speed = arg } } } property alias controller: controller 

Now calls the controller .left_motor.onGuiSpeedChanged (speed), as before, but connected to the mock function. I can even read the speed property to know that a call has occurred.

Here is my test function (the code I'm testing is part of page 1):

 function test_set_speed() { console.log("controller.left_motor.speed: " + controller.left_motor.speed) var got = page1.set_left_speed(250) compare(got, 250, "set_left_speed() return incorrect") console.log("controller.left_motor.speed: " + controller.left_motor.speed) } 

Please note that it is important to use slots instead of writable properties. Calling a slot looks the same as calling a function, and you can mock it as such. I could not figure out a way to mock property creation.

I started trying rewritable properties because this was the first thing in the documentation for linking C ++ and QML. It incorporates QML and C ++ as expected, but cannot be worn for testing.

-one
source share

All Articles