Search code examples
iosjsonswift3xctestxcode8.2

Read local JSON file in XCUITest


I am writing UI tests for iOS application. I want to read data from a local json file.

I am using the following code to get the path for my json file:

func testExample() {

    readJSON()
}

func readJSON(){
    let bundle = Bundle(for:myTestClass.self)
    if let path = bundle.url(forResource: "myurl", withExtension: "json"){
        print("Got the path")
        print(path)
    }
    else{
        print("Invalid filename/path")
    }

I have tried using the solution for the following stackoverflow question : Reading in a JSON File Using Swift. Didn't work!

Also, I had a look at the following Apple documentation: https://developer.apple.com/swift/blog/?id=37

Any help would be greatly appreciated!


Solution

  • First of all, you need to check the .json file is in the same target with the test file. If the file is in the main target, you have to use Bundle.main. However if it is in the same target with your test, use the below code.

    let t = type(of: self)
    let bundle = Bundle(for: t.self)
    let path = bundle.path(forResource: "myurl", ofType: "json")