Skip to content

Instantly share code, notes, and snippets.

@catalinghita8
Created June 3, 2022 17:48
Show Gist options
  • Save catalinghita8/0d4e310aeedf3604121b041e6f110d71 to your computer and use it in GitHub Desktop.
Save catalinghita8/0d4e310aeedf3604121b041e6f110d71 to your computer and use it in GitHub Desktop.
@ExperimentalCoroutinesApi
class RestaurantsViewModelTest {
private val dispatcher = StandardTestDispatcher()
private val scope = TestScope(dispatcher)
@Test
fun stateWithError_isProduced() = scope.runTest {
val testVM = getViewModel(shouldThrowException = true)
advanceUntilIdle()
val currentState = testVM.state.value
assert(
currentState == RestaurantsScreenState(
restaurants = emptyList(),
isLoading = false,
error = "error_message"
)
)
}
private fun getViewModel(shouldThrowException: Boolean = false): RestaurantsViewModel {
val restaurantsRepository =
RestaurantsRepository(FakeApiService(shouldThrowException), FakeRoomDao(), dispatcher)
val getSortedRestaurantsUseCase =
GetSortedRestaurantsUseCase(restaurantsRepository)
val getInitialRestaurantsUseCase =
GetInitialRestaurantsUseCase(
restaurantsRepository,
getSortedRestaurantsUseCase
)
val toggleRestaurantUseCase = ToggleRestaurantUseCase(
restaurantsRepository,
getSortedRestaurantsUseCase
)
return RestaurantsViewModel(
getInitialRestaurantsUseCase,
toggleRestaurantUseCase,
dispatcher
)
}
}
class FakeApiService(private val shouldThrowException: Boolean) : RestaurantsApiService {
override suspend fun getRestaurants(): List<RemoteRestaurant> {
delay(1000)
if (shouldThrowException)
throw Exception("error_message")
return DummyContent.getRemoteRestaurants()
}
override suspend fun getRestaurant(id: Int)
: Map<String, RemoteRestaurant> {
TODO("Not yet implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment