How to test ViewModel in Android?

Testing ViewModel in Android is essential for ensuring that your application's UI logic works as intended. Below is a simple guide on how to effectively test a ViewModel using JUnit and Mockito.

import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.verify; public class MyViewModel extends ViewModel { private MutableLiveData data = new MutableLiveData<>(); public MutableLiveData getData() { return data; } public void updateData(String value) { data.setValue(value); } } public class MyViewModelTest { @Mock private MyViewModel viewModel; @Before public void setUp() { MockitoAnnotations.initMocks(this); viewModel = new MyViewModel(); } @Test public void testUpdateData() { String testValue = "Hello World"; viewModel.updateData(testValue); verify(viewModel.getData()).setValue(testValue); } }

Android ViewModel testing JUnit Mockito LiveData unit testing UI logic