79589255

Date: 2025-04-23 18:22:12
Score: 7 đŸš©
Natty:
Report link

1) Where should I put the files in the project?

This turns out to be flexible. I ended up putting my files in a directory I named “SampleFiles”, inside my “Tests” directory (which contains separate directories for each test target, such as unit tests and UI tests).

Important: The key to having the files available through the bundle is to ensure they are included in the “Copy Bundle Resources” phase of the “Build Phases” tab for the target.

  1. Open the Project Navigator (the first tab in the sidebar on the left in the Xcode window, shortcut: ⌘-1).
  2. Open the project at the top of the project navigator sidebar.
  3. Select the target (in my case, I want my sample files included in the bundle resources for the unit tests target).
  4. Select the “Build Phases” tab.
  5. In the “Copy Bundle Resources” section, ensure the file(s) is included.

2) How should I get the bundle that contains the sample files?

If the resources are in the app’s main bundle, just use Bundle.main.

But if they are in a different target bundle, I haven’t found a better answer than this “brute force” approach, which requires there be a known file in the bundle resources (in this example, sample.file):

private static func findSampleBundle() -> Bundle? {
    for bundle in Bundle.allBundles {
        if bundle.url(forResource: "sample", withExtension: "file") != nil {
            return bundle
        }
    }
    return nil
}

3) Where do I put the files in the Xcode project to have them added to the test bundle?

See question 1.

4) How do I get access to the test bundle when using swift-testing (not XCTest)?

See question 2.

5) How do I get the URL for a given file in the test bundle?

Having got the bundle (answer to question 2):

let sampleFileURL = bundle.url(forResource: "sample", withExtension: "file")

6) Alternatively, is there a way, when using swift-testing in Xcode, to give the test runner permission to read the sample files (overriding the sandbox limitations)?

No answer yet.

Reasons:
  • Blacklisted phrase (1): How do I
  • Blacklisted phrase (1): is there a way
  • Blacklisted phrase (1.5): Where should I
  • Blacklisted phrase (1): How should I
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Grant Neufeld