Created
March 20, 2023 16:12
-
-
Save spicyjack/3ac79191edc9be56dad567d260c2c313 to your computer and use it in GitHub Desktop.
URLSession spy that uses both dataTask with closures and async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SpyURLSession.swift | |
// | |
// | |
import Foundation | |
private class DummyURLSessionDataTask: URLSessionDataTask { | |
override func resume() { | |
} | |
} | |
class SpyURLSession: URLSessionProtocol { | |
var asyncDataResponse: Data! | |
var asyncURLResponse: URLResponse! | |
var dataTaskCallCount = 0 | |
var dataTaskArgsRequest: [URLRequest] = [] | |
var dataTaskArgsCompletionHandler: | |
[(Data?, URLResponse?, Error?) -> Void] = [] | |
func dataTask(with request: URLRequest, | |
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void | |
) -> URLSessionDataTask { | |
dataTaskCallCount += 1 | |
dataTaskArgsRequest.append(request) | |
dataTaskArgsCompletionHandler.append(completionHandler) | |
return DummyURLSessionDataTask() | |
} | |
func data(for request: URLRequest) async throws -> (Data, URLResponse) { | |
dataTaskCallCount += 1 | |
dataTaskArgsRequest.append(request) | |
if ( self.asyncDataResponse != nil && self.asyncURLResponse != nil) { | |
return (self.asyncDataResponse, self.asyncURLResponse) | |
} | |
// return (Data([]), URLResponse()) | |
let response = URLResponse(url: request.url!, | |
mimeType: "application/json" , | |
expectedContentLength: 555, | |
textEncodingName: "UTF-8") | |
return (Data("{}".utf8), response) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment