Dependency injection is fundamental to efficient unit testing. A view model contains the presentation logic underlying one or more views, so you can write unit tests for the view model’s code instead of testing the logic through UI tests. If you also separate out services like networking, you can write mock services and inject them into your view models to create unit tests that don’t require network access.
Another use of dependency injection is to improve the performance or convenience of SwiftUI previews. A view’s preview doesn’t have to use the same properties as the view — instead, you can pass it “mock” versions of properties. It’s especially useful to pass it a mock version of its view model.
If your app gets data by sending requests to a server, there’s usually a service module to handle these tasks. Often, it’s the view models that instantiate this service and pass user input to its methods. This means you’re sending requests to the server every time the preview refreshes. When you’re editing the appearance of a view that accesses the view model, every character you type refreshes the preview.
Some APIs have a daily quota, and you need to save that for when you want to test the full app. It would be more convenient if the preview used “canned” data, and it’s quite easy to do this with MVVM. You create a “mock” version that supplies static values for published properties. This might require you to write mock versions of methods that generate these values.
Work through the following demo in the next section to try this out.
See forum comments
This content was released on Feb 28 2025. The official support period is 6-months
from this date.
Learn why Dependency Injection is useful for writing unit tests and improving the performance or convenience of SwiftUI previews.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.