Swift: Dependency Injection with a Custom Initializer

As my first project of the year, I’m working on the Swift version of @catehstn’s iOS Unit Testing Workshop – you can sign up here if you’re interested.

As I was working through my code and writing tests, I ran into the following problem…

Let’s say I’m building a simple counter in Swift:

This is super simple, and I can easily write a test for increment:

This is great, but what about about this case!

Since the Counter is initiated with the count of 0, our multiplication test is not as effective:

To be an effective test, we need to test our scaleBy function when the count is not 0 – we need to have control over the initial counter value. This is where we can use default values to inject the init function with the correct starter value (vs making count not private anymore):

Now the test looks like this!

That’s it! By adding an init function that injects the initial value we want, we keep the integrity of our Counter as it was intended while writing effective tests for it!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.