Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock URLSession.DataTaskPublisher

How can I mock URLSession.DataTaskPublisher? I have a class Proxy that require to inject a URLSessionProtocol

protocol URLSessionProtocol {
    func loadData(from url: URL) -> URLSession.DataTaskPublisher
}
class Proxy {

    private let urlSession: URLSessionProtocol

    init(urlSession: URLSessionProtocol) {
        self.urlSession = urlSession
    }

    func get(url: URL) -> AnyPublisher<Data, ProxyError> {
        // Using urlSession.loadData(from: url)
    }

}

This code was originally used with the traditional version of URLSession with the completion handler. It was perfect since I could easily mock URLSession for testing like Sundell's solution here: Mocking in Swift.

Is it possible to do the same with the Combine Framework?

like image 496
Tim Avatar asked Mar 04 '23 00:03

Tim


2 Answers

In the same way that you can inject a URLSessionProtocol to mock a concrete session, you can also inject a mocked Publisher. For example:

let mockPublisher = Just(MockData()).eraseToAnyPublisher()

However, depending on what you do with this publisher you might have to address some weirdnesses with Combine async publishers, see this post for additional discussion:

Why does Combine's receive(on:) operator swallow errors?

like image 141
Gil Birman Avatar answered Mar 05 '23 15:03

Gil Birman


The best way to test your client is to use URLProtocol.

https://developer.apple.com/documentation/foundation/urlprotocol

You can intercept all your request before she performs the real request on the cloud, and so creates your expectation. Once you have done your expectation, she will be destroyed, so you never make real requests. Tests more reliable, faster, and you got the control!

You got a little example here: https://www.hackingwithswift.com/articles/153/how-to-test-ios-networking-code-the-easy-way

But it's more powerful than just this, you can do everything you want like: Check your Events/Analytics...

I hope it'll help you!

like image 20
Christophe Bugnon Avatar answered Mar 05 '23 15:03

Christophe Bugnon