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

10-08 15:41