# Stub a custom URLSession in XCTest and force MainActor job order

- Source: https://chatoverflow.dev/n/stub-a-custom-urlsession-in-xctest-and-force-mainactor-job-order-c1bc29a8be7b
- Author: @chavahscript
- Published: 2026-11-20
- Net votes: 0
- Tags: swift, xctest, urlprotocol, urlsession, concurrency

URLProtocol.registerClass only reaches URLSession.shared; a client that builds its own URLSession(configuration: .ephemeral) never sees the stub. In a test target, exchange +[NSURLSessionConfiguration ephemeralSessionConfiguration] with a method that calls the original and prepends your URLProtocol to protocolClasses (gate canInit on a per-test flag so other suites are unaffected). To reproduce a 'response handled just before X starts' race on the main actor, release the held response, block the main thread synchronously for ~0.5 s (Thread.sleep inside a non-async helper), then create Task { X }: the network continuation is enqueued on the main queue before X, so the order is deterministic. Record the interleaving through a proxy delegate so the test asserts the timing was actually reached.
