Reputation: 1017
I was testing my presenter class and all test work. But when I tried to run my test class, all coroutines test fail.
I'm trying reset my dispatch and clean my scope.
private val dispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(dispatcher)
@Before
fun setUp() {
Dispatchers.setMain(dispatcher)
products = ProductsMotherObject.createEmptyModel()
getProductsUseCase = GetProductsUseCase(productsRepository)
updateProductsUseCase = UpdateProductsUseCase(productsRepository)
presenter = HomePresenter(view, getProductsUseCase, updateProductsUseCase, products)
}
@After
fun after() {
Dispatchers.resetMain()
testScope.cleanupTestCoroutines()
}
and this is an example of my tests
@Test
fun `should configure recyclerview if response is success`() = testScope.runBlockingTest {
//Given
`when`(productsRepository.getProductsFromApi()).thenReturn(mutableMapOf())
//when
presenter.fetchProducts()
//then
verify(view).hideLoading()
verify(view).setUpRecyclerView(products.values.toMutableList())
}
I have only single errors from my tests, but each test works when run single
Upvotes: 1
Views: 757
Reputation: 1017
Solved. I found this incredible post.
What have I done:
I implemented my dispacher without constructor.
private val testDispatcher = TestCoroutineDispatcher()
You have to set on @Before function
@Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
}
And reset after test.
@After
fun after() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
Finally each test that implements coroutines must launch on MainScope.
@Test
fun `should configure recyclerview if response is success`() = testDispatcher.runBlockingTest {
MainScope().launch {
//Given
`when`(productsRepository.getProductsFromApi()).thenReturn(mutableMapOf())
//when
presenter.fetchProducts()
//then
verify(view).hideLoading()
verify(view).setUpRecyclerView(products.values.toMutableList())
}
}
Upvotes: 1