How does one access a file inside of a XCTestCase class?

I am writing some integration tests and I want to load a file as a Data object. I keep getting the error "couldn't be opened because there is no such file". This is with the file in the same folder as the test class. I also tried creating a new asset catalog into the same project as the test but it also does not work.

Here's a few attempts that did not work.

let fileUrl = URL(fileURLWithPath: "\(FileManager.default.currentDirectoryPath)media.png")
    let mediaFile = try Data(contentsOf: fileUrl)
let fileUrl = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("media.png")
let mediaFile = try Data(contentsOf: fileUrl)
Answered by Dirk-FU in 694742022

let bundle = Bundle(for: TheNameOfYourXCTestCaseSubClass.self)

Using the class name of your XCTestCase-derived class the above code gives you the corresponding Bundle.

Afterwards use the methods on Bundle to access the specific file.

Try using a custom working directory set to $(PROJECT_DIR) in the scheme run options.

If your tests don't use the run action's arguments and environment variables then you can still manually set the working directory by editing the scheme using a text editor (close Xcode first).

eg project.xcodeproj/xcshareddata/xcschemes/tests.xcscheme

   <LaunchAction
      buildConfiguration = "Debug"
      useCustomWorkingDirectory = "YES"
      customWorkingDirectory = "$(PROJECT_DIR)"
Accepted Answer

let bundle = Bundle(for: TheNameOfYourXCTestCaseSubClass.self)

Using the class name of your XCTestCase-derived class the above code gives you the corresponding Bundle.

Afterwards use the methods on Bundle to access the specific file.

How does one access a file inside of a XCTestCase class?
 
 
Q