Search code examples
androidunit-testingkotlinmvpreactivex

How to unit test presenter method based on an Observable returned value?


Having the following real implementation of a function, where mTallesPreferences.isUserAuthenticated() returns an Observable<Boolean> type value:

override fun showInitialScreen() {
    mTallesPreferences.isUserAuthenticated()
            .subscribe { isAuthenticated ->
                if (isAuthenticated) mView?.showMainScreen()
                else mView?.showAccessScreen()
                mView?.closeCurrentScreen()
            }
 }

How can I unit test if mView?.showAccessScreen() is called when subscriber gets isAuthenticated = false?

I have tried the following approach, but unfortunately NullPointerException appears on the scene.

class LaunchPresenterTest {

    @Mock
    lateinit var mView: LaunchContract.View

    @Mock
    lateinit var mTallesPreferences: TallesPreferencesApi

    private lateinit var mPresenter: LaunchPresenter

    @Before
    fun setupLaunchPresenter() {
        MockitoAnnotations.initMocks(this)
        mPresenter = LaunchPresenter(mTallesPreferences)
    }

    @Test
    fun testShowInitialScreenNotAuthenticated() {
        mPresenter.showInitialScreen()
        Mockito.`when`(mTallesPreferences.isUserAuthenticated()).thenReturn(Observable.just(false))
        Mockito.verify(mView).showAccessScreen()
    }

}

Solution

  • Your functions are in the wrong order. When you call showInitialScreen() the mTallesPreferences.isUserAuthenticated() is not mocked to return the value you want. Re-order your test method like:

    @Test
    fun testShowInitialScreenNotAuthenticated() {
        Mockito.`when`(mTallesPreferences.isUserAuthenticated()).thenReturn(Observable.just(false))
        mPresenter.showInitialScreen()
        Mockito.verify(mView).showAccessScreen()
    }