【问题标题】:Access to project code from XCTestCase - UI Test从 XCTestCase 访问项目代码 - UI 测试
【发布时间】:2017-07-01 07:26:56
【问题描述】:

我正在尝试在我的项目中设置 UI 测试。我正在做一个 UI 测试,试图通过我的应用程序登录提示登录。为了确保在测试启动时显示登录提示,我尝试运行项目代码库中的ServerManager.logout()。这将导致在启动时显示登录提示。

import XCTest

class SmokeTest: XCTestCase {

    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.
        ServerManager.logout()
    }

    func testLogin() {

        let app = XCUIApplication()

        let emailTextField = app.textFields["email textfield"]
        emailTextField.tap()
        emailTextField.typeText("test@test.com")

        let passwordTextField = app.secureTextFields["password textfield"]
        passwordTextField.tap()
        passwordTextField.typeText("12345678")

        let loginButton = app.buttons["log in button"]
        loginButton.tap()
    }
}

我应该如何设置我的项目以访问ServerManager

当我在 ServerManager.swift 文件中检查 UITest 目标(称为 DonkeyProductionUITests)的 Target Membership 时,Xcode 开始抱怨该文件中的许多引用未为 UITest 目标定义。因此,我将项目中所有文件的 Target Membership 添加到 UITest Target,包括所有 CocoaPods。它解决了大多数问题。我还有一些奇怪的剩菜:

UITest 目标应该有哪些源文件作为“编译源”?

为什么 Xcode 突然无法识别 UIColorUIViewController 之类的类型?

【问题讨论】:

    标签: ios xcode xctest xcode-ui-testing


    【解决方案1】:

    只能在 UnitTests 中通过@testable import 访问您的项目代码。当您运行 UITests 时,这不起作用,因为在 UITest 期间,您的测试类无法访问您的应用程序代码。

    来自Apple's Docs

    UI 测试在根本上不同于单元测试。单元测试 使您能够在应用程序的范围内工作并允许您锻炼 可以完全访问您的应用程序变量的函数和方法,以及 状态。 UI 测试以与用户相同的方式练习您的应用程序的 UI 无需访问您应用的内部方法、函数和 变量。这使您的测试能够以与用户相同的方式查看应用程序 确实,暴露了用户遇到的 UI 问题。

    如果您想在测试后注销,您必须通过应用程序的用户界面进行操作:如果您的应用程序中的某处有注销按钮,请在测试结束时导航到那里并让测试tap() 它。

    【讨论】:

    • 太棒了,谢谢!但有点烦人.. 我只是想确保应用程序在测试启动时处于正确状态,但这似乎不是func setup() 的用例...您介意将链接添加到来自苹果?
    • 是的,有点不方便,但是没有办法解决。您必须在测试后使用您的应用程序的 UI 来重置您的。如果您需要在每次测试后执行此操作,您可以将该代码移至 tearDown()。这是文档的链接:developer.apple.com/library/content/documentation/…
    • 你不认为这是一个使用参数启动应用程序的解决方案吗,就像这个解决方案:stackoverflow.com/a/33466038/2299801 谢谢:)
    • 是的,您可以将参数从 UITest 传递到您的应用程序,但是您必须在您的应用程序中放入代码来检查参数是否存在,然后在没有任何用户交互的情况下注销用户。你可以这样做,但恕我直言,它有点脏。我还在我的 UITests 中使用环境变量,但只是为了模拟应用程序内部的现有行为(比如模拟失败的 API 调用)。而且您可能无论如何都必须对注销按钮进行 UITest,对吧?
    • 这是没有意义的,所以现在它预计会增加更多的复杂性,如果你正在运行 UITests。这使得 UI 测试毫无意义
    猜你喜欢
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多