Dependency Injection in MVVM

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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
Download course materials from Github
Previous: Introduction Next: Demo