Swift test with CoreData in a Package

I'm getting an error running unit tests with swift test that succeed when I run them from Xcode. The units and my CoreData model are in a Swift Package. I'm loading the model using Bundle.module like so:

Code Block
Bundle.module.url(forResource: PersistenceController.modelName, withExtension: "momd")

The unit tests are able to load the CoreData model when run from Xcode and also using the xcodebuild test command line.

When I run the tests with swift test I get the following error:
Code Block
error: cannot find type 'MyEntity' in scope

Is there something more to be done to enable running CoreData unit tests from a Package using swift tests?

Replies

I'm glad I'm not the only one having this issue. It's like swift build doesn't even include the compiled .momd file (works just fine in Xcode!). I have tests that fail with

let modelPath = try XCTUnwrap(bundle.url(forResource: "TestModel", withExtension: "momd"), "Unable to find TestModel.momd")

and when I inspect the generated test bundles, I get the normal .xcdatamodeld. swift build appears to be missing a step that compiles Core Data models — something that xcodebuild knows how to do. It's likely this is intentionally decoupled from swift build and I have no idea how to fix it.

I think the problem you're having is because your package tests are in a different bundle. Packages define a separate test target in the Package.swift manifest.

To allow your tests to access resources, like the momd file, you'll need to declare a public symbol for them. This is similar to what you would need to do to access those resources from your app target.

For example, in a source file in your Swift package:

public static let momURL = Bundle.module.url(forResource: "MyModel", withExtension: "momd")

You can then use this to load the MOM in your unit tests:

let mom = NSManagedObjectModel(contentsOf: momURL!)
Add a Comment