繁体   English   中英

如何在单元测试中验证参数

[英]how to verify a parameter in unit test

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

我可以模拟orderStorage.flOrder.!.idaction是在 function 本地创建的,并且基于DateTime

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

我该如何处理这种情况/

这是我的运行 function 和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
);

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

谢谢 R

您可以像这里描述的那样使用argumentCaptor

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

/**
 * 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
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM