目前,我正在尝试在单元测试期间创建文件,以查看是否可以在创建数据后检索数据,但fileManager.createFileAtPath始终失败。我查看了这篇文章:fileManager.createFileAtPath always fails我实现了该答案的解决方案,但仍然失败了。这就是单元测试和附带功能的样子:
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 test_createFile(){
let path = sut?.getCacheFolderPath()
let fileManager = FileManager.default
if !FileManager.default.fileExists(atPath: path!) {
do {
try FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
}
let isFileCreated = fileManager.createFile(atPath: path!, contents: mockData, attributes: nil)
print(isFileCreated)//This always returns false
}
答案 0 :(得分:0)
使用data.write(to :)代替create file有助于确定问题所在。看起来我正在创建一个文件夹作为文件路径并尝试将文件保存到该路径。因为它是一个文件而不是文件夹,它返回的东西已经存在。
以下是完成的工作代码:
func saveData(data: Data, forFileName fileName: String, completionHandler: @escaping (URL?)->()) {
let url = URL(fileURLWithPath: self.filePathForFileName(name: fileName))
print("saveData:\(url)")
do {
// [data writeToFile:[self thdncFilePathForFileName:name] atomically:YES];
try data.write(to: url, options: .atomic)
completionHandler(url)
} catch {
print(error.localizedDescription)
completionHandler(nil)
}
}
func test_createFile(){
var isSaved: Bool = false
let path = sut?.getCacheFolderPath()
let promise = expectation(description: "Completion Hander invoked")
if !FileManager.default.fileExists(atPath: path!)
{
do {
try FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
}
sut?.saveData(data: mockData!, forFileName: filePath, completionHandler: { (url) in
let fileManager = MockFileManager.default
if fileManager.fileExists(atPath: self.sut!.filePathForFileName(name: self.filePath)) {
isSaved = true
print("FILE AVAILABLE")
} else {
isSaved = false
print("FILE NOT AVAILABLE")
}
promise.fulfill()
})
wait(for: [promise], timeout: 10, enforceOrder: true)
XCTAssertTrue(isSaved)
}