Last active
September 30, 2021 04:00
-
-
Save 5AbhishekSaxena/7fd3c26eb760149a0a8179cf79f12d49 to your computer and use it in GitHub Desktop.
Test Robot with Execute around example
This file contains 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 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() | |
} | |
} | |
} |
This file contains 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
@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