MVVM-C Architecture with Dependency Injection + Testing
A complete example
--
I’ve been using MVVM-C for quite some time. I’m sure you (probably, I don’t know you) agree that by abstracting the navigation away from the main MVVM architecture code gives you the opportunity for testing. Great!
What if you have multiple dependencies? How are these going to be injected into your…wait.. where…what?
Making this clear is the goal of this article.
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.4.1, and Swift 5.2.2
Prerequisites:
- You will be expected to be aware how to make a Single View Application in Swift.
- Some experience of architecture patterns are required, whether MVC or MVVM.
- The principles of Dependency Injection are explained in this article, but some in-depth explanation always helps!
- You’ll need to be comfortable with protocols
Terminology:
Factory Pattern: A design pattern where an object is created without exposing the creation logic to the client. The factory pattern lets a class defer instantiation to subclasses.
The Problem
MVVM-C helps with separation of concerns, and allows testing and implementation to be…much better than MVC. Now, nothing is perfect, but it is perfectly possible to have a variety of dependencies which can lead to large and unwieldy initializers.
One possible solution to this is use of the Factory Pattern, and the use of Dependency Injection to test the relevant classes. This particular article is written with the views programmatically defined, avoiding Storyboards in the entire project, and neatly overriding loadview().
With that understood, let’s get to it!
The Example
The idea of this article is to have a basic skeleton for the MVVM-C architecture. There are few around, particularly coded in Swift and even fewer making an attempt at testing.