0

I've got a json file in my xcode project and I'm trying to read the file via:

let fileUrl = Bundle.main.url(forResource: "myfile", withExtension: "json")

and so on.

When I run this code from a file within the project target membership like a view controller file, the code runs and I'm able to read the json. However, when run it within my XCUITestCase file – it fails, unable to find the url.

How can I read the json file from within XCUItest?

I've taken a look at this post which hasn't helped Read local JSON file in XCUITest

leedex
  • 963
  • 8
  • 19

2 Answers2

4

a little modification of your code, and this works for me

if let file = Bundle(for: type(of: self)).url(forResource: "YOUR_FILE", withExtension: "json") {
    let data = try! Data(contentsOf: file)
    let dataJson = try! JSON(data: data)
    // TODO Your handle here
} else {
    XCTFail("Cannot read json file")
}
Fadielse
  • 381
  • 2
  • 12
  • Thank you for this. Do you know why Bundle(for: type(of: self)) allows for a correct url? I read that if the file is in the main target then Bundle.main should be used. – leedex Aug 09 '19 at 16:24
  • 1
    That's because the unit test is not a standalone app. With mainBundle you get something like /Applications/Xcode.app/Contents/Developer/Tools, but using bundleForClass gets you the bundle where your unit test class is located. – Fadielse Aug 09 '19 at 16:27
  • Ahh that makes sense. Thank you. I appreciate you taking the time to help me learn and get better. – leedex Aug 09 '19 at 16:31
0

Did you add this myfile.json to UITest target? This is the most common problem

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
  • yes I did. In the righthand panel under the paper icon, I selected the target membership to be both the project and the UITest. – leedex Aug 09 '19 at 15:35