【问题标题】:My test cases fail when run together but pass individually, at android studio我的测试用例在 android studio 一起运行但单独通过时失败
【发布时间】:2018-09-13 12:25:18
【问题描述】:

测试用例单独运行良好,但是当我将所有测试用例一起运行时,其中一些失败了。

我尝试使用 Mockito.reset 函数来重置模拟,但它不起作用

那么,我该怎么做才能重置模拟?

注意:我使用的是 mockito 2.21.0

class MainPresenterTest {

private lateinit var api: Api
private lateinit var mainViewContract: MainActivity
private lateinit var presenter: MainPresenter

@Before
fun setup() {
    api = Mockito.mock(Api::class.java)
    mainViewContract = Mockito.mock(MainActivity::class.java)
    presenter = MainPresenter(mainViewContract, api)
}

@After
fun resetMocks() {
    reset(api, mainViewContract)
    StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().build())
}

@Test
fun changeShiftToOn1() {

    Shared.shiftState = ShiftStatus.OFF
    val postShiftResponse = PostShiftResponse(200, "132")

    Mockito.`when`(api.startShift()).thenReturn(postShiftResponse)

    Mockito.`when`(mainViewContract.popupErrorMessage()).then { }
    Mockito.`when`(mainViewContract.showShiftDialog()).then { }
    Mockito.`when`(mainViewContract.dismissDialog()).then { }
    Mockito.`when`(mainViewContract.showProgressDialog()).then { }

    presenter.changeShiftState()

    Mockito.verify(mainViewContract, Mockito.atLeastOnce()).showConnectingBar()
    Mockito.verify(mainViewContract, Mockito.atLeastOnce()).startServices()
    Mockito.verify(mainViewContract, Mockito.atLeastOnce()).setStartShiftLayout(false)
}

@Test
fun changeShiftToOn2() {

    Shared.shiftState = ShiftStatus.OFF
    val postShiftResponse = PostShiftResponse(400, "132")

    Mockito.`when`(api.startShift()).thenReturn(postShiftResponse)

    Mockito.`when`(mainViewContract.popupErrorMessage(null)).then { }
    Mockito.`when`(mainViewContract.showShiftDialog()).then { }
    Mockito.`when`(mainViewContract.dismissDialog()).then { }
    Mockito.`when`(mainViewContract.showProgressDialog()).then { }

    presenter.changeShiftState()

    Mockito.verify(mainViewContract, Mockito.atLeastOnce()).popupErrorMessage(null)
    Mockito.verify(mainViewContract, Mockito.atLeastOnce()).showShiftDialog()

}
}

【问题讨论】:

  • 有哪些故障?你得到了哪些错误?
  • 请添加导入..
  • import io.swagger.client.models.PostShiftResponse import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.reset导入 android.os.StrictMode @Roland
  • 没有错误,我只想一起运行测试但不工作@Fred

标签: android unit-testing android-studio kotlin mockito


【解决方案1】:

如果你正在做一些异步任务,那么确保在异步操作完成后执行下一条指令。

为了等待异步任务,有一个名为 Awaitility 的库。 这是它的链接; https://github.com/awaitility/awaitility.git

你也可以像我一样使用它, //SUT是被测系统 SUT.login()

    await().until {
        SUT.coroutineContext.isActive
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多