I’m building out a SwiftData model in the preliminary stages of app development. I’m using test-driven development (tdd) to iterate on the model and iron out kinks prior to integrating the model into the app itself.
Working with the classes works fine until I add the @Model
declaration. But once the classes have been added to SwiftData, I’m unable to test them without an “active container”.
import SwiftData
@Model
class StringContainer {
let string: String
init(_ string: String) {
self.string = string
}
}
class Tester: XCTestCase {
func testSwiftData() throws {
let container = StringContainer("foo")
XCTAssertEqual(container.string, "foo")
}
}
The test case crashes with the error:
Thread 1: Fatal error: failed to find a currently active container for StringContainer
@Transient private var _$backingData: any SwiftData.BackingData<StringContainer> = StringContainer.createBackingData()
What’s the easiest and simplest way to get a SwiftData stack set up within tests, just to test objects? I do not care about actually persisting the data or running queries, as SwiftData / Core Data provides in the real app. I just want to construct and test each class independently.