[英]NullPointerException when mocking a DB call with Pageable and Slice Interfaces with Mockito
Summary 摘要
We are trying to mock a call to DB with a Pageable & Slice objects, but the mock is not returning the assigned return value when called by the application. 我们正在尝试使用Pageable&Slice对象模拟对DB的调用,但是当应用程序调用时,模拟未返回分配的返回值。
In Details 详细介绍
We have a Pageable method in our Spring-Data Repository
: 我们在
Spring-Data Repository
有一个Pageable方法:
public interface CatRepository extends CouchbasePagingAndSortingRepository<Cat, String> {
Slice<Cat> findAllByOwnerIdAndName(String ownerId, String name, Pageable pageable);
Since Slice
is an interface, we created a MockSlice
class that implements its methods: 由于
Slice
是接口,因此我们创建了一个MockSlice
类来实现其方法:
@Builder
@Data
public class MockSlice implements Slice{
...
When creating a Mockito
test for this call we wrote this code: 在为此调用创建
Mockito
测试时,我们编写了以下代码:
Slice<Cat> slice = MockSlice.builder().content(new LinkedList()).build();
when(catRepository.findAllByOwnerIdAndname(anyString(), anyString(), any(Pageable.class))).thenReturn(slice);
The test class has these annotations: 测试类具有以下注释:
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class GetCatsTest{
But, in the service class, when the unit test runs, the following slice
is null
: 但是,在服务类中,当运行单元测试时,以下
slice
为null
:
Pageable pageable = PageRequest.of(pageNumber, 1000, Sort.by("id"));
Slice<Cat> slice = catRepository.findAllByOwnerIdAndName("23423", "Oscar", pageable);
catList = slice.getContent(); <-- NullpointetException here
EDIT 编辑
To make sure the wiring is correct, and the overall conf is working fine, I added another non-paginatable method to the repository, mocked it and it is working fine: 为了确保接线正确,并且整个conf工作正常,我向存储库添加了另一个不可分页的方法,对其进行了模拟,并且工作正常:
In Test class: 在测试课程中:
LinkedList<Cat> list = new LinkedList<>();
list.add(new Cat("fasdfasf", "Oscar"));
when(catRepository.findAllByOwnerIdAndName(anyString(), anyString())).thenReturn(list);
In repository interface: 在存储库界面中:
List<Cat> findAllByOwnerIdAndName(String ownerId, String name);
After spending several hours on this issue.... 在这个问题上花了几个小时后...。
The problem was in Intellij
and not in the code. 问题出在
Intellij
而不是代码中。
Intellij version is: Intellij版本是:
2018.2.3 Ultimate Edition
Build #UI-182.4323.46
Built on Sep 3 2018
At some point it just started to work.... 在某个时候它才开始起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.