在单元测试时删除fileManager(FileManager.default.removeItem)中的文件时出现问题

时间:2018-03-28 16:02:57

标签: ios swift caching xctest nsfilemanager

目前,文件未被删除存在问题。我查看了其他帖子:FileManager.default.removeItem not removing file [duplicate] Error deleting contents in directory - Domain=NSCocoaErrorDomain Code=4 | Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”

我收到相同的错误“没有这样的文件或目录”。当这个功能进行单元测试时,会发生这种情况:

 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
}


internal func filePathForFileName(name: String) -> String {
    let cyptoName = name.md5()
    return getCacheFolderPath() + "/" + (cyptoName ?? "")
}



func deleteFile(forFile fileName: String){
        let path = self.filePathForFileName(name: fileName)

        if self.fileExists(atPath: path) {
            do {
                try self.removeItem(atPath: path)
              //  print(path)
            } catch  {
                print(error.localizedDescription)
            }
        }
    }

这就是单元测试的样子:

func test_deleteFile(){

    let path = sut!.filePathForFileName(name: fileName)

    sut?.deleteFile(forFile: fileName)
    print(path)

    if sut!.fileExists(atPath: path){

    let filemanager = FileManager.default

           do {
    try filemanager.removeItem(atPath: path)

           } catch {
            print ("The file could not be removed: \(error)")
        }
    }
}

仅供参考我使用的是从FileManager子类化的mockFileSystem。即使我尝试在do,try,catch块中手动删除路径,它仍会返回错误“No such file or directory”。

0 个答案:

没有答案