一些代码,我是单元测试需要加载一个资源文件。它包含以下一行:
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构建阶段,那么为什么它不能找到该文件呢?
当前回答
有一个找到文件的代码: 如何检查文件是否存在在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)
这不是测试文件是否创建在正确的位置,而是测试文件是否创建了。
其他回答
我必须确保设置了General Testing复选框
与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)
这不是测试文件是否创建在正确的位置,而是测试文件是否创建了。
当单元测试工具运行你的代码时,你的单元测试包不是主包。
即使您正在运行测试,而不是您的应用程序,您的应用程序包仍然是主要的包。(据推测,这可以防止您正在测试的代码搜索错误的包。)因此,如果您将一个资源文件添加到单元测试包中,那么在搜索主包时将找不到它。如果将上面的行替换为:
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *path = [bundle pathForResource:@"foo" ofType:@"txt"];
然后,代码将搜索单元测试类所在的包,一切正常。
如果你的项目中有多个目标,那么你需要在目标成员关系中不同的目标之间添加资源,你可能需要在不同的目标之间切换,如下图所示的3个步骤