在XCUITest中读取本地JSON文件

问题描述:

我正在为iOS应用程序编写UI测试.我想从本地json文件读取数据.

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

我正在使用以下代码来获取我的json文件的路径:

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

我已尝试将解决方案用于以下stackoverflow问题: 使用Swift读取JSON文件.没用!

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

我还查看了以下Apple文档: https://developer.apple.com/swift/blog/?id=37

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

任何帮助将不胜感激!

首先,您需要检查.json文件是否与测试文件位于同一目标中.如果文件在主要目标中,则必须使用Bundle.main.但是,如果它与您的测试位于同一目标中,请使用以下代码.

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