上一篇的 URLSessionProtocolMock 沒有處理到錯誤,這一篇加上 error 的 testing。
step1: URLSessionProtocolMock 中加上 Error? property
/// URLSessionProtocolMock.swift
/// handle error
var dataForDelegateError: Error?
step2: data(for:delegate) 的起始處,加上 error
func data(for request: URLRequest, delegate: URLSessionTaskDelegate?) async throws -> (Data, URLResponse) {
/// handle error at start
if let error = dataForDelegateError {
throw error
}
dataForDelegateRequest = request
guard let dataForDelegateReturnValue = dataForDelegateReturnValue else {
fatalError()
}
return dataForDelegateReturnValue
}
step3: 在 APIClientTests 寫下 Error 的測試
func testErrorHandleOnURLSessionProtocolMock() async throws {
let urlSessionMock = URLSessionProtocolMock()
let expect = NSError(domain: "", code: 1234)
urlSessionMock.dataForDelegateError = expect
sut.session = urlSessionMock
do {
_ = try await sut.getStockClosPriceList()
XCTFail("this test should get error")
} catch {
let nsError = try XCTUnwrap(error as NSError)
XCTAssertEqual(nsError, expect)
}
}
step4: 通過所有的測試