从 XCTestCase 访问项目代码 - UI 测试

Access to project code from XCTestCase - UI Test

我正在尝试在我的项目中设置 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 文件上检查 UI 测试目标(称为 DonkeyProductionUITests)的目标成员资格时,Xcode 开始抱怨其中有很多参考UI测试目标的文件未定义。因此,我将项目中所有文件的目标成员资格添加到 UI 测试目标,包括所有 CocoaPods。它解决了大多数问题。我还有一些奇怪的剩菜:

UI测试目标应该有哪些源文件作为"Compile Sources"?

为什么 UIColorUIViewController 突然无法被 Xcode 识别?

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

来自Apple's Docs

UI testing differs from unit testing in fundamental ways. Unit testing enables you to work within your app's scope and allows you to exercise functions and methods with full access to your app's variables and state. UI testing exercises your app's UI in the same way that users do without access to your app's internal methods, functions, and variables. This enables your tests to see the app the same way a user does, exposing UI problems that users encounter.

如果你想在测试后注销,你必须通过你的应用程序的用户界面来完成:如果你的应用程序中有一个注销按钮,在你的测试结束时导航到那里并让测试 tap()它。