表示单元测试案例。 更多...
导入语句: | import QtTest |
继承: |
Test cases are written as JavaScript functions within a TestCase type:
import QtQuick 2.0 import QtTest 1.2 TestCase { name: "MathTests" function test_math() { compare(2 + 2, 4, "2 + 2 = 4") } function test_fail() { compare(2 + 2, 5, "2 + 2 = 5") } }
Functions whose names start with "test_" are treated as test cases to be executed. The name property is used to prefix the functions in the output:
********* Start testing of MathTests ********* Config: Using QTest library 4.7.2, Qt 4.7.2 PASS : MathTests::initTestCase() FAIL! : MathTests::test_fail() 2 + 2 = 5 Actual (): 4 Expected (): 5 Loc: [/home/.../tst_math.qml(12)] PASS : MathTests::test_math() PASS : MathTests::cleanupTestCase() Totals: 3 passed, 1 failed, 0 skipped ********* Finished testing of MathTests *********
Because of the way JavaScript properties work, the order in which the test functions are found is unpredictable. To assist with predictability, the test framework will sort the functions on ascending order of name. This can help when there are two tests that must be run in order.
Multiple TestCase types can be supplied. The test program will exit once they have all completed. If a test case doesn't need to run (because a precondition has failed), then optional can be set to true.
Table data can be provided to a test using a function name that ends with "_data". Alternatively, the
init_data()
function can be used to provide default test data for all test functions in a TestCase type:
import QtQuick 2.0 import QtTest 1.2 TestCase { name: "DataTests" function init_data() { return [ {tag:"init_data_1", a:1, b:2, answer: 3}, {tag:"init_data_2", a:2, b:4, answer: 6} ]; } function test_table_data() { return [ {tag: "2 + 2 = 4", a: 2, b: 2, answer: 4 }, {tag: "2 + 6 = 8", a: 2, b: 6, answer: 8 }, ] } function test_table(data) { //data comes from test_table_data compare(data.a + data.b, data.answer) } function test__default_table(data) { //data comes from init_data compare(data.a + data.b, data.answer) } }
The test framework will iterate over all of the rows in the table and pass each row to the test function. As shown, the columns can be extracted for use in the test. The
tag
column is special - it is printed by the test framework when a row fails, to help the reader identify which case failed amongst a set of otherwise passing tests.
Functions whose names start with "benchmark_" will be run multiple times with the Qt benchmark framework, with an average timing value reported for the runs. This is equivalent to using the
QBENCHMARK
macro in the C++ version of QTestLib.
TestCase { id: top name: "CreateBenchmark" function benchmark_create_component() { var component = Qt.createComponent("item.qml") var obj = component.createObject(top) obj.destroy() component.destroy() } } RESULT : CreateBenchmark::benchmark_create_component: 0.23 msecs per iteration (total: 60, iterations: 256) PASS : CreateBenchmark::benchmark_create_component()
To get the effect of the
QBENCHMARK_ONCE
macro, prefix the test function name with "benchmark_once_".
The keyPress (), keyRelease (),和 keyClick () methods can be used to simulate keyboard events within unit tests. The events are delivered to the currently focused QML item. You can pass either a Qt.Key enum value or a latin1 char (string of length one)
Rectangle { width: 50; height: 50 focus: true TestCase { name: "KeyClick" when: windowShown function test_key_click() { keyClick(Qt.Key_Left) keyClick("a") ... } } }
The mousePress (), mouseRelease (), mouseClick (), mouseDoubleClickSequence () 和 mouseMove () methods can be used to simulate mouse events in a similar fashion.
注意: keyboard and mouse events can only be delivered once the main window has been shown. Attempts to deliver events before then will fail. Use the 当 and windowShown properties to track when the main window has been shown.
A typical pattern with QML tests is to dynamically create an item and then destroy it at the end of the test function:
TestCase { id: testCase name: "MyTest" when: windowShown function test_click() { var item = Qt.createQmlObject("import QtQuick 2.0; Item {}", testCase); verify(item); // Test item... item.destroy(); } }
The problem with this pattern is that any failures in the test function will cause the call to
item.destroy()
to be skipped, leaving the item hanging around in the scene until the test case has finished. This can result in interference with future tests; for example, by blocking input events or producing unrelated debug output that makes it difficult to follow the code's execution.
By calling createTemporaryQmlObject () instead, the object is guaranteed to be destroyed at the end of the test function:
TestCase { id: testCase name: "MyTest" when: windowShown function test_click() { var item = createTemporaryQmlObject("import QtQuick 2.0; Item {}", testCase); verify(item); // Test item... // Don't need to worry about destroying "item" here. } }
For objects that are created via the createObject () function of 组件 , createTemporaryObject () function can be used.
In most cases, you would want to separate your tests from the application logic by splitting them into different projects and linking them.
For example, you could have the following project structure:
. | — CMakeLists.txt | — src | | — main.cpp | — qml | | — main.qml | — modules | | — MyModule | | — MyButton.qml | | — CMakeLists.txt | — tests | — UnitQMLTests | — tst_testqml.qml | — main.cpp | — setup.cpp | — setup.h
Now, to test the
modules/MyModule/MyButton.qml
, create a library for
MyModule
in
modules/MyModule/CMakeLists.txt
and link it to your test project,
tests/UnitQMLTests/CMakeLists.txt
:
... qt_add_library(${MyModule} STATIC) qt6_add_qml_module(${MyModule} URI ${MyModule} VERSION 1.0 QML_FILES ${QML_SOURCES} # SOURCES ${CPP_SOURCES} ${HPP_SOURCES} ) ...
... add_executable(TestQML main.cpp setup.cpp setup.h) add_test(NAME TestQML COMMAND TestQML) target_link_libraries( TestQML PRIVATE Qt6::QuickTest PRIVATE Qt6::Qml PRIVATE MyModule PRIVATE MyModuleplugin ) ...
Then, in your
tests/UnitQMLTests/tst_testqml.qml
, you can import your
modules/MyModule/MyButton.qml
:
import QtQuick import QtQuick.Controls import QtTest import MyModule Item { width: 800; height: 600 MyButton { id: myButton anchors.centerIn: parent } TestCase { name: "MyButton"; when: windowShown; function test_clickToExpand() { const widthBeforeClick = myButton.width; mouseClick(myButton); const widthAfterClick = myButton.width; verify(widthBeforeClick < widthAfterClick); } } }
ignoreWarning ( message ) |
Marks
message
as an ignored warning message. When it occurs, the warning will not be printed and the test passes. If the message does not occur, then the test will fail. Similar to
QTest::ignoreMessage(QtWarningMsg, message)
in C++.
从 Qt 5.12 起, message can be either a string, or a regular expression providing a pattern of messages to ignore.
For example, the following snippet will ignore a string warning message:
ignoreWarning("Something sort of bad happened")
And the following snippet will ignore a regular expression matching a number of possible warning messages:
ignoreWarning(new RegExp("[0-9]+ bad things happened"))
注意: Despite being a JavaScript RegExp object, it will not be interpreted as such; instead, the pattern will be passed to QRegularExpression .
另请参阅 warn ().
init () |
This function is called before each test function that is executed in the TestCase type. The default implementation does nothing. The application can provide its own implementation to perform initialization before each test function.
另请参阅 cleanup () 和 initTestCase ().
initTestCase () |
This function is called before any other test functions in the TestCase type. The default implementation does nothing. The application can provide its own implementation to perform test case initialization.
另请参阅 cleanupTestCase () 和 init ().
bool isPolishScheduled ( object itemOrWindow ) |
若
itemOrWindow
是
Item
,此函数返回
true
if
updatePolish
() has not been called on it since the last call to
polish
(),否则返回
false
.
Since Qt 6.5, if
itemOrWindow
是
Window
,此函数返回
true
if
updatePolish
() has not been called on any item it manages since the last call to
polish
() on those items, otherwise returns
false
.
When assigning values to properties in QML, any layouting the item must do as a result of the assignment might not take effect immediately, but can instead be postponed until the item is polished. For these cases, you can use this function to ensure that items have been polished before the execution of the test continues. For example:
verify(isPolishScheduled(item)) verify(waitForItemPolished(item))
Without the call to
isPolishScheduled()
above, the call to
waitForItemPolished()
might see that no polish was scheduled and therefore pass instantly, assuming that the item had already been polished. This function makes it obvious why an item wasn't polished and allows tests to fail early under such circumstances.
另请参阅 waitForPolish (), QQuickItem::polish (),和 QQuickItem::updatePolish ().
keyClick ( key , modifiers = Qt.NoModifier, delay = -1) |
Simulates clicking of key with optional modifiers on the currently focused item. If delay is larger than 0, the test will wait for delay 毫秒。
The event will be sent to the TestCase window or, in case of multiple windows, to the current active window. See QGuiApplication::focusWindow () 了解更多细节。
另请参阅 keyPress () 和 keyRelease ().
keyPress ( key , modifiers = Qt.NoModifier, delay = -1) |
Simulates pressing a key with optional modifiers on the currently focused item. If delay is larger than 0, the test will wait for delay 毫秒。
The event will be sent to the TestCase window or, in case of multiple windows, to the current active window. See QGuiApplication::focusWindow () 了解更多细节。
注意: At some point you should release the key using keyRelease ().
另请参阅 keyRelease () 和 keyClick ().
keyRelease ( key , modifiers = Qt.NoModifier, delay = -1) |
Simulates releasing a key with optional modifiers on the currently focused item. If delay is larger than 0, the test will wait for delay 毫秒。
The event will be sent to the TestCase window or, in case of multiple windows, to the current active window. See QGuiApplication::focusWindow () 了解更多细节。
另请参阅 keyPress () 和 keyClick ().
keySequence ( keySequence ) |
Simulates typing of keySequence . The key sequence can be set to one of the 标准键盘快捷键 , or it can be described with a string containing a sequence of up to four key presses.
Each event shall be sent to the TestCase window or, in case of multiple windows, to the current active window. See QGuiApplication::focusWindow () 了解更多细节。
另请参阅 keyPress (), keyRelease (), GNU Emacs 样式键序列 ,和 Shortcut.sequence .
mouseClick ( item , x = item.width / 2, y = item.height / 2, button = Qt.LeftButton, modifiers = Qt.NoModifier, delay = -1) |
Simulates clicking a mouse button with optional modifiers on an item . The position of the click is defined by x and y 。若 x and y are not defined the position will be the center of item 。若 delay is specified, the test will wait for the specified amount of milliseconds before pressing and before releasing the button.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
另请参阅 mousePress (), mouseRelease (), mouseDoubleClickSequence (), mouseMove (), mouseDrag (),和 mouseWheel ().
mouseDoubleClickSequence ( item , x = item.width / 2, y = item.height / 2, button = Qt.LeftButton, modifiers = Qt.NoModifier, delay = -1) |
Simulates the full sequence of events generated by double-clicking a mouse button with optional modifiers on an item .
This method reproduces the sequence of mouse events generated when a user makes a double click: Press-Release-Press-DoubleClick-Release.
The position of the click is defined by x and y 。若 x and y are not defined the position will be the center of item 。若 delay is specified, the test will wait for the specified amount of milliseconds before pressing and before releasing the button.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
This QML method was introduced in Qt 5.5.
另请参阅 mousePress (), mouseRelease (), mouseClick (), mouseMove (), mouseDrag (),和 mouseWheel ().
mouseDrag ( item , x , y , dx , dy , button = Qt.LeftButton, modifiers = Qt.NoModifier, delay = -1) |
Simulates dragging the mouse on an item with button pressed and optional modifiers The initial drag position is defined by x and y , and drag distance is defined by dx and dy 。若 delay is specified, the test will wait for the specified amount of milliseconds before releasing the button.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
另请参阅 mousePress (), mouseClick (), mouseDoubleClickSequence (), mouseMove (), mouseRelease (),和 mouseWheel ().
mouseMove ( item , x = item.width / 2, y = item.height / 2, delay = -1, buttons = Qt.NoButton) |
Moves the mouse pointer to the position given by x and y within item , while holding buttons if given. Since Qt 6.0, if x and y are not defined, the position will be the center of item .
若 delay (in milliseconds) is given, the test will wait before moving the mouse pointer.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
另请参阅 mousePress (), mouseRelease (), mouseClick (), mouseDoubleClickSequence (), mouseDrag (),和 mouseWheel ().
mousePress ( item , x = item.width / 2, y = item.height / 2, button = Qt.LeftButton, modifiers = Qt.NoModifier, delay = -1) |
Simulates pressing a mouse button with optional modifiers on an item . The position is defined by x and y 。若 x or y are not defined the position will be the center of item 。若 delay is specified, the test will wait for the specified amount of milliseconds before the press.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
另请参阅 mouseRelease (), mouseClick (), mouseDoubleClickSequence (), mouseMove (), mouseDrag (),和 mouseWheel ().
mouseRelease ( item , x = item.width / 2, y = item.height / 2, button = Qt.LeftButton, modifiers = Qt.NoModifier, delay = -1) |
Simulates releasing a mouse button with optional modifiers on an item . The position of the release is defined by x and y 。若 x or y are not defined the position will be the center of item 。若 delay is specified, the test will wait for the specified amount of milliseconds before releasing the button.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
另请参阅 mousePress (), mouseClick (), mouseDoubleClickSequence (), mouseMove (), mouseDrag (),和 mouseWheel ().
mouseWheel ( item , x , y , xDelta , yDelta , button = Qt.LeftButton, modifiers = Qt.NoModifier, delay = -1) |
Simulates rotating the mouse wheel on an item with button pressed and optional modifiers . The position of the wheel event is defined by x and y 。若 delay is specified, the test will wait for the specified amount of milliseconds before releasing the button.
The position given by x and y is transformed from the co-ordinate system of item into window co-ordinates and then delivered. If item is obscured by another item, or a child of item occupies that position, then the event will be delivered to the other item instead.
The xDelta and yDelta contain the wheel rotation distance in eighths of a degree. see QWheelEvent::angleDelta () 了解更多细节。
另请参阅 mousePress (), mouseClick (), mouseDoubleClickSequence (), mouseMove (), mouseRelease (), mouseDrag (),和 QWheelEvent::angleDelta ().
skip ( message = "") |
Skips the current test case and prints the optional
message
. If this is a data-driven test, then only the current row is skipped. Similar to
QSKIP(message)
in C++.
sleep ( ms ) |
Sleeps for ms milliseconds without processing Qt events.
另请参阅 wait () 和 waitForRendering ().
TouchEventSequence touchEvent ( object item ) |
Begins a sequence of touch events through a simulated touchscreen ( QPointingDevice ). Events are delivered to the window containing item .
The returned object is used to enumerate events to be delivered through a single QTouchEvent . Touches are delivered to the window containing the TestCase unless otherwise specified.
Rectangle { width: 640; height: 480 MultiPointTouchArea { id: area anchors.fill: parent property bool touched: false onPressed: touched = true } TestCase { name: "ItemTests" when: windowShown id: test1 function test_touch() { var touch = touchEvent(area); touch.press(0, area, 10, 10); touch.commit(); verify(area.touched); } } }
另请参阅 TouchEventSequence::press (), TouchEventSequence::move (), TouchEventSequence::release (), TouchEventSequence::stationary (), TouchEventSequence::commit (),和 QInputDevice::DeviceType .
tryCompare ( obj , property , expected , timeout = 5000, message = "") |
Fails the current test case if the specified property on obj is not the same as expected , and displays the optional message . The test will be retried multiple times until the timeout (in milliseconds) is reached.
This function is intended for testing applications where a property changes value based on asynchronous events. Use compare () for testing synchronous property changes.
tryCompare(img, "status", BorderImage.Ready) compare(img.width, 120) compare(img.height, 120) compare(img.horizontalTileMode, BorderImage.Stretch) compare(img.verticalTileMode, BorderImage.Stretch)
SignalSpy::wait () provides an alternative method to wait for a signal to be emitted.
另请参阅 compare () 和 SignalSpy::wait ().
tryVerify ( function , timeout = 5000, message = "") |
Fails the current test case if
function
does not evaluate to
true
before the specified
timeout
(in milliseconds) has elapsed. The function is evaluated multiple times until the timeout is reached. An optional
message
is displayed upon failure.
This function is intended for testing applications where a condition changes based on asynchronous events. Use verify () for testing synchronous condition changes, and tryCompare () for testing asynchronous property changes.
For example, in the code below, it's not possible to use
tryCompare
(), because the
currentItem
property might be
null
for a short period of time:
tryCompare(listView.currentItem, "text", "Hello");
Instead, we can use tryVerify() to first check that
currentItem
isn't
null
, and then use a regular compare afterwards:
tryVerify(function(){ return listView.currentItem }) compare(listView.currentItem.text, "Hello")
另请参阅 verify (), compare (), tryCompare (),和 SignalSpy::wait ().
verify ( condition , message = "") |
Fails the current test case if
condition
is false, and displays the optional
message
. Similar to
QVERIFY(condition)
or
QVERIFY2(condition, message)
in C++.
wait ( ms ) |
等待 ms milliseconds while processing Qt events.
另请参阅 sleep () 和 waitForRendering ().
|
若
windowOrItem
is an Item, this functions waits for
timeout
milliseconds or until
isPolishScheduled(windowOrItem)
返回
false
。返回
true
if
isPolishScheduled(windowOrItem)
返回
false
within
timeout
milliseconds, otherwise returns
false
.
若
windowOrItem
is a Window, this functions waits for
timeout
milliseconds or until
isPolishScheduled()
返回
false
for all items managed by the window. Returns
true
if
isPolishScheduled()
返回
false
for all items within
timeout
milliseconds, otherwise returns
false
.
This method was introduced in Qt 6.5.
另请参阅 isPolishScheduled (), QQuickItem::polish (),和 QQuickItem::updatePolish ().
waitForRendering ( item , timeout = 5000) |
等待
timeout
milliseconds or until the
item
is rendered by the renderer. Returns true if
item
is rendered in
timeout
milliseconds, otherwise returns false. The default
timeout
value is 5000.
warn ( message ) |
Prints
message
as a warning message. Similar to
qWarning(message)
in C++.
另请参阅 ignoreWarning ().