java - 无法在 Java 中获取单元测试的 thenReturn() 值
问题描述
我有以下服务和测试方法:
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
方法?
解决方案
你通常会做这样的事情:
public class ProductServiceImplTest {
// create an actual instance of the class you want to test, with its dependencies supplied by mocks
@InjectMocks
ProductServiceImpl productService;
// This will be injected into productService;
@Mock
ProductRepository productRepository;
@Test
public void testSomeAspectOfProductServiceImplBehaviour() {
// tell the productRepository mock to respond as necessary for the test
when(productRepository.something()).thenReturn(...);
// call the method you want to test and check that the result is as expected
assertThat(productService.someMethod(), Matchers.equalTo(...);
}
}
推荐阅读
- azure-devops - 如何将 Azure DevOps 构建工件复制到同一管道中的 Docker 映像构建?
- amazon-web-services - 粘贴 Spark Scala 脚本以检查 S3 中是否存在文件?
- maven - 从现有源对模块运行 mvn 命令
- jquery - 如何使用列的类名来设置默认列排序?
- javascript - setInterval 内的 api 命中两次
- python - 使用自定义虚拟环境加载 Python 模块
- python - 串行端口块 GUI - 发射信号块 PyQt-App
- javascript - 手动复制构建 index.html Vue 和 Angular
- matplotlib - Matplotlib 用于子图的多面板
- xamarin.forms - xamarin形成webview没有响应android中的_blank链接