gpt4 book ai didi

qt - Qt Quick 的单元测试

转载 作者:行者123 更新时间:2023-12-02 07:14:35 26 4
gpt4 key购买 nike

我对 Qt 和 Qt Quick 非常陌生。我正在验证 Qt Quick 的 Qt Test 单元测试框架,但我无法理解如何运行测试。这就是我所拥有的,我创建了一个具有以下结构的 SUBDIRS 项目:

ProjectSolution
ProjectSolution.pro
Project
Project.pro
Sources/main.cpp
Resources/qml.qrc/main.qml
ProjectTest
ProjectTest.pro
Sources/main.cpp
Resources/qml.qrc/main.qml
Resources/qml.qrc/tst_gui.qml

“Project”是要测试的应用程序,我的测试用例位于“ProjectTest/Resources/qml.qrc/tst_gui.qml”中。

tst_gui.qml:

import QtQuick 2.5
import QtTest 1.0

TestCase {
name: "UI Testcase"
when: windowShown

function test_button_click() {
mouseClick(click_button, Qt.LeftButton, Qt.NoModifier)
}

function test_key_press() {
keyClick(Qt.Key_Left)
keyClick("a")
}
}

我想在“Project/Resources/qml.qrc/main.qml”中模拟一个 id 为“click_button”的按钮。当我运行测试项目时,我收到失败消息:

FAIL!  : tst_gui::UI Testcase::test_button_click() Uncaught exception: click_button is not defined
C:\Users\sjayaprakash\Qt Test Projects\Qt Test Validation\QtTestValidation6\QtTestValidation6Test\tst_gui.qml(9) : failure location

我确信我做错了什么。有人可以帮忙吗?

最佳答案

终于,我成功了。测试用例无法找到该按钮,因为它位于不同的 QML 文件中。我尝试导入和使用属性别名,但都不起作用。我将所有内容复制到 tst_gui.qml(将 main.qml 留空),现在工作正常。

tst_gui.qml(更新):

import QtTest 1.0
import QtQuick 2.5
import QtQuick.Window 2.0
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Dialogs 1.2
import QtQml 2.2


Rectangle {
id: main_window
visible: true
width: Screen.width/2
height: Screen.height/2
color: "light grey"

Rectangle {

property alias click_button: click_button

id: click_button
width: main_window.width/4
height: main_window.height/14
color: "blue"
x: main_window.width/2 - click_button.width/2
y: main_window.height/2 - main_window.height/4
Text {
id: button_text
text: qsTr("Click!")
font.pointSize: 24
color: "white"
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
}

MouseArea {
anchors.fill: parent
onClicked: {
//Log to console as a proof of button click simulation
console.log("Button was clicked!")
}
}
}

TextArea {
id: textarea
width: main_window.width/2
height: main_window.height/8
x: main_window.width/2 - textarea.width/2
y: (main_window.height/2 - textarea.height/2) + main_window.height/8

focus: true
selectByKeyboard: true
textColor: "darkblue"
textFormat: TextEdit.PlainText
wrapMode: TextEdit.WrapAtWordBoundaryOrAnywhere

Keys.onLeftPressed: {
//Log to console as a proof of key press simulation
console.log("Left key was pressed!")
}
}


TestCase {
name: "UI Testcase"
when: windowShown

function test_button_click() {
mouseClick(click_button, Qt.LeftButton, Qt.NoModifier)
}

function test_key_press() {
keyClick(Qt.Key_Left)
}
}
}

在我的 main.cpp 中,我只是调用宏:

QUICK_TEST_MAIN("tst_gui")

编写单元测试的正确方法可能是将它们与实际代码分开。目前,这对我有用。

关于qt - Qt Quick 的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34747483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com