Mockito - Kotlin 测试在尝试捕获 Pageable 参数时抛出空指针异常

Nic*_*Div 5 unit-testing mockito kotlin pageable

我使用 Mockito 为控制器中的方法编写了一个非常简单的测试

@Test
fun `get items based on category ID`() {
    val pageable: Pageable = PageRequest.of(5, 50)
    controller.get(10, pageable)

    val captor = ArgumentCaptor.forClass(Int::class.java)
    val pageableCaptor = ArgumentCaptor.forClass(Pageable::class.java)
    Mockito.verify(itemService).getItemsBasedOnCategoryID(captor.capture(), pageableCaptor.capture())
    assertEquals(captor.value, 10)
    assertEquals(pageableCaptor.value.pageSize, 50)
    assertEquals(pageableCaptor.value.pageNumber, 5)
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个例外

pageableCaptor.capture() must not be null
java.lang.NullPointerException: pageableCaptor.capture() must not be null
    at com.practice.ItemControllerTest.get items based on category ID(ItemControllerTest.kt:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Run Code Online (Sandbox Code Playgroud)

我无法理解,因为当我使用类似的代码直接在服务层上测试该方法时,它通过了测试。我有一个针对此测试的解决方法,但我只是想了解为什么这不起作用。我真的很感激一些帮助。

如果您希望我添加任何其他信息,请随时告诉我。

Maf*_*for 15

问题在于 的pageable参数getItemsBasedOnCategoryID是不可为空的,而 的返回类型ArgumentCaptor.capture平台类型,Kotlin 编译器认为它可能为空(实际上 capture() 返回 null,这就是 Mockito 的工作原理)。在这种情况下,编译器会在使用该类型时生成空检查。您可以在测试的反编译代码中看到它:

@Test
public final void get_items_based_on_category_ID {
      ...
      Object var10002 = pageableCaptor.capture();
      Intrinsics.checkNotNullExpressionValue(var10002, "pageableCaptor.capture()"); <<- NPE
      var10000.getItemsBasedOnCategoryID(var4, (Pageable)var10002);
      ...
}
Run Code Online (Sandbox Code Playgroud)

诀窍是以某种方式欺骗编译器以防止其生成空检查。

选项 1:使用mockito-kotlin库。它提供了此类问题的解决方法以及一些附加工具。这可能是你最好的选择,因为你可能会遇到下一个问题,例如使用 Mockito 的any()参数匹配器时(同样的故事,空与非空不匹配)

选项 2:DIY:

  1. 首先,显式声明 ArgumentCapture 的类型参数为不可空:
val pageableCaptor: ArgumentCaptor<Pageable> = ArgumentCaptor.forClass(Pageable::class.java)
Run Code Online (Sandbox Code Playgroud)

如果没有显式声明,则 的类型pageableCaptorArgumentCaptor<Pageable!>!,即平台类型。

  1. 那么你将需要一个辅助函数:
@Suppress("UNCHECKED_CAST")
private fun <T> capture(captor: ArgumentCaptor<T>): T = captor.capture()
Run Code Online (Sandbox Code Playgroud)

它似乎是一个无操作函数,但重点是它不再返回平台类型:如果 ArgumentCaptor 的类型参数不可为 null,则函数返回值的类型也是如此。

  1. 最后使用这个函数代替ArgumentCaptor.capture()
Mockito.verify(itemService).getItemsBasedOnCategoryID(captor.capture(), capture(pageableCaptor))
Run Code Online (Sandbox Code Playgroud)

现在,Kotlin 编译器认为capture(pageableCaptor)永远不会返回 null,因此它不会生成任何 null 检查。