1

I have json file that I want to include in the test bundle so I can just read this json for my tests.

So I created a file called "test.json", it is in my Tests folder.

Now I want to read this file. I am reading it like this, the code here is in the test file in test bundle:

 let bundle = Bundle(for: type(of: self))
 var url = bundle.url(forResource: "test", withExtension: "json")

the url is nil every single time. I swear that file is there, if I open it in finder, it's under the same directory as the test-info.plist. I even tried the main bundle but it is still nil!!

Where is this file????

Anna
  • 443
  • 9
  • 29

1 Answers1

7

Try this:

let bundle = Bundle(for: YourTestClass.self)
let path = bundle.path(forResource: "test", ofType: "json")
let data = try Data(contentsOf: URL(fileURLWithPath: path))
Adam Bardon
  • 3,829
  • 7
  • 38
  • 73
  • 1
    This is the exact correct answer, and should be selected as the answer. – Mostafa Al Belliehy Sep 10 '21 at 15:53
  • 1
    Make sure you select "Copy Files If Needed, "Create Groups", and specify your test target if you're using the JSON for unit testing. – Adrian Aug 10 '22 at 04:27
  • If you need the url of a resource, you can use: ```swift guard let fileUrl = Bundle(for: YourTestClass.self).url(forResource: "jsonFile", withExtension: "json") else { fatalError("jsonFile.json not found.") } ``` – Heitara Jun 23 '23 at 23:00