The Test Subject

In this tutorial we will be testing “Video Games” application. It’s a simple app that loads and display a list of Games on home screen. Our app flow is as follows: I have compiled a starter project so that you can practice as we proceed. Download the project from here and open the project in Starter folder to get started.

Games List View Model

Before we start writing test cases of our GamesListViewModel, lets take a look at its behaviour. You can find GamesListViewModel in the root of starter porject. In GameListViewModel we are exposing all the state information, state change notifications (GameListViewModelDelegate) and actions that UI can initiate. GameListViewModel has one dependency that is DataService which allows us to load Game list.

Prepare Test Enviornment

One of the Unit Testing principle is to isolate the test subject and simulate its dependencies in order to test all the possible cases. Our test subject GameListViewModel has one dependency i.e. DataService. In order to isolate and simulate enviornment of GameListViewModel, we have to mock DataService behaviours. Following is the mock servicer we will be using: The GameListViewModel notifies events through GameListViewModelDelegate and to monitor these events we will use the following:

Lets Start Testing

In our first test case we will test the behaviour of GamesListViewModel if data is loaded successfully with none empty list. To do that we tell MockDataService to send games list with one item and will check the GamesListViewModel response using MonitorGamesListViewModelDelegate. In this test case we are performing five steps: Now we will test what if loading data request fails with an error. According to our requirement showError should be true and errorMessage should say “Unable to load games. Please try again !” Now our final case, data loaded successfully but game list is empty. Desired result in this case is, showError should be true and errorMessage should say “No games available at the moment.”


We have seen how MVVM makes it easy to simulate the user behaviour without dealing with the View. We have written three test cases to see how we can test different states of the View. You can download the final project from here. Also if you have any question or suggestion drop a comment below.

Unit Testing With MVVM in iOS - 43