Last active
October 21, 2021 21:54
-
-
Save oliverspryn/be2108baedfb2efd5833b4e2d348d713 to your computer and use it in GitHub Desktop.
A correct example of how to unit test the PhotosController
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
| class PhotosControllerTest : Spek({ | |
| describe("The PhotosController") { | |
| var mockPhotosApiService: PhotosApiService? = null | |
| var mockSchedulerForwarder: SchedulerForwarder? = null | |
| var uut: PhotosController? = null | |
| beforeEachTest { | |
| // uut and supporting classes setup and mocked here | |
| } | |
| describe("when getPhotos") { | |
| var ioTestScheduler: TestScheduler? = null | |
| var mainThreadTestScheduler: TestScheduler? = null | |
| beforeEachTest { | |
| // Mock the threads for the call here | |
| } | |
| describe("and the call succeeds") { | |
| beforeEachTest { | |
| val photo1 = PhotosModel( | |
| id = 42, | |
| thumbnailUrl = "https://ddg.co/", | |
| title = "DuckDuckGo", | |
| url = "https://duckduckgo.com/" | |
| ) | |
| val photo2 = PhotosModel( | |
| id = 42, | |
| thumbnailUrl = "https://ddg.co/", | |
| title = "DuckDuckGo", | |
| url = "https://duckduckgo.com/" | |
| ) | |
| val data = listOf(photo1, photo2) | |
| whenever(mockPhotosApiService?.getPhotos()).thenReturn(Single.just(data)) | |
| uut?.photosAdapter = mock() | |
| uut?.getPhotos() | |
| ioTestScheduler?.triggerActions() | |
| mainThreadTestScheduler?.triggerActions() | |
| } | |
| it("updates the photos adapter the with fetched data") { | |
| verify(uut?.photosAdapter)?.updatePhotos(data!!) | |
| } | |
| it("adds a disposable to the composite disposable") { | |
| verify(mockCompositeDisposable)?.add(any()) | |
| } | |
| } | |
| describe("and the call fails") { | |
| // Test failure condition here | |
| } | |
| } | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment