Skip to content

Instantly share code, notes, and snippets.

@Raiden18
Last active July 21, 2022 19:10
Show Gist options
  • Save Raiden18/154e0cd49edd3b64ce9d77760860f7e1 to your computer and use it in GitHub Desktop.
Save Raiden18/154e0cd49edd3b64ce9d77760860f7e1 to your computer and use it in GitHub Desktop.
SomeViewModelTest for states
class SomeViewModelTest {
private lateinit var someViewModel: SomeViewModel
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 {
coEvery { someInteractor.loadSomething() } coAnswers {
delay(1_000)
dataToLoad
}
val dispatechers = TestDispatchersProvider(testScheduler)
someViewModel = SomeViewModel(someInteractor, dispatechers)
runCurrent()
assertTrue(someViewModel.getLoaderState().value)
assertFalse(someViewModel.getErrorState().value)
assertEquals(ContentState.Hidden, someViewModel.getContentState().value)
}
@Test
fun `Should show content if data is loaded`() = runTest {
coEvery { someInteractor.loadSomething() } returns dataToLoad
val dispatechers = TestDispatchersProvider(testScheduler)
someViewModel = SomeViewModel(someInteractor, dispatechers)
runCurrent()
assertEquals(ContentState.Shown(dataToLoad), someViewModel.getContentState().value)
assertFalse(someViewModel.getLoaderState().value)
assertFalse(someViewModel.getErrorState().value)
}
@Test
fun `Should show error state if error appeared`() = runTest {
coEvery { someInteractor.loadSomething() } coAnswers { throw Throwable() }
val dispatechers = TestDispatchersProvider(testScheduler)
someViewModel = SomeViewModel(someInteractor, dispatechers)
runCurrent()
assertTrue(someViewModel.getErrorState().value)
assertFalse(someViewModel.getLoaderState().value)
assertEquals(ContentState.Hidden, someViewModel.getContentState().value)
}
@Test
fun `Should show content state if user clicks on retry button after loading data with error`() = runTest {
coEvery { someInteractor.loadSomething() } coAnswers { throw Throwable() }
val dispatechers = TestDispatchersProvider(testScheduler)
someViewModel = SomeViewModel(someInteractor, dispatechers)
runCurrent()
coEvery { someInteractor.loadSomething() } returns dataToLoad
someViewModel.onRetryButtonClicked()
assertEquals(ContentState.Shown(dataToLoad), someViewModel.getContentState().value)
assertFalse(someViewModel.getErrorState().value)
assertFalse(someViewModel.getLoaderState().value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment