【发布时间】:2020-05-03 22:37:52
【问题描述】:
我正在尝试在我的 Xcode 11 项目上运行 UI 测试(以在整个 fastlane 中生成快照),但我面临着一个相当奇怪的情况。
当我运行测试时,应用程序在显示主页后立即崩溃,并出现错误:
Fatal error: No ObservableObject of type TabCommands found. A View.environmentObject(_:) for TabCommands may be missing as an ancestor of this view.: file SwiftUI, line 0
但是在正常运行应用时,我没有这个错误。
这是应用程序的层次结构:
Scene Delegate 使用环境对象构建视图
let contentView = ContentView()
.environmentObject(UserManager())
.environmentObject(TabCommands())
.environmentObject(IAPStore())
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
内容视图使用基于 UIViewControllerRepresentable 的 TabView:
var body: some View {
UIKitTabView([
UIKitTabView.Tab(view: NavigationView {
HomeContentView()
Spacer()
}, title: "menu_home".localized(), image: "house"),
UIKitTabView.Tab(view: NavigationView {
SearchView()
Spacer()
}, title: "menu_home".localized(), image: "magnifyingglass"),
UIKitTabView.Tab(view: NavigationView {
UserTabRootLoading()
Spacer()
}, title: "menu_home".localized(), image: "person.crop.circle"),
])
.edgesIgnoringSafeArea(.bottom)
.edgesIgnoringSafeArea(.top)
}
崩溃发生在 SearchView 主体内部,在导航链接中使用 EnvironmentVariable 对象作为isActive 状态(以便稍后在不传递值的情况下弹出 3 个视图)。
struct SearchView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@EnvironmentObject var tabCommands: TabCommands
@EnvironmentObject var userManager: UserManager
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
NavigationLink(destination: PremiumView()
.navigationBarTitle("")
.navigationBarHidden(true),
isActive: self.$tabCommands.isStartPremiumViewActive) {
EmptyView()
}.isDetailLink(false)
}
}
(我删除了其余代码)
TabCommand 是一个有 6 行的 ObservableObject @Published var myVar = false
同样,当我在模拟器或设备上运行应用程序时,应用程序按预期运行,问题仅在我启动 UI 测试时出现。
当我尝试一个简单的测试时
let app = XCUIApplication()
app.launch()
测试成功。当我添加第一行 app.staticTexts["MainButton"].tap() 时它失败了
场景委托中是否需要进行一些配置以启用环境对象或其他东西?
【问题讨论】: