如何创建 Qt-Quick 测试

How to create a Qt-Quick Test

我必须创建一个单元测试。

但首先,我要弄清楚该做什么。 有一个 QtQuick2-App 写的,现在我想用 GUI 做单元测试。使用 GUI 进行单元测试的步骤是什么?看了Qt的文档,实在想不出入手测试的思路。

希望有人能帮助我。

编辑:在我的项目中添加 tst_button.qmltst_test.cpp 之后,我能够 运行 一些测试(main.cpp 现在在评论中)。这是正确的方法,还是我应该为测试创建一个新项目?如果是,需要什么样的项目? 最后一个问题:例如,我需要为按下按钮建立 MainForm 吗?

tst_button.qml

import QtQuick 2.4
import QtTest 1.0

Rectangle{
    id: myRec
    property var myMainForm: null

    TestCase{
        name:"ButtonClick"
        when:windowShown

        function test_init(){
           var createMyWindow = "import QtQuick 2.0; MainForm{id:myForm}"
           var myMainForm = Qt.createQmlObject(createMyWindow,myRec)
            myRec.myMainForm = myMainForm
        }
      }
  }

tst_test.cpp

#include <QtQuickTest/quicktest.h>
QUICK_TEST_MAIN(test)

Testing and Debugging列出两种方式:

您可以使用 Qt Test 来测试 Qt Quick 应用程序,但是当您需要访问 QML 中不可用的 C++ API 时,这通常更好。

Do I just add a *.qml file to my project and fill it with my code? If yes, what do I have to do to start the test?

您首先需要将测试作为一个单独的项目,除非您打算使用 qmltestrunner(我不知道为什么 Qt 本身没有记录该工具)。

Qt Quick Test 文档的 Running Tests 部分详细介绍了如何启动和 运行ning 测试。


I was able to run some tests, after adding tst_button.qml and tst_test.cpp to my Project (main.cpp is in comments now). Is this the right way, or should I create a new project just for the Tests?

如果您的应用程序是纯 QML,并且仅打算 运行 和 qmlscene,那么这样做就可以了。但是,如果您打算 deploy/ship 您的应用程序,您可能需要一个可执行文件,这意味着为应用程序和测试创建单独的项目。

If yes, what kind of project is needed?

您可以有一个 SUBDIRS 项目,这样您的测试和应用程序本身就可以在 Qt Creator 中同时打开。像这样:

myapp.pro
app/
    main.cpp
    app.pro
    resources.qrc
    main.qml
tests/
    tests.pro
    data/
        tst_stuff.qml

And the last question: Do I need to build up my MainForm for pressing buttons for example?

没有。 只是一种格式,它允许 Qt Creator 强制执行某些约束,以便更轻松地使用 Qt Quick Designer 设计 Qt Quick UI。 MainForm.ui.qml 因此只是一种方便。如果您在 QML 中已经有一个现有组件,您可以创建它的实例并对其进行测试。