Search code examples
jsonswiftxcodexcuitest

How to read Json file from XCUITest?


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


Solution

  • 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")
    }