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

时间:2019-01-16 23:51:23

标签: android kotlin mockito android-junit

我正在尝试使用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

1 个答案:

答案 0 :(得分:0)

我有同样的问题,但是使用Java。

对我来说,原因是,我试图在静态上下文中调用的方法上返回模拟,因此Mockito.when()调用不会对我造成困扰。即使这样做是不好的做法,我也将方法调用移出了静态上下文,因为不需要将其静态化,并且可以正常工作。

也许有帮助。