DevPrep

All topics › Software testing

How to stub the network in tests: a protocol client or URLProtocol?

Middle PRO

The gist

The network is replaced at one of two levels. A protocol client: code depends on your own HTTPClient, and the test injects a stub that returns Data immediately. URLProtocol: code works with a real URLSession, but a URLProtocol subclass is registered in its configuration, intercepts requests and answers with canned data. The first approach tests logic above the network, the second tests the networking layer itself: building the URLRequest, headers, status codes and decoding.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store