Using Swift Package Manager to Structure Test-Only Code in Swift

A Working Example? Yes!

Steven Curtis
6 min readOct 22, 2024
Photo by Samia Liamani on Unsplash

This article is about my NetworkClient, and how I’ve managed to add mock objects into my network client and (with thought) put them in the proper place so each of my projects can use it (which is nice).

The Importance of Testing Code

I think unit testing code is really important, and helps us to confirm that our code fits a given specification.

I’ve a network client and I’ve (gasp) been repeating the same mock code in each and every project.

Let me show you what that means.

My technique

Using Mocks in tests
Each time I want to test a service I need to implement the following Mocks, and this is the same for each and every project I create.

import NetworkClient

final class MockNetworkClient: NetworkClient {
var fetchResult: (any MockResult)?
private(set) var fetchResultCalled = false

func fetch<T>(
api: URLGenerator,
request: T
) async throws -> T.ResponseDataType? where T: APIRequest {
fetchResultCalled = true
return try fetchResult?.getResult() as? T.ResponseDataType
}
}

protocol MockResult {…

--

--

No responses yet