我目前正在编写涉及缓存目录中文件的单元测试。发生的问题是第一次启动应用程序缓存相关测试失败时出现以下错误:
无法打开文件“5b063e275d506f65ebf1b02d926f19a4”,因为 没有这样的文件。
我认为原因是因为自第一次打开应用程序以来,缓存目录中没有任何内容。有没有办法在单元测试本身的缓存目录中插入文件,这样就不会抛出这个错误?
这是一个样本单元测试:
internal func filePathForFileName(name: String) -> String {
let cyptoName = name.md5()
return getCacheFolderPath() + "/" + (cyptoName ?? "")
}
internal func getCacheFolderPath() -> String {
var folderPath = ""
guard let path = self.urls(for:.cachesDirectory , in: .userDomainMask).last?.path else {
return folderPath }
folderPath = path + "/NetworkCache"
if !self.fileExists(atPath: folderPath) {
do {
try self.createDirectory(atPath: folderPath, withIntermediateDirectories: false, attributes: nil)
}
catch {
print(error.localizedDescription)
}
}
return folderPath
}
}
func saveData(data: Data, forFileName fileName: String, completionHandler: @escaping (URL?)->()) {
let url = URL(fileURLWithPath: self.filePathForFileName(name: fileName))
print("saveData:\(url)")
do {
try data.write(to: url, options: .atomic)
completionHandler(url)
} catch {
print(error.localizedDescription)
completionHandler(nil)
}
}
let filePath = "fileName"
func test_saveData(){
let promise = expectation(description: "Completion Hander invoked")
var isSaved: Bool?
let path = self.sut!.filePathForFileName(name: self.filePath)
sut?.saveData(data: mockData!, forFileName: filePath, completionHandler: {_ in
let fileManager = MockFileManager.default
if fileManager.fileExists(atPath: path) {
isSaved = true
print("FILE AVAILABLE")
} else {
isSaved = false
print("FILE NOT AVAILABLE")
}
promise.fulfill()
})
wait(for: [promise], timeout: 10, enforceOrder: true)
XCTAssertTrue(isSaved!)
}