如何模拟QML组件 [英] How to mock a QML component

查看:102
本文介绍了如何模拟QML组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我正在尝试在嵌入C ++对象的QML组件上进行一些测试.不幸的是,执行测试时出现一些错误. QML文件无法识别C ++对象.由于在main.cpp文件中设置了C ++对象,因此也很有意义.

Actually I'm trying to run some test on a QML component which embeds C++ objects. Unfortunately, I'm getting some errors when I execute my tests. The C++ objects aren't recognized by the QML file. That makes also sense as the C++ objects are set in the main.cpp file.

我的问题是:如何模拟执行QML测试的上下文属性?或其他人说,如何混合Qt/QML代码进行单元测试?

My question is: How can I mock an context property for performing QML tests? Or other said, how can I do unit-test with mixing Qt/QML code?

推荐答案

我可以在不编译任何C ++代码的情况下使用QML测试.

I got QML tests working for me without compiling in any C++ code.

在我的情况下,我有一个C ++对象 controller ,它具有名为 left_motor 的属性,它是另一个对象,并且具有属性 speed .

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

请注意,速度是可读的,但不是可写的.任何更新都将通过插槽进行.在QML中如下所示:controller.left_motor.onGuiSpeedChanged(speed)

Note that speed is readable, but not writable. Any updates will happen through slots. In QML that looks like this: controller.left_motor.onGuiSpeedChanged(speed)

我能够使用Item组件,属性和一些javascript在QML中对此进行模拟.

I was able to mock this in QML using Item 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

现在对controller.left_motor.onGuiSpeedChanged(speed)的调用像以前一样解析,但是连接到模拟函数中.我什至可以读回speed属性,以了解呼叫已发生.

Now calls to controller.left_motor.onGuiSpeedChanged(speed) resolve like before, but connect into the mock function. I can even read back the speed property to know that the call happened.

这是我的测试功能(我正在测试的代码在第1页中):

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

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)
}

请注意,使用插槽而不是可写属性很重要.对插槽的调用看起来就像一个函数调用,可以这样模拟.我想不出一种模拟属性写入的方法.

Note that it's important to use slots instead of writable properties. The call to a slot looks just like a function call and can be mocked as such. I could not figure out a way to mock out a property write.

我已经开始尝试可写属性,因为这是绑定C ++和QML的文档中的第一件事.它可以按预期的方式连接QML和C ++,但无法进行测试.

I had started out trying writable properties because that was the first thing in the documentation on binding C++ and QML. It connects QML and C++ as expected, but can't be mocked out for testing.

这篇关于如何模拟QML组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆