Mocking URLSessionDataTask without using init

Viewed 1100

I'm trying to mock my URLSession instance and after researching on StackOverflow, I've seen that one approach is to create a mocked URLSessionDataTask and call the completion handler on resume():

class URLSessionDataTaskMock: URLSessionDataTask {
    private let closure: () -> Void

    init(closure: @escaping () -> Void) {
        self.closure = closure
    }

    override func resume() {
        closure()
    }

    override func cancel() {
        closure()
    }
}

class URLSessionMock: URLSession {
    typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void
    var data: Data?
    var error: Error?
    override func dataTask(
        with _: URLRequest,
        completionHandler: @escaping CompletionHandler
    ) -> URLSessionDataTask {
        let data = self.data
        let error = self.error
        return URLSessionDataTaskMock {
            completionHandler(data, nil, error)
        }
    }
}

The problem I'm facing is that URLSessionDataTask.init has been deprecated as of iOS 13:

'init()' was deprecated in iOS 13.0: Please use -[NSURLSession dataTaskWithRequest:] or other NSURLSession methods to create instances

Is there an updated approach to achieve the same goal?

0 Answers
Related