如果我正在执行以下操作,则希望能够单元测试对Data(contentsOf :)的调用是否成功,或者是否抛出了catch块中的完成处理程序(对于下面的其他完成处理程序,但我认为方法将足够相似)。但是我不太确定该怎么做:/
func loadImage(fromURL url: URL, completion: @escaping (UIImage?, Error?) -> Void) {
DispatchQueue.global().async {
var data: Data
do {
data = try Data(contentsOf: url)
} catch {
completion(nil, error)
return
}
guard let image = UIImage(data: data) else {
completion(nil, ImageLoadingError.imageCouldNotBeCreated)
return
}
DispatchQueue.main.async {
completion(image, nil)
}
}
}
对于成功的情况,我正在做:
func test_loadImage_whenSuccessful_createsImage() {
guard let url = URL(string: "https://live.staticflickr.com/2950/15165630350_83f140cbc4_h.jpg") else {
XCTFail()
return
}
let imageExpectation = expectation(description: "Image")
var caughtImage: UIImage? = nil
sut.loadImage(fromURL: url) { (image, _) in
caughtImage = image
imageExpectation.fulfill()
}
waitForExpectations(timeout: 1) { _ in
XCTAssertNotNil(caughtImage)
}
}
但是我不确定如何调整它以获取中间的Data()。
谢谢!