我使用 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)
我无法理解,因为当我使用类似的代码直接在服务层上测试该方法时,它通过了测试。我有这个测试的解决方法,但我只是想了解为什么这不起作用。我真的很感激这方面的一些帮助。
如果您希望我添加任何其他信息,请随时告诉我。