Created
June 15, 2020 20:17
-
-
Save cdmunoz/4e20d06a8f3beb1165feff29f34bf0d5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @ExperimentalCoroutinesApi | |
| @RunWith(MockitoJUnitRunner::class) | |
| class PhotosViewModelTest { | |
| @get:Rule | |
| val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule() | |
| @get:Rule | |
| val testCoroutineRule = TestCoroutineRule() | |
| private lateinit var viewModel: PhotosViewModel | |
| @Mock | |
| private lateinit var photosRepository: PhotosRepository | |
| @Mock | |
| private lateinit var photosResponseObserver: Observer<Result<ArrayList<Photo>>> | |
| @Before | |
| fun setUp() { | |
| viewModel = PhotosViewModel(photosRepository) | |
| } | |
| @Test | |
| fun `when fetching results ok then return a list successfully`() { | |
| val emptyList = arrayListOf<Photo>() | |
| testCoroutineRule.runBlockingTest { | |
| viewModel.getPhotos().observeForever(photosResponseObserver) | |
| whenever(photosRepository.getPhotosFromApi(anyInt(), anyInt())).thenAnswer { | |
| Result.Success(emptyList) | |
| } | |
| viewModel.loadData() | |
| assertNotNull(viewModel.getPhotos().value) | |
| assertEquals(Result.Success(emptyList), viewModel.getPhotos().value) | |
| } | |
| } | |
| @Test | |
| fun `when calling for results then return loading`() { | |
| testCoroutineRule.runBlockingTest { | |
| viewModel.getPhotos().observeForever(photosResponseObserver) | |
| viewModel.loadData() | |
| verify(photosResponseObserver).onChanged(Result.InProgress) | |
| } | |
| } | |
| @Test | |
| fun `when fetching results fails then return an error`() { | |
| val exception = mock(HttpException::class.java) | |
| testCoroutineRule.runBlockingTest { | |
| viewModel.getPhotos().observeForever(photosResponseObserver) | |
| whenever(photosRepository.getPhotosFromApi(anyInt(), anyInt())).thenAnswer { | |
| Result.Error(exception) | |
| } | |
| viewModel.loadData() | |
| assertNotNull(viewModel.getPhotos().value) | |
| assertEquals(Result.Error(exception), viewModel.getPhotos().value) | |
| } | |
| } | |
| @After | |
| fun tearDown() { | |
| viewModel.getPhotos().removeObserver(photosResponseObserver) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment