If you’re using MVVM architecture in your iOS project you probably have a ViewModel that gets data from the network. So how can we write tests for that kind of ViewModel?
You should be able to test your App functionality without depending on data from dependencies, Right?
In this article, I will show you how you can achieve this.
Before we can write tests for the ViewModel we must make sure that the ViewModel is testable.
To make our code testable we should consider two concepts:
Dependency Inversion is one the principle of SOLID Design Principles that says :
High-level modules should not depend on low-level modules; both should depend on abstractions.
Abstractions should not depend on details. Details should depend upon abstractions.
In software engineering, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object.
Enough with the theory, let’s get our hands dirty by Coding.
Below image demonstrates what we are going to create.
Abstract Network Layer
This piece of code is an Abstract layer that contains every method we need to implement in the target classes.
#ios #swift #viewmodel #unit-testing #mvvm #testing