A simple URLSession mock
There are so many people advocating for the use of URLProtocol for mocking HTTP requests in Swift that I couldn’t believe how quickly it fell apart for me. In fact, I found more writing about using URLProtocol as a mock than I did about using URLProtocol for its intended purpose. This post is about the shortcomings that I encountered, and how I solved them by mocking URLSession instead.
The trouble with URLProtocol
Most of the posts advocating for mocking with URLProtocol recommend storing a single request handler as a static variable on the URLProtocol subclass. The closure gives you a chance to assert against the request and inject a specific response or raise an exception. I like that this approach lets me keep all of my #expect
and #require
calls in the test function, but I ran into trouble using it to test my API client. One method implements the pretty common pattern of getting a pre-signed S3 URL from my API, and then using that URL to upload some data to a bucket. These two requests have to happen every time I upload something, so it made sense to treat them as a single method in the client rather than exposing the two-step process.
Better networking while traveling
As I was preparing to travel to a family wedding recently, I decided to take action on an item that has been on my to-do list for some time: get better internet access for my devices while traveling.
Motivation
Hotel Wi-Fi is such a pain. I travel with a stupid number of devices, and getting all of them connected can take a lot of effort. At home each TV has a Chromecast with Google TV for streaming, but getting one connected to hotel Wi-Fi is usually an exercise in frustration. If we can manage to connect it, Caroline is stuck watching the morning news for wherever we happen to be because of silly content restrictions.