Load bundle resources in UI Tests

I want to load images from my bundle, which works fine when running the main app. However this does not work when running UI Tests. I read that the test bundle is not the main bundle when running tests. I try loading the bundle via this snippet:

let bundle = Bundle(for: Frames_HoerspielUITests.self)

This is my test class wrapped these the canImport statements so it can be added to the main app target and used for getting the correct bundle:

#if canImport(XCTest)
import XCTest

final class Frames_HoerspielUITests: XCTestCase {
    override func setUpWithError() throws {
        continueAfterFailure = false
    }

    override func tearDownWithError() throws { }

    @MainActor
    func testExample() throws {
        let app = XCUIApplication()
        app.launch()
    }

    @MainActor
    func testLaunchPerformance() throws {
        measure(metrics: [XCTApplicationLaunchMetric()]) {
            XCUIApplication().launch()
        }
    }
}
#else
final class Frames_HoerspielUITests { }
#endif

However while this works when running the main app, it still fails in the UI tests. It is a SwiftUI only app. and I can't add the images to the asset catalog because they are referenced from another location.

Any ideas? Thank you

Answered by DTS Engineer in 849436022

A UI test is a bundle. That bundle is loaded by the test runner. This is completely separate from the app under test. If you get Bundle.main in your UI test, you get the bundle of the test runner. If you do the bundle-for-class thing within a class in your UI test, you get the bundle of the UI test itself. If you want a resource to be available there, add that resource to the UI test bundle itself.

IMPORTANT You can’t fetch the resource from the app’s bundle because there’s no guarantee you have permission to access its bundle. If your app also needs this resource, you’ll have to add it to both the app and the UI test target.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

A UI test is a bundle. That bundle is loaded by the test runner. This is completely separate from the app under test. If you get Bundle.main in your UI test, you get the bundle of the test runner. If you do the bundle-for-class thing within a class in your UI test, you get the bundle of the UI test itself. If you want a resource to be available there, add that resource to the UI test bundle itself.

IMPORTANT You can’t fetch the resource from the app’s bundle because there’s no guarantee you have permission to access its bundle. If your app also needs this resource, you’ll have to add it to both the app and the UI test target.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Load bundle resources in UI Tests
 
 
Q