如何在 Test Bundle swift 中包含文件



我有 json 文件,我想包含在测试包中,这样我就可以为我的测试读取这个 json。

所以我创建了一个名为"test.json"的文件,它在我的测试文件夹中。

现在我想读取这个文件。我是这样读的,这里的代码在测试包的测试文件中:

 let bundle = Bundle(for: type(of: self))
 var url = bundle.url(forResource: "test", withExtension: "json")

网址每次都为零。我发誓该文件就在那里,如果我在 finder 中打开它,它与 test-info.plist 位于同一目录下。我什至尝试了主要捆绑包,但它仍然是零!!

这个文件在哪里????

试试这个:

let bundle = Bundle(for: YourTestClass.self)
let path = bundle.path(forResource: "test", ofType: "json")
let data = try Data(contentsOf: URL(fileURLWithPath: path))

最新更新