I'm writing unit tests for Presenters of an MVP project. My presenter implement like this:
class SplashPresenter {
override fun onAttach() {
if (dataManager.getAppLaunchFirstTime()) {
onAppOpenFirstTime()
} else {
// Other logic...
}
}
@VisibleForTesting
fun onAppOpenFirstTime() {
dataManager.setAppLaunchFirstTime(false)
splashView.openLoginScreen()
// May be I will add more functionalities in the future...
}
}
Here we have 2 approaches to write unit test.
First approach:
Verify directly what will happen: openLoginScreen() & setAppLaunchFirstTime(false). Don't care how they will be called.
@Test
fun onAttachTest_appLaunchFirstTime() {
Mockito.`when`(dataManager.getAppLaunchFirstTime()).thenReturn(true)
splashPresenter.onAttach()
verify(dataManager).setAppLaunchFirstTime(false)
verify(splashView).openLoginScreen()
}
Second approach
We use spy() to verify private internal method onAppOpenFirstTime() will be called. Then write another separate test for onAppOpenFirstTime().
@Test
fun onAttachTest_appLaunchFirstTime() {
`when`(dataManager.getAppLaunchFirstTime()).thenReturn(true)
val spyPresenter = Mockito.spy(splashPresenter)
spyPresenter.onAttach()
verify(spyPresenter).onAppOpenFirstTime()
}
@Test
fun onAppOpenFirstTimeTest() {
splashPresenter.onAppOpenFirstTime()
verify(dataManager).setAppLaunchFirstTime(false)
verify(splashView).openLoginScreen()
}
So which approach is better? Which approach will make the project more testable when extending feature in the future?
Do we need to write unit test for private internal method?
Aucun commentaire:
Enregistrer un commentaire