【问题标题】:NullPointerException when mocking a DB call with Pageable and Slice Interfaces with Mockito使用 Mockito 模拟具有 Pageable 和 Slice 接口的 DB 调用时出现 NullPointerException
【发布时间】:2018-11-13 10:27:31
【问题描述】:

总结

我们正在尝试使用 Pageable 和 Slice 对象模拟对 DB 的调用,但在应用程序调用时,模拟没有返回分配的返回值。

详细介绍

我们的Spring-Data Repository 中有一个Pageable 方法:

public interface CatRepository extends CouchbasePagingAndSortingRepository<Cat, String> {

  Slice<Cat> findAllByOwnerIdAndName(String ownerId, String name, Pageable pageable);

由于Slice 是一个接口,我们创建了一个实现其方法的MockSlice 类:

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

在为此调用创建Mockito 测试时,我们编写了以下代码:

 Slice<Cat> slice = MockSlice.builder().content(new LinkedList()).build();
  when(catRepository.findAllByOwnerIdAndname(anyString(), anyString(), any(Pageable.class))).thenReturn(slice);

测试类有这些注解:

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class GetCatsTest{

但是,在服务类中,当单元测试运行时,下面的slice 是null:

  Pageable pageable = PageRequest.of(pageNumber, 1000, Sort.by("id"));
  Slice<Cat> slice = catRepository.findAllByOwnerIdAndName("23423", "Oscar", pageable);
  catList = slice.getContent();  <-- NullpointetException here

编辑

为了确保接线正确,并且整个 conf 工作正常,我在存储库中添加了另一个不可分页的方法,对其进行了模拟,它工作正常:

在测试类中:

LinkedList<Cat> list = new LinkedList<>();
list.add(new Cat("fasdfasf", "Oscar"));
when(catRepository.findAllByOwnerIdAndName(anyString(), anyString())).thenReturn(list);

在仓库界面中:

List<Cat> findAllByOwnerIdAndName(String ownerId, String name);

【问题讨论】:

  • 你能在你的服务和测试中显示catRepository的声明吗?可能没有正确注入模拟
  • 您确定.build() 方法没有返回null?
  • @migron ,是的。 build() 正在正确创建 MockSlice
  • @EamonScullion ,catRepository 似乎注入正常,因为其中的其他方法被正确模拟。
  • 您的测试在findAllByOwnerIdAndname 中使用小写n 作为名称是否只是一个错字?

标签: java unit-testing spring-boot mockito


【解决方案1】:

在这个问题上花了几个小时之后......

问题出在Intellij 而不是代码。

Intellij 版本是:

2018.2.3 Ultimate Edition

Build #UI-182.4323.46

Built on Sep 3 2018

在某个时候它刚刚开始工作......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多