gpt4 book ai didi

android - MockitoJUnit 测试在 Android Studio 中运行但在命令行上运行时失败

转载 作者:行者123 更新时间:2023-12-02 12:59:02 25 4
gpt4 key购买 nike

我正在尝试使用 MockitoJUnitRunner 运行单元测试;它们在 Android Studio 下运行良好,但在命令行中运行时,一些(不是全部)测试会失败 - 这很重要,我需要能够从我的持续集成平台运行它们,而不仅仅是从 IDE 运行。这是正在测试的实际方法之一:

internal fun requestSecurityQuestion() {
if (isViewAttached) mvpView.showLoadingDialog()

api.getSecurityQuestionToday(mDataManager.token,
ACTION_ASK_SECURITY_QUESTION_ON_LOGIN, 0)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : CallbackWrapper<SettingsResponse>(mDataManager) {
override fun onSuccess(response: SettingsResponse) {
mDataManager.securityQuestion = response.question
mDataManager.processId = response.processId

if (isViewAttached) {
mvpView.dismissLoadingDialog()
mvpView.showVsecVerificationDialog(0, response.question!!)
}
}

override fun onFailed(errorId: Int, jsonResponse: String?) {
if (isViewAttached) mvpView.dismissLoadingDialog()
}
})
}

这是失败的测试之一:
@RunWith(MockitoJUnitRunner::class)
class HomePresenterTest {

@Mock
private var mView: HomeView? = null
@Mock
private var mDataManager: DataManager? = null
@Mock
private var mApi: Api? = null

lateinit var mPresenter: HomePresenter

@Before
fun setUp() {
mPresenter = spy(HomePresenter(mDataManager!!))
mPresenter.attachView(mView!!)
}

@Test
fun requestSecurityQuestion_onSuccess() {
val response = SettingsResponse()
response.question = TestData.secretQuestion
response.processId = TestData.processId

`when`(mPresenter.api).thenReturn(mApi)
`when`(mDataManager!!.token).thenReturn(TestData.userToken)
`when`<Observable<SettingsResponse>>(mApi!!.getSecurityQuestionToday(
TestData.userToken, ACTION_ASK_SECURITY_QUESTION_ON_LOGIN, 0))
.thenReturn(Observable.just(response))

mPresenter.requestSecurityQuestion()

verify<HomeView>(mView).dismissLoadingDialog()
verify<HomeView>(mView).showVsecVerificationDialog(0, TestData.secretQuestion)
}
}

这是我在命令行上使用 运行测试时得到的结果./gradlew testDebugUnitTest
> Task :app:testDebugUnitTest 

com.domain.app.screens.main.home.HomePresenterTest > requestSecurityQuestion_onSuccess FAILED
org.mockito.exceptions.verification.WantedButNotInvoked at HomePresenterTest.kt:306

另外:我使用的是 Android Studio 3.1.4,Gradle 版本是 3.1.2,Mockito 的版本是 2.8.9

最佳答案

我有同样的问题,但使用Java。
我的原因是,我试图返回一个在静态上下文中调用的方法的模拟,因此我的 Mockito.when() 没有打扰。称呼。即使这样做是不好的做法,我还是将方法调用移出静态上下文,因为它不需要是静态的,并且它可以工作。
也许这有帮助。

关于android - MockitoJUnit 测试在 Android Studio 中运行但在命令行上运行时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227109/

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