Member-only story
Dependency Injection in SwiftUI: Flexible and Testable Code
Part 84 of 100 in the SwiftUI Zero to Expert Series
“Can you add a unit test for this?” My tech lead’s PR comment seemed simple enough.
I looked at the ViewModel.
It created its own URLSession, built its own URLs, parsed its own JSON.
Testing it meant hitting a real server.
There was no way to inject a mock.
I could have faked it — spin up a local server, point the tests at it, hope the network was reliable.
Instead, I spent two hours refactoring.
I extracted the network calls behind a protocol, passed the implementation through the initializer, and suddenly I could inject a mock that returned whatever data I wanted.
↓↓↓ I’ve also made an Android game feel free to play it if you’re bored ↓↓↓
https://play.google.com/store/apps/details?id=com.jeripurnama.infixox
↑↑↑ — ↑↑↑ — ↑↑↑
The test took five minutes to write after that.
That refactoring session taught me something I keep learning in different ways: the pain of testing is almost always a design problem.
