【问题标题】:how to verify a parameter in unit test如何在单元测试中验证参数
【发布时间】:2021-01-27 23:22:51
【问题描述】:

我有一个调用 repository.startFlling(orderStorage.flOrder!!.id, action) 的运行函数,我正在尝试验证 repository.startFlling 是否使用正确的参数调用。

我可以模拟 orderStorage.flOrder!!.id,但 action 是在函数中本地创建的,并且基于 DateTime

我尝试在我的测试用例中创建一个动作,但这与实际函数中动态创建的不匹配。

我该如何处理这种情况/

这是我在调用时创建的带有startTime 的运行函数。

 val startTime = DateTime()
lateinit var orderEquipment: Equipment

override suspend fun run(params: Params): Either<Failure, GenericResponse> {
    this.orderEquipment = params.equipment
    val action = TimestampedAction(
        app.session.user.id, null, startTime
    )
    val result = repository.startFlling(orderStorage.flOrder!!.id, action)
    result.fold(::handleStartFllingFailure, ::handleStartFllingSuccess)
    return result
}

测试用例

@Test
fun `when StartFllingUseCase is invoked then call startFlling in flOrderRespository with correct parameters`() {
    val id = "1"
    val userId = "userId"
    val flOrderId = "flOrderId"
    val action: TimestampedAction = TimestampedAction(userId, null, DateTime())
    val equipment: Equipment = mock()

    runBlocking {
        whenever(user.id).thenReturn(userId)
        whenever(orderStorage.flOrder).thenReturn(flOrder)
        whenever(flOrder.id).thenReturn(flOrderId)
        whenever(equipment.times).thenReturn(times)
        whenever(flOrderRepository.startFlling(any(), any()))
            .thenReturn(Either.Right(GenericResponse(true)))

        startFllingUseCase.run(StartFllingUseCase.Params(equipment))

        verify(flOrderRepository).startFlling(flOrderId, action)
    }
}

错误

org.mockito.exceptions.base.MockitoAssertionError: There were multiple verification failures:
1. Argument(s) are different! Wanted:
flOrderRepository.startFlling(
    "flOrderId",
    com.xx.xxx.objects.florder.equipment.TimestampedAction@4567e53d
);
-> at com.xx.xxx.clean.florder.data.repository.FlOrderRepository.startFlling(FlOrderRepository.kt:17)
Actual invocations have different arguments:
flOrderRepository.startFlling(
    "flOrderId",
    com.xx.xxx.objects.florder.equipment.TimestampedAction@66ec9390
);

你能建议我如何解决这个问题

谢谢 回复

【问题讨论】:

    标签: java android unit-testing kotlin mocking


    【解决方案1】:

    您可以使用argumentCaptor,如here 所述。

    或者,如果你使用 mockitokotlin2,有一个名为 ArgThat 的函数会创建新的 基于谓词的参数匹配器。

    /**
     * Creates a custom argument matcher.
     * `null` values will never evaluate to `true`.
     *
     * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.
     */
    inline fun <reified T : Any> argThat(noinline predicate: T.() -> Boolean): T {
        return Mockito.argThat { arg: T? -> arg?.predicate() ?: false } ?: createInstance(
              T::class
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 2016-05-18
      • 1970-01-01
      • 2014-09-10
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      相关资源
      最近更新 更多