swift - 如何创建一个在 XCTest 中定义按钮或文本字段的 swift 文件?

标签 swift user-interface xctest

如何在 XCTest 中创建定义按钮或文本字段的 swift 文件?我有一个文件 UITest.我想在其他 swift 文件中定义 UITest 中的元素,但这是错误的。这就是我正在寻找的:

import Foundation

class HomeVC{

    let app = XCUIApplication()
    let tabBarsQuery = app.tabBars
    let tablesQuery = app.tables

    let btn = app.buttons["a"]
    let btn2 = app.buttons.element(boundBy: 0)
    let txt = app.tables.staticTexts["a"]

}

我想在我的 UI 测试中使用这些元素:

import XCTest

class UITests: XCTestCase {

    let config = TestConfig()
    let log = Log()

    override func setUp() {
        super.setUp()

        // Put setup code here. This method is called before the invocation of each test method in the class.

        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = false
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()

        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()

    }
    func testExample() {

    //Call HomeVC
    let homeVC = HomeVC()
    homeVC.btn.tap()
    homeVC.btn2.tap()
    homeVC.txt.tap()
}

有什么解决办法吗?请指导我找到正确的解决方案。 谢谢大家!

最佳答案

在您当前的代码中,那些属于 XCUIElement 而不是 XCUIElementQuery 的常量会在 HomeVC 类初始化时立即解析。如果初始化 HomeVC 时按钮不全部存在,则这些属性将无法使用。

可以使属性变得惰性,这意味着它们将在首次使用时解析,而不是在对象初始化时解析,但这不是可扩展模型。

应该使用页面对象模型,在其中为每个离散页面创建一个类。该类可以封装不同元素的所有路径和标识符,并将元素公开为计算属性。这意味着每次访问元素查询时都将使用当时最新的 View 层次结构进行解析。

我的博客上有关于在 Swift 中使用 XCTest 实现页面对象模型的更多信息:http://qualitytesting.tumblr.com/post/144462182209/xctest-and-the-page-object-model

关于swift - 如何创建一个在 XCTest 中定义按钮或文本字段的 swift 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40145670/

相关文章:

ios - 从命令行为 iOS 应用程序运行单独的 XCTest(UI、单元)测试用例

ios - 如何在 Swift 中以编程方式调整 UILabel 行间距?

user-interface - 用于实验 OpenCV 的 GUI 发生了什么变化?

ios - 从 XCTest 访问主要应用程序数据

xcode - 如何从 faSTLane 只运行一个 ui-test?

python - pyqt:向 QFileSystemModel 添加自定义列

ios - 如何知道用户是否共享了我的应用程序?

ios - 从 Swift 4 中的后台线程调用并运行 Firebase 4 的 UI API

ios - Swift:如何访问某个 tableView 部分中自定义单元格中的标签

mysql - Ubuntu 上用于查看和编辑 MySQL 数据库中的表的简单用户界面