【发布时间】:2021-06-28 00:34:51
【问题描述】:
我有以下服务和测试方法:
ProductServiceImpl:
public List<ProductDTO> findAllByCategoryUuid(UUID categoryUuid) {
// code omitted
return result;
}
ProductServiceImplTest:
@Spy
@Autowired
ProductServiceImpl productService;
@Mock
ProductRepository productRepository;
// ... other mock repositories
@Test
public void testFindAllByCategoryUuid() {
UUID categoryUuid = UUID.randomUUID();
final List<Product> productList = new ArrayList<>();
for (int i = 0; i < size; i++) {
// create product by setting "categoryUuid" and add to productList
}
when(productRepository.saveAll(productList)).thenReturn(productList); // ?
List<ProductDTO> response = new ArrayList<>();
doReturn(response).when(productService).findAllByCategoryUuid(categoryUuid); // ?
}
虽然我创建了具有正确categoryUuid 关系的模拟产品,但我无法通过相同的categoryUuid 和findAllByCategoryUuid 方法检索这些模拟产品总是返回空列表。那么,我该如何解决?以及如何正确使用上面的when 和doReturn 方法?
【问题讨论】:
-
您使用
@Spy的原因是什么?此外,您可能需要使用@MockBean。最后,在大多数情况下,如果您使用构造函数注入,则不需要 Spring 进行单元测试;只需将您的模拟传递给被测类的构造函数即可。 -
为什么
productService上有doReturn?这不是您要测试的对象吗?您的测试也没有断言。在findAllByCategoryUuid中的productRepository上调用了哪个方法?是saveAll吗? -
@chrylis-cautiouslyoptimistic- 为什么不通过更新我的代码作为答案来发布示例?
-
因为我对您的代码的作用还不够了解,无法给您答案。例如,在我理解你为什么选择使用
doReturn(response).when(productService)...之前,我可能并不真正理解你想要做什么。 -
我的问题不是你为什么使用
doReturn而不是when,而是你为什么要嘲笑被测类的行为。
标签: java spring-boot unit-testing testing mocking