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:

1 . Dependency Inversion

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.

2 . Dependency Injection

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.

Image for post

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

Testable ViewModel Using Mock
1.95 GEEK