简体   繁体   中英

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.

In Details

We have a Pageable method in our Spring-Data Repository :

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:

@Builder
@Data
public class MockSlice implements Slice{
...

When creating a Mockito test for this call we wrote this code:

 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 :

  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:

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 version is:

2018.2.3 Ultimate Edition

Build #UI-182.4323.46

Built on Sep 3 2018

At some point it just started to work....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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