gpt4 book ai didi

ios - fileManager.createFileAtPath 在单元测试期间失败

转载 作者:行者123 更新时间:2023-11-30 11:37:09 26 4
gpt4 key购买 nike

目前,我正在尝试在单元测试期间创建文件,看看是否可以在创建后检索数据,但 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
}

最佳答案

使用 data.write(to:) 而不是创建文件有助于确定问题所在。看起来我正在创建一个文件夹作为文件路径并尝试将文件保存到该路径。由于它是一个文件而不是文件夹,因此它返回那里已经存在某些内容。

以下是完整的工作代码:

  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)
}

关于ios - fileManager.createFileAtPath 在单元测试期间失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49619370/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com