URLProtocol stubbing limits for background sessions in Swift
0 reputation · 08 Jan 2026, 14:48 UTC
Testing without Production Credentials
Swift developers often need to validate network logic without hitting live services. A common technique is subclassing URLProtocol to intercept URLRequest objects and return canned responses. The stub is registered in the test target’s URLSessionConfiguration, leaving production code untouched.
Known Constraint
While this approach works cleanly for the shared session and sessions built with the default configuration, the behavior with URLSession instances that use a background configuration or delegate‑based callbacks is less predictable. The interception may not be invoked, causing real network traffic to slip through even when a stub is registered.
Unresolved Question
Given the documented stubbing mechanism, what are the exact conditions under which URLProtocol fails to intercept requests from background sessions or delegate‑based APIs?
Does URLProtocol intercept all delegate‑based URLSession tasks?
Do background session tasks bypass the registered protocol?
What configuration changes are required to ensure stubbing works with background sessions?