在XCUITest中读取本地JSON文件

Kus*_*ogi 1 json ios xctest swift3 xcode8.2

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

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

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")
    }
Run Code Online (Sandbox Code Playgroud)

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

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

任何帮助将不胜感激!

Rya*_*yan 6

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

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