单元测试协程用例和暂停功能

时间:2020-11-02 17:15:59

标签: android unit-testing kotlin kotlin-coroutines

嗨,我正在尝试测试一个使用了用例的api暂停函数调用,但出现两个错误

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method com.xx.xxx.clean.orderview.domain.OnStandUseCaseCoroutine$Params.<init>, parameter action

org.mockito.exceptions.misusing.UnfinishedVerificationException: Missing method call for verify(mock) here: -> at com.xx.xxx.unit_test.clean.orderview.presenter.BaseOrderViewPresenterTest$when notifyOnStand is called then we create a TimestampedAction with the correct user id, vehicle, timestamp and pass that to the usecase$1.invokeSuspend(BaseOrderViewPresenterTest.kt:398)

这是我的测试用例

@Test
    fun `when notifyOnStand is called then we create a TimestampedAction with the correct user id, vehicle, timestamp and pass that to the usecase`() {
        val actionCaptor = argumentCaptor<TimestampedAction>()
        val timestamp = DateTime.now()

        every(noServiceRequiredBus.get()).thenReturn(Observable.just(REQUESTED))
        every(timingsUpdater.timestampCalculator(any(), any())).thenReturn(timestamp)

        baseOrderViewPresenter.setView(view)
        baseOrderViewPresenter.notifyOnStand()

        runBlocking {
            verify(onStandUseCaseCoroutine).run(OnStandUseCaseCoroutine.Params(anyString(), anyString(), capture(actionCaptor)))
        }
        assertEquals("1", actionCaptor.value.userId)
        assertEquals(null, actionCaptor.value.vehicleId)
        assertEquals(timestamp, actionCaptor.value.timestamp)
    }

OnStandUseCaseCoroutine

class OnStandUseCaseCoroutine @Inject constructor(
    private val orderRepository: OrderRepository,
    private val serviceOrderTypeProvider: ServiceOrderTypeProvider
) : UseCaseCoroutine<GenericResponse, OnStandUseCaseCoroutine.Params> (){

    override suspend fun run(params: Params) =
        orderRepository.notifyOnStandSuspend(serviceOrderTypeProvider.apiPathFor(params.serviceType), params.id, params.action)

    data class Params(val serviceType: String, val id: String, val action: TimestampedAction)
}

演示者

override fun notifyOnStand() {
    notifyOnStandApi(this::onStandResponseSuccess)
}

override fun notifyOnStandApi(callback: (GenericResponse?) -> Unit) {
    val serviceOrder = orderStorage.serviceOrder!!

    view?.showLoader()

    val timestamp = timingsUpdater.timestampCalculator(serviceOrder, getEquipment())

    val action = TimestampedAction(
        app.session.user.id, null, timestamp
    )

    onstandUseCaseCoroutines(serviceOrder.serviceType, serviceOrder.id, action, callback)
}

private fun onstandUseCaseCoroutines(serviceType: String, id: String, action: TimestampedAction, callback: (GenericResponse?) -> Unit) {
    try {
        onStandUseCaseCoroutine(OnStandUseCaseCoroutine.Params(serviceType, id, action)) {
            callback.invoke(it)
        }
    } catch (exception: Exception) {
        onStandResponseErrors()
    }
}

请指导我如何解决此问题 R

0 个答案:

没有答案