【发布时间】: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