首页 > 解决方案 > 如何在 SwiftUI 的 UI 测试中获取 EnvironmentObject/Publishers

问题描述

我正在尝试为 SwiftUI 标志页面编写 UI 测试,如果变量从 切换到 ,则尝试从类中检查发布falsetrue。我所做的是将应用程序作为模块导入,@testable import MyApp然后将此代码编写如下;

func testLogInOfAUser() throws {
    let email = app.textFields["email"]
    email.tap()
    email.typeText("email@mail.com \n")
    let password = app.secureTextFields["password"]
    password.tap()
    password.typeText("password \n")
    let loginBtn = app.buttons["Login"]
    loginBtn.tap()
    
    let sut = UserAuth()
    sut.login()

    XCTAssert(sut.isLoggedin == true)
    
}

UserAuth

class UserAuth: ObservableObject {
    @Published var isLoggedin:Bool = false
    
    func login() {
        self.isLoggedin.toggle()
    }
}

当我运行测试时,我遇到了这个错误;

Undefined symbols for architecture arm64:
  "type metadata accessor for MyApp.UserAuth", referenced from:
      MyAppUITests.MyAppUITests.testLogInOfAUser() throws -> () in MyAppUITests.o
  "MyApp.UserAuth.__allocating_init() -> MyApp.UserAuth", referenced from:
      MyAppUITests.MyAppUITests.testLogInOfAUser() throws -> () in MyAppUITests.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

标签: swiftunit-testingtestingswiftuixcode-ui-testing

解决方案


XCTest 是一个黑盒测试框架。因此,您只能按照用户与应用交互的方式与应用交互。

在您的情况下,您应该检查 UI 更改,例如登录后是否出现新屏幕等。

如果您仍需要深入研究您的应用程序,则应使用白盒测试框架。我建议您使用 EarlGrey 2.0,因为它与 XCTest 完全兼容,并且您可以保留所有现有代码。


推荐阅读