Access file in tests with swift-testing

I am adding tests using swift-testing to a parser library and would like to access files.

What is the recommended way to do that ? Is using the SwiftPM Resource.copy then Bundle.module.path(...) facility the way to go ?

Hi @mlienert, yes, when writing tests in a Swift package, I'd recommend that approach to access files as resources in the test target. Or you can use Bundle.module.url(forResource: ...), but the general idea is to ask for the location from Bundle.module.

Thank you for your feedback !

Does anyone know how I'd do this for an app developed in Xcode? Bundle.module.load gives the error Type 'Bundle' has no member 'module' for me.

The Bundle.module accessor is a SwiftPM feature: SwiftPM generates this accessor for targets that have a non-empty resources: argument in their target definition.

Because it's a SwiftPM feature, Bundle.module is not available for targets defined in an Xcode project. For a typical app test target defined in an Xcode project, you can probably use the Bundle(for class: AnyClass) initializer, passing in some class in your target that's visible to Objective-C. (I forget whether Bundle.main in an app unit test target will return the bundle for the tests or the main app bundle.)

If you're talking about a test target defined via SwiftPM (i.e. in a Package.swift file), Bundle.module should work even when you run the tests in Xcode (provided the test target has any resources defined).

2 Likes

Something we probably ought to do with our is to add a Bundle instance that points at the test target explicitly. Something like:

extension Bundle {
  public static var testContent: Self { get }
}

We can't do that today because it creates a cyclical dependency between Foundation and Swift Testing (sad trombone) but we're looking at setting up what Swift calls a "cross-import overlay": a tertiary module with its own dependency graph that's automatically imported if you import two other modules (in this case, Testing and Foundation.)

2 Likes

Thanks, I was able to use the traditional Bundle(for: TestClass.self) where TestClass is an @Suite with swift-testing to get something working.

1 Like