一些代码,我是单元测试需要加载一个资源文件。它包含以下一行:
NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"txt"];
在应用程序中,它运行得很好,但当由单元测试框架运行时,pathForResource:返回nil,这意味着它无法找到foo.txt。
我已经确保foo.txt包含在单元测试目标的Copy Bundle Resources构建阶段,那么为什么它不能找到该文件呢?
一些代码,我是单元测试需要加载一个资源文件。它包含以下一行:
NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"txt"];
在应用程序中,它运行得很好,但当由单元测试框架运行时,pathForResource:返回nil,这意味着它无法找到foo.txt。
我已经确保foo.txt包含在单元测试目标的Copy Bundle Resources构建阶段,那么为什么它不能找到该文件呢?
当前回答
我必须确保设置了General Testing复选框
其他回答
我必须确保设置了General Testing复选框
就像我这样的人,在最初的帖子中错过了这一点:
确保foo。md包含在单元测试目标的Copy Bundle Resources构建阶段中
如果你的项目中有多个目标,那么你需要在目标成员关系中不同的目标之间添加资源,你可能需要在不同的目标之间切换,如下图所示的3个步骤
与swift swift 3的语法自我。dynamicType已弃用,请改用此类型
let testBundle = Bundle(for: type(of: self))
let fooTxtPath = testBundle.path(forResource: "foo", ofType: "txt")
or
let fooTxtURL = testBundle.url(forResource: "foo", withExtension: "txt")
有一个找到文件的代码: 如何检查文件是否存在在Swift的文档目录?
我在一个测试中使用它,如下所示,测试我的文件是否被创建,并为进一步测试提供其位置。
let fileFound = XCTestExpectation (description: "Checking for DB File Found")
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("filename.ext") {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
fileFound.fulfill()
print("DB FILE AVAILABLE")
} else {
print("DB FILE NOT AVAILABLE")
}
} else {
print("DB FILE PATH NOT AVAILABLE")
}
wait(for: [fileFound], timeout: 5)
这不是测试文件是否创建在正确的位置,而是测试文件是否创建了。