Qt Quick Test Reference Documentation

介绍

Qt Quick Test 是用于 QML 应用程序的单元测试框架。测试用例被编写成 JavaScript 函数在 TestCase 类型:

import QtQuick 2.3
import QtTest 1.0
TestCase {
    name: "MathTests"
    function test_math() {
        compare(2 + 2, 4, "2 + 2 = 4")
    }
    function test_fail() {
        compare(2 + 2, 5, "2 + 2 = 5")
    }
}
					

函数名称开头采用 test_ are treated as test cases to be executed. See the documentation for the TestCase and SignalSpy types for more information on writing test cases.

运行测试

Test cases are launched by a C++ harness that consists of the following code:

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

Where "example" is the identifier to use to uniquely identify this set of tests. You should add CONFIG += qmltestcase . for example:

TEMPLATE = app
TARGET = tst_example
CONFIG += warn_on qmltestcase
SOURCES += tst_example.cpp
					

The test harness scans the specified source directory recursively for "tst_*.qml" files. If QUICK_TEST_SOURCE_DIR is not defined, then the current directory will be scanned when the harness is run. Other *.qml files may appear for auxillary QML components that are used by the test.

The -input command-line option can be set at runtime to run test cases from a different directory. This may be needed to run tests on a target device where the compiled-in directory name refers to a host. For example:

tst_example -input /mnt/SDCard/qmltests
					

It is also possible to run a single file using the -input 选项。例如:

tst_example -input data/test.qml
					
tst_example -input <full_path>/test.qml
					

注意: Specifying the full path to the qml test file is for example needed for shadow builds.

If your test case needs QML imports, then you can add them as -import options to the test program command-line.

If IMPORTPATH is specified in your .pro file, each import path added to IMPORTPATH will be passed as a command-line argument when the test is run using "make check":

IMPORTPATH += $$PWD/../imports/my_module1 $$PWD/../imports/my_module2
					

The -functions command-line option will return a list of the current tests functions. It is possible to run a single test function using the name of the test function as an argument. For example:

tst_example Test_Name::function1
					

The -help command-line option will return all the options available.

tst_example -help