gpt4 book ai didi

android - 如何基于 Observable 返回值对 Presenter 方法进行单元测试?

转载 作者:行者123 更新时间:2023-11-29 19:05:41 24 4
gpt4 key购买 nike

具有以下功能的实际实现,其中mTallesPreferences.isUserAuthenticated()返回 Observable<Boolean>类型值:

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

如果mView?.showAccessScreen(),我该如何进行单元测试?当订阅者获得 isAuthenticated = false 时被调用?

我试过下面的方法,可惜NullPointerException出现在现场。

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()
}

}

最佳答案

您的函数顺序错误。当您调用 showInitialScreen() 时,mTallesPreferences.isUserAuthenticated() 不会模拟返回您想要的值。重新排序您的测试方法,例如:

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

关于android - 如何基于 Observable 返回值对 Presenter 方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47348784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com