Read local JSON file in XCUITest

橙三吉。 提交于 2019-12-11 07:29:28

问题


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!


回答1:


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



回答2:


That's not how you read local json files from Bundle in iOS. It's done in the following way:

// "myUrl" is assumed to be your json file name 

if let pathStr: String = Bundle.main.path(forResource: "myurl", ofType: ".json") {
    print("json path: \(pathStr)")
}



回答3:


I just found resources added to XCUITest targets will be placed under Bundle.main.resourcePath + "/PlugIns/<TARGET_NAME>.xctest/". However, I'm not sure if there were better ways to access them rather than hard-coding the sub-directory path.



来源:https://stackoverflow.com/questions/42309402/read-local-json-file-in-xcuitest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!