Testing the iOS Network Layer: URLSession Mocking and URLProtocol
Testing networking code in iOS without hitting real servers requires intercepting URLSession requests. The official Apple mechanism for this is URLProtocol—a class you subclass to handle any URL request made through a configured URLSession. This gives you full control over responses, errors, delays, and headers.
Why URLProtocol over Mocking URLSession Directly
You could inject a mock URLSession via a protocol, but this has limits: you're mocking the interface, not testing the actual URLSession behavior (redirects, cookies, caching, auth challenges). URLProtocol intercepts at a lower level, so your real URLSession code runs—only the network I/O is replaced.
Implementing MockURLProtocol
// MockURLProtocol.swift
import Foundation
class MockURLProtocol: URLProtocol {
// Stub response per URL
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
override class func canInit(with request: URLRequest) -> Bool {
return true // Handle all requests
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
guard let handler = MockURLProtocol.requestHandler else {
client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse))
return
}
do {
let (response, data) = try handler(request)
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
} catch {
client?.urlProtocol(self, didFailWithError: error)
}
}
override func stopLoading() {}
}
// Helper to create a URLSession that uses MockURLProtocol
extension URLSession {
static var mock: URLSession {
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [MockURLProtocol.self]
return URLSession(configuration: config)
}
}Basic Network Test
// APIClient.swift
struct APIClient {
let session: URLSession
let baseURL: URL
init(session: URLSession = .shared, baseURL: URL) {
self.session = session
self.baseURL = baseURL
}
func fetchUser(id: String) async throws -> User {
let url = baseURL.appendingPathComponent("users/\(id)")
let (data, response) = try await session.data(from: url)
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
guard httpResponse.statusCode == 200 else {
throw APIError.httpError(statusCode: httpResponse.statusCode)
}
return try JSONDecoder().decode(User.self, from: data)
}
}// APIClientTests.swift
import XCTest
@testable import MyApp
class APIClientTests: XCTestCase {
var sut: APIClient!
let baseURL = URL(string: "https://api.example.com")!
override func setUp() {
sut = APIClient(session: .mock, baseURL: baseURL)
}
override func tearDown() {
MockURLProtocol.requestHandler = nil
}
func testFetchUserReturnsDecodedUser() async throws {
let expectedUser = User(id: "1", name: "Alice", email: "alice@example.com")
let userData = try JSONEncoder().encode(expectedUser)
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: ["Content-Type": "application/json"]
)!
return (response, userData)
}
let user = try await sut.fetchUser(id: "1")
XCTAssertEqual(user.name, "Alice")
XCTAssertEqual(user.email, "alice@example.com")
}
func testFetchUserThrowsOn404() async {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(
url: request.url!,
statusCode: 404,
httpVersion: nil,
headerFields: nil
)!
return (response, Data())
}
do {
_ = try await sut.fetchUser(id: "nonexistent")
XCTFail("Expected APIError.httpError(404)")
} catch APIError.httpError(let statusCode) {
XCTAssertEqual(statusCode, 404)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
func testFetchUserThrowsOnNetworkError() async {
MockURLProtocol.requestHandler = { _ in
throw URLError(.notConnectedToInternet)
}
do {
_ = try await sut.fetchUser(id: "1")
XCTFail("Expected URLError")
} catch let error as URLError {
XCTAssertEqual(error.code, .notConnectedToInternet)
} catch {
XCTFail("Unexpected error type: \(error)")
}
}
func testFetchUserSendsCorrectURL() async throws {
var capturedRequest: URLRequest?
MockURLProtocol.requestHandler = { request in
capturedRequest = request
let user = User(id: "42", name: "Bob", email: "bob@example.com")
let data = try JSONEncoder().encode(user)
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: nil
)!
return (response, data)
}
_ = try await sut.fetchUser(id: "42")
XCTAssertEqual(
capturedRequest?.url?.absoluteString,
"https://api.example.com/users/42"
)
}
}Testing Authentication Headers
func testAuthenticatedRequestIncludesBearerToken() async throws {
var capturedRequest: URLRequest?
let expectedToken = "test-jwt-token-abc123"
MockURLProtocol.requestHandler = { request in
capturedRequest = request
let data = try JSONEncoder().encode(User(id: "1", name: "Alice", email: "a@b.com"))
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (response, data)
}
let authClient = APIClient(
session: .mock,
baseURL: baseURL,
authToken: expectedToken
)
_ = try await authClient.fetchUser(id: "1")
XCTAssertEqual(
capturedRequest?.value(forHTTPHeaderField: "Authorization"),
"Bearer \(expectedToken)"
)
}Testing Retry Logic
class RetryAPIClient {
let session: URLSession
let maxRetries: Int
func fetchWithRetry(url: URL, maxRetries: Int = 3) async throws -> Data {
var lastError: Error?
for attempt in 0..<maxRetries {
do {
let (data, response) = try await session.data(from: url)
guard let http = response as? HTTPURLResponse,
http.statusCode == 200 else {
throw APIError.invalidResponse
}
return data
} catch {
lastError = error
if attempt < maxRetries - 1 {
try await Task.sleep(nanoseconds: UInt64(0.1 * 1e9))
}
}
}
throw lastError ?? APIError.unknown
}
}
// Test retry behavior
func testRetrySucceedsOnThirdAttempt() async throws {
var callCount = 0
MockURLProtocol.requestHandler = { request in
callCount += 1
if callCount < 3 {
throw URLError(.timedOut)
}
// Third attempt succeeds
let response = HTTPURLResponse(
url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil
)!
return (response, Data("{\"status\":\"ok\"}".utf8))
}
let client = RetryAPIClient(session: .mock, maxRetries: 3)
let data = try await client.fetchWithRetry(
url: URL(string: "https://api.example.com/health")!
)
XCTAssertEqual(callCount, 3, "Expected exactly 3 attempts")
XCTAssertFalse(data.isEmpty)
}
func testRetryExhaustedThrows() async {
MockURLProtocol.requestHandler = { _ in
throw URLError(.timedOut)
}
let client = RetryAPIClient(session: .mock, maxRetries: 3)
do {
_ = try await client.fetchWithRetry(
url: URL(string: "https://api.example.com/health")!
)
XCTFail("Expected error after retries exhausted")
} catch {
XCTAssertTrue(error is URLError)
}
}Testing Response Decoding Errors
func testMalformedJSONThrowsDecodingError() async {
MockURLProtocol.requestHandler = { request in
let malformedData = Data("{ invalid json }".utf8)
let response = HTTPURLResponse(
url: request.url!,
statusCode: 200,
httpVersion: nil,
headerFields: ["Content-Type": "application/json"]
)!
return (response, malformedData)
}
do {
_ = try await sut.fetchUser(id: "1")
XCTFail("Expected DecodingError")
} catch is DecodingError {
// Expected
} catch {
XCTFail("Expected DecodingError, got: \(error)")
}
}Simulating Network Delay
class DelayedMockURLProtocol: URLProtocol {
static var delay: TimeInterval = 0
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
guard let handler = DelayedMockURLProtocol.requestHandler else {
client?.urlProtocol(self, didFailWithError: URLError(.badServerResponse))
return
}
let delay = DelayedMockURLProtocol.delay
DispatchQueue.global().asyncAfter(deadline: .now() + delay) { [weak self] in
guard let self else { return }
do {
let (response, data) = try handler(self.request)
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocol(self, didLoad: data)
self.client?.urlProtocolDidFinishLoading(self)
} catch {
self.client?.urlProtocol(self, didFailWithError: error)
}
}
}
override func stopLoading() {}
}
func testRequestTimeoutWithSlowServer() async {
DelayedMockURLProtocol.delay = 10 // 10s delay
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [DelayedMockURLProtocol.self]
config.timeoutIntervalForRequest = 1 // 1s timeout
let slowSession = URLSession(configuration: config)
let client = APIClient(session: slowSession, baseURL: baseURL)
do {
_ = try await client.fetchUser(id: "1")
XCTFail("Expected timeout error")
} catch let error as URLError {
XCTAssertEqual(error.code, .timedOut)
}
}Testing Pagination
func testFetchAllPagesAggregatesResults() async throws {
var pageCallCount = 0
MockURLProtocol.requestHandler = { request in
pageCallCount += 1
let page = Int(URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?
.queryItems?.first(where: { $0.name == "page" })?.value ?? "1") ?? 1
struct PaginatedResponse: Encodable {
let items: [User]
let nextPage: Int?
}
let response: PaginatedResponse
if page == 1 {
response = PaginatedResponse(
items: [User(id: "1", name: "Alice", email: "a@b.com")],
nextPage: 2
)
} else if page == 2 {
response = PaginatedResponse(
items: [User(id: "2", name: "Bob", email: "b@b.com")],
nextPage: nil // Last page
)
} else {
XCTFail("Unexpected page request: \(page)")
throw URLError(.unknown)
}
let data = try JSONEncoder().encode(response)
let httpResponse = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (httpResponse, data)
}
let allUsers = try await sut.fetchAllUsers()
XCTAssertEqual(allUsers.count, 2)
XCTAssertEqual(pageCallCount, 2)
XCTAssertEqual(allUsers[0].name, "Alice")
XCTAssertEqual(allUsers[1].name, "Bob")
}Conclusion
URLProtocol is the right tool for iOS network testing: it intercepts at the URLSession level without requiring protocol wrappers around URLSession itself. You get deterministic responses, error injection, delay simulation, and request inspection—all without touching real network infrastructure. Combined with async/await tests, this makes network layer tests fast, readable, and reliable.