ApiViewModel extends ViewModel { @VisibleForTesting public LiveData<Resource<Example>> getData() { data =apiRepository.getData(); return data; } @Inject  ApiViewModel(ApiRepository apiRepository); @VisibleForTesting LiveData<Resource<Example>> getData();  }
@Test public void testNull() { MutableLiveData<Resource<Example>> resourceMutableLiveData = new MutableLiveData<>(); when(apiViewModel.getData()).thenReturn(resourceMutableLiveData); assertThat(apiViewModel.getData(),notNullValue() ); verify(repository).getData(); }
@Test public void loadData() { apiViewModel.getData(); when(repository.getData()).thenReturn(mock(LiveData.class)); verify(repository).getData(); }
@Test public void sendResultToUI() { MutableLiveData<Resource<Example>> resourceMutableLiveData = new MutableLiveData<>(); when(repository.getData()).thenReturn(resourceMutableLiveData); Observer<Resource<Example>> observer = mock(Observer.class); apiViewModel.getData().observeForever(observer); Example example = TestUtil.createSampleExample("Raghunandan", "30"); Resource<Example> exampleResource = Resource.success(example); resourceMutableLiveData.setValue(exampleResource); verify(observer).onChanged(exampleResource); reset(observer); Example exampleExample = TestUtil.createSampleExample("Raghunandan Kavi", "30"); Resource<Example> exampleResourceExample = Resource.success(exampleExample); resourceMutableLiveData.setValue(exampleResourceExample); verify(observer).onChanged(exampleResourceExample); }