Testing the ViewModels in Open Event Organizer App
In Open Event Organizer Android App we follow Test Driven Development Approach which means the features added in the app are tested thoroughly by unit tests. More tests would ensure better code coverage and fewer bugs. This blog explains how to write tests for Viewmodel class in MVVM architecture.
Specifications
We will use JUnit4 to write unit tests and Mockito for creating mocks. The OrdersViewModel class returns the list of Order objects to the Fragment class. The objects are requested from OrderRepository class which fetches them from Network and Database. We will create a mock of OrderRepository class since it is out of context and contain logic that doesn’t depend on Orders Respository. Below is the getOrders method that we will test.
public LiveData<List<Order>> getOrders(long id, boolean reload) { if (ordersLiveData.getValue() != null && !reload) return ordersLiveData; compositeDisposable.add(orderRepository.getOrders(id, reload) return ordersLiveData; |
We will be using InstantTaskExecutorRule() which is a JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously. We will use setUp() method to load the RxJavaPlugins, RxAndroid plugins and reset them in tearDown method which will ensure each test runs independently from the other and avoid memory leaks. After doing this initialization and basic setup for tests we can begin code the method shouldLoadOrdersSuccessfuly() to test the getOrders method present in ViewModel class. Let’s see the step by step approach.
- Use Mockito.when to return Observables one by one from ORDERS_LIST whenever the method getOrders of the mock orderRepository is called.
- We will use Mockito.InOrder and pass orders, orderRepository and progress to check if they are called in a particular order.
- We will use .observeForever method to observe on LiveData objects and add a ArrayList on change.
- Finally, we will test and verify if the methods are called in order.
@Test public void shouldLoadOrdersSuccessfully() { when(orderRepository.getOrders(EVENT_ID, false)) .thenReturn(Observable.fromIterable(ORDERS_LIST)); InOrder inOrder = Mockito.inOrder(orders, orderRepository, progress); ordersViewModel.getProgress().observeForever(progress); orders.onChanged(new ArrayList<>()); ordersViewModel.getOrders(EVENT_ID, false); inOrder.verify(orders).onChanged(new ArrayList<>()); |
Similar approach can be followed for writing tests to check other behaviour of the ViewModel.
References
- Official Documentation for testing. https://developer.android.com/reference/android/arch/core/executor/testing/InstantTaskExecutorRule
- Official Documentation for JUnit. https://junit.org/junit4/
- Official documentation for Mockito. http://site.mockito.org/
- Open Event Organizer App codebase. https://github.com/fossasia/open-event-orga-app
You must be logged in to post a comment.