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)
}
但我得到了这个例外
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)
我无法理解,因为当我使用类似的代码直接在服务层上测试该方法时,它通过了测试。我有这个测试的解决方法,但我只是想了解为什么这不起作用。我真的很感激这方面的一些帮助。
如果您希望我添加任何其他信息,请随时告诉我。
解决方案
问题是 的pageable
参数getItemsBasedOnCategoryID
是不可为空的,而返回的类型ArgumentCaptor.capture
是平台类型,Kotlin 编译器认为它可能可以为空(实际上 capture() 返回空,这就是 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);
...
}
诀窍是以某种方式欺骗编译器以防止它生成空检查。
选项 1:使用mockito-kotlin库。它为这类问题提供了解决方法,并提供了几个额外的工具。这可能是您的最佳选择,因为您可能会面临下一个问题,例如在使用 Mockito 的any()
参数匹配器时(同样的故事,空值与非空值不匹配)
选项2:DIY:
- 首先,将 ArgumentCapture 的类型参数显式声明为不可为空:
val pageableCaptor: ArgumentCaptor<Pageable> = ArgumentCaptor.forClass(Pageable::class.java)
如果没有显式声明,则类型pageableCaptor
为ArgumentCaptor<Pageable!>!
,即平台类型。
- 然后你将需要一个辅助函数:
@Suppress("UNCHECKED_CAST")
private fun <T> capture(captor: ArgumentCaptor<T>): T = captor.capture()
它似乎是一个无操作函数,但关键是它不再返回平台类型:如果 ArgumentCaptor 的类型参数不可为空,那么函数返回值的类型也是如此。
- 最后使用这个函数而不是
ArgumentCaptor.capture()
:
Mockito.verify(itemService).getItemsBasedOnCategoryID(captor.capture(), capture(pageableCaptor))
现在 Kotlin 编译器认为capture(pageableCaptor)
永远不会返回 null,因此它不会生成任何 null 检查。
推荐阅读
- psql - 普遍视图中的迄今为止的字符串
- sparql - 为什么我得到不同的结果?
- django - 如何过滤查询集以使用 django rest 框架中的实例序列化嵌套序列化程序?
- google-apps-script - 仅将非空单元格复制到通过电子邮件发送的 HTML 对象中
- c# - 将文件从用户网页直接上传到 Google Cloud Storage
- linux - 在 _interactive_ docker start 之前,docker 容器似乎失败了 /etc/hosts
- ruby-on-rails - ActionCable:Module 的未定义方法`server`
- javascript - 是否可以在我的服务器上为我的网站禁用 JS
- unity3d - 计算着色器中的工作组执行顺序是否具有确定性和有序性?
- lua - MouseClick 和 MoveTo 事件不适用于产生的第二部分