Skip to content

Instantly share code, notes, and snippets.

@5AbhishekSaxena
Last active September 30, 2021 04:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5AbhishekSaxena/7fd3c26eb760149a0a8179cf79f12d49 to your computer and use it in GitHub Desktop.
Save 5AbhishekSaxena/7fd3c26eb760149a0a8179cf79f12d49 to your computer and use it in GitHub Desktop.
Test Robot with Execute around example
class ArticleListViewModelRobot private constructor() {
private lateinit var viewModel: ArticleListViewModel
private val fakeRepository = FakeArticleRepository()
private fun setup() {
buildViewModel()
}
fun buildViewModel() = apply {
viewModel = ArticleListViewModel(
articleRepository = fakeRepository
)
}
// actions
suspend fun emitArticles(articles: List<Article>) = apply {
fakeRepository.emitArticles(articles)
}
// all assert functions
fun assertArticleWasPersisted(article: Article) = apply {
// assert
}
private fun cleanUp() = apply {
fakeRepository.closeChannel()
}
companion object {
fun test(action: suspend (ArticleListViewModelRobot) -> Unit) {
val testRobot = ArticleListViewModelRobot()
testRobot.setup()
runBlockingTest {
action(testRobot)
}
testRobot.cleanUp()
}
}
}
@ExperimentalCoroutinesApi
class ArticleListViewModelTest {
@Test
fun successfulRequest() = runBlockingTest {
val testArticles = listOf(
Article(
htmlTitle = HtmlString("Test String"),
author = "",
url = ""
)
)
// notice the user of TestRobot doesn't have to worry about setups and cleanups/teardowns
ArticleListViewModelRobot.test {
it.assertViewState(
expectedViewState = ArticleListViewState.Loading
)
.emitArticles(testArticles)
.assertViewState(
expectedViewState = ArticleListViewState.Success(testArticles)
)
.assertNumberOfCallsToFetchArticles(1)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment