Skip to content

Instantly share code, notes, and snippets.

@Raiden18
Last active July 21, 2022 19:21
Show Gist options
  • Save Raiden18/e7244cd11ff3f24ad1f3d1b9af572e42 to your computer and use it in GitHub Desktop.
Save Raiden18/e7244cd11ff3f24ad1f3d1b9af572e42 to your computer and use it in GitHub Desktop.
class SomeViewModelTest {
private val someInteractor: SomeInteractor = mockk(relaxed = true)
private val dataToLoad: String = "Data to load"
@Before
fun setUp() {
clearAllMocks()
}
@Test
fun `Loader state should be shown while data is being loaded`() = runTest {
// Replaced with the builder
val viewModel = ViewModelBuilder()
.withLoadingData()
.build(testScheduler)
assertThat(viewModel)
.loaderIsShown()
.errorIsHidden()
.contentIsHidden()
}
@Test
fun `Should show content if data is loaded`() = runTest {
// Replaced with the builder
val viewModel = ViewModelBuilder()
.withLoadedData(dataToLoad)
.build(testScheduler)
assertThat(viewModel)
.contentIsShow(dataToLoad)
.errorIsHidden()
.loaderIsHidden()
}
@Test
fun `Should show error state if error appeared`() = runTest {
val throwable = Throwable()
// Replaced with the builder
val viewModel = ViewModelBuilder()
.withDataLoadedWithError(throwable)
.build(testScheduler)
assertThat(viewModel)
.errorIsShown()
.contentIsHidden()
.loaderIsHidden()
}
@Test
fun `Should show content state if user clicks on retry button after loading data with error`() = runTest {
// Replaced with the builder
val viewModel = ViewModelBuilder()
.withDataLoadedWithError(throwable)
.build(testScheduler)
coEvery { someInteractor.loadSomething() } returns dataToLoad
someViewModel.onRetryButtonClicked()
assertThat(viewModel)
.contentIsShow(dataToLoad)
.errorIsHidden()
.loaderIsHidden()
}
private inner class ViewModelBuilder {
fun withLoadingData(): ViewModelBuilder {
coEvery { someInteractor.loadSomething() } coAnswers {
delay(1_000)
"result is not important"
}
return this
}
fun withDataLoadedWithError(throwable: Throwable): ViewModelBuilder {
coEvery { someInteractor.loadSomething() } coAnswers { throw throwable }
return this
}
fun withLoadedData(dataToLoad: String): ViewModelBuilder {
coEvery { someInteractor.loadSomething() } returns dataToLoad
return this
}
fun build(testScheduler: TestCoroutineScheduler): SomeViewModel {
val dispatechers = TestDispatchersProvider(testScheduler)
val viewModel = SomeViewModel(someInteractor, dispatechers)
return viewModel
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment