在另一个函数中测试一个函数

时间:2019-10-18 09:11:33

标签: swift

当我在Swift中使用文件时,我一直在测试深埋在另一个函数中的函数。

我将字符串写入URL:

func writeStringFromURLToBundle(bundle: String, stringURL: URL, withDestinationFileName dest: String, toDirectory directory: FileManager.SearchPathDirectory = .applicationSupportDirectory, _ fm: FileManagerProtocol = FileManager.default)  {
    let folderName = stringURL.lastPathComponent
    do {
        let fullURLPath = stringURL.appendingPathComponent(dest)
        let dataString = try String(contentsOf: fullURLPath)
        writeStringToDirectory(string: dataString, withDestinationFileName: dest, withSubDirectory: "\(bundle)/\(folderName)")
    } catch let error {
        print ("error \(error)")
    }
}

调用另一个函数writeStringToDirectory

func writeStringToDirectory(string: WritableStringProtocol, withDestinationFileName dest: String, toDirectory directory: FileManager.SearchPathDirectory = .applicationSupportDirectory, withSubDirectory: String) {
    if let destPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first {
        _ = createDirectory(toDirectory: directory, withSubDirectoryPath: withSubDirectory)
        let fullDestPath = NSURL(fileURLWithPath: destPath + "/" + withSubDirectory + "/" + dest)
        do {
            try string.write(to: fullDestPath as URL, atomically: true, encoding: .utf8)
        } catch let error {
            print ("error\(error)")
        }
    }
}

这就是我被困住的地方。我可以使用符合协议的字符串自行测试writeStringToDirectory

但是,我无法将此模拟的字符串传递给writeStringFromURLToBundle-我看不到实现此目的的方法。那么,除非我在writeStringFromURLToBundle中创建新参数,否则如何传递模拟的可写字符串?

WritableStringProtocol的详细信息及其模拟并不重要,因为实际上问题在于我正在测试的函数的结构-因此,如何将它们分开,以便第一个函数(即只是一个包装器而已)并不需要了解writeStringToDirectory所需的模拟功能。

0 个答案:

没有答案