I am new to testing and I am writing a test for my ViewModel. I have a couple of questions about it.
- In my Test method, unless I add a delay(10), the test fails saying:
Wanted but not invoked: breweryRepository.getBeerStyles(); -> at com.helenc.test.repositories.BreweryRepository.getBeerStyles(BreweryRepository.kt:12) Actually, there were zero interactions with this mock.
Why do I need a delay? Is there a better way to do it?
- I added the test in the test folder (not in androidTest). Is this correct? I am not sure since I am using some androidx dependencies, like androidx.lifecycle.Observer or androidx.arch.core.executor.testing.InstantTaskExecutorRule.
This is my ViewModel test file:
@RunWith(JUnit4::class)
class BeerStylesViewModelTest {
private lateinit var viewModel: BeerStylesViewModel
private lateinit var repository: BreweryRepository
private lateinit var beerStylesObserver: Observer<Resource<List<StylesData>>>
private val successResource = Resource.success(mockedBeerStylesList)
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
@ObsoleteCoroutinesApi
private val mainThreadSurrogate = newSingleThreadContext("UI thread")
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
@Before
fun setUp() {
Dispatchers.setMain(mainThreadSurrogate)
repository = mock()
runBlocking {
whenever(repository.getBeerStyles()).thenReturn(successResource)
}
viewModel = BeerStylesViewModel(repository)
beerStylesObserver = mock()
}
@Test
fun `when load beerStyles success`() = runBlocking {
viewModel.beerStyles.observeForever(beerStylesObserver)
delay(10)
verify(repository).getBeerStyles()
verify(beerStylesObserver).onChanged(Resource.loading(null))
verify(beerStylesObserver).onChanged(successResource)
}
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
@After
fun tearDown() {
Dispatchers.resetMain()
mainThreadSurrogate.close()
}
}
Aucun commentaire:
Enregistrer un commentaire