How can I access a file inside of an XCTestCase?

I am trying to load a png file that is in the same folder as my test class. I use the code below but the call fails saying file does not exist.

try Data(contentsOf: URL(fileURLWithPath: "\(FileManager.default.currentDirectoryPath)media.png"))

I also tried creating an asset catalog into my test project and adding my file there, but no luck. This code fails as nil.

let mediaFile = NSDataAsset(name: "media")!.data

You shouldn't put resource files in the same directory as code. Are you using a swift package or an xcode project?

I have an xcode project that has a test project in it. Regardless I got it by doing this.

let fileImg = UIImage(named: "media", in: Bundle(for: ArweaveSvcMessageTests.self), compatibleWith: nil)
let mediaFileData = fileImg?.pngData()!

We've got the following helpers in a source file inside our Tests folder:

func fixtureData(for fixture: String) throws -> Data {
    try Data(contentsOf: fixtureUrl(for: fixture))

func fixtureUrl(for fixture: String) -> URL {

func fixturesDirectory(path: String = #file) -> URL {
    let url = URL(fileURLWithPath: path)
    let testsDir = url.deletingLastPathComponent()
    let res = testsDir.appendingPathComponent("Fixtures")
    return res

The #file default parameter resolves this to the source file's path. From there we resolve to the Fixtures directory inside Tests, which contains all manner of static data we want to load in for tests.

Hope that helps!

1 Like
Terms of Service

Privacy Policy

Cookie Policy