I'm trying to use @EnvironmentObject in my UITests, but I get an error at runtime.
Thread 1: Fatal error: No ObservableObject of type Person found. A View.environmentObject(_:) for Person may be missing as an ancestor of this view.
Doesn't Work
The following code throws the error mentioned above when running the UITest.
import SwiftUI
@main
struct RootView: App {
var body: some Scene {
WindowGroup {
AppView()
.environmentObject(Person())
}
}
}
class Person: ObservableObject {
@Published var name = "Lex"
}
UITest
import XCTest
import SwiftUI
class AppTests: BaseUITest {
@EnvironmentObject var person: Person
func testPerson() {
assert(person.name == "Lex")
}
}
// For your info.
class BaseUITest: XCTestCase {
let app = XCUIApplication()
override func setUpWithError() throws {
continueAfterFailure = false
app.launch()
}
}
Current alternative: global variable
The following code works just fine.
import SwiftUI
var person = Person()
@main
struct RootView: App {
var body: some Scene {
WindowGroup {
AppView()
.environmentObject(person)
}
}
}
import XCTest
class AppTests: BaseUITest {
func testPerson() {
assert(person.name == "Lex")
}
}
My Goal
My goal is to step away from the usage of global variables, as those are a code smell. I'm trying to resolve my code smells.
The answer I'm looking for can be:
- A solution to allow the usage of @EnvironmentObject in my UITests!
- An explanation as to why this is not possible and/or an alternative solution to both global variables and @EnvironmentObject that works, looks clean and is not a different code smell.