ios - 如何用 `downloadTask` 为 `completionHandler ` 编写单元测试?

标签 ios swift unit-testing nsurlsession xctestexpectation

这是我的下载函数:

// Download a file from the url to the local directory
class func downloadUrl(url: URL, to dirUrl: URL, completion: (() -> ())?){
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    let request = URLRequest(url: url)

    let task = session.downloadTask(with: request) {(tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success, copy the downloaded file from the memory to the disk
            print("Finished downloading!")
            do {
                try FileManager.default.copyItem(at: tempLocalUrl,to:
                    dirUrl.appendingPathComponent((response?.suggestedFilename)!))
                if completion != nil {
                    completion!()
                }
            } catch (let writeError) {
                print("Fliled to write file \(dirUrl) : \(writeError)")
            }
        } else {
            print("Failure: \(String(describing: error?.localizedDescription))")
        }
    }
    task.resume()
}

我想写一个单元测试方法来测试它是否从url下载文件到dirUrl

func testDownloadUrl(){
    let fm = FileManager.default
    let url = URL(string: "https://raw.githubusercontent.com/apple/swift/master/README.md")
    fileDownloader.downloadUrl(url: url!, to: fm.temporaryDirectory, completion: nil)

    // Check the contents of temp file
    let tempContents = try? fm.contentsOfDirectory(atPath: fm.temporaryDirectory.path)
        print("Contents: \(tempContents)")
    }

但是没有输出“Finished downloading!”或“失败...”,即使我通过了单元测试,所以我猜在这个测试用例中没有调用 completionHandler。

我的问题是如何让单元测试方法等到下载任务完成?

最佳答案

标准习语是使用Xcode asynchronous testing APIs , 主要是 XCTestExpectation类(class)。这些从 Xcode 6 开始可用,因此,如果您使用的是最新版本,您应该被覆盖 ;)

通用的异步测试模板如下:

func testAsyncFunction() {
    let asyncDone = expectation(description: "Async function")
    ...
    someAsyncFunction(...) {
        ...
        asyncDone.fulfill()
    }
    wait(for: [asyncDone], timeout: 10)
    /* Test the results here */
}

这将阻止您的测试执行,直到上述功能完成(指定的超时已过)。

关于ios - 如何用 `downloadTask` 为 `completionHandler ` 编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126023/

相关文章:

ios - 从我的服务器加载的图片在 iPad 应用程序上有错误的颜色

ios - 如何在 iOS 7 中超过 180 秒的后台运行 NSTimer?

swift - 使用 SwiftyJSON 和 Alamofire 循环 JSON

swift - 如何清除 Swift 中的终端屏幕?

python - uwsgi下运行的单元测试Flask应用

java - Intellij IDEA - 测试时大量内存使用

ios - 将格式化的测量值限制为 2 位数字

iphone - ios游戏制作 mask 层效果

ios - isRegisteredForRemoteNotifications 即使注册成功也返回 false

php - PHP 应用程序的单元、集成和系统测试