【发布时间】:2021-06-27 18:42:15
【问题描述】:
我没有测试经验,并尝试通过单元测试来测试方法。我看过的所有示例都通过使用模拟值来执行操作。我知道,我还将在我的项目中使用带有mockito 的模拟值。这是我要测试的服务方法:
ProductServiceImpl:
public List<ProductDTO> findAllByCategoryUuid(UUID categoryUuid) {
// code omitted
return result;
}
这是我的单元测试类:
ProductServiceImplTest:
// ? @InjectMocks
@Autowired
ProductServiceImpl productService;
@Mock
ProductRepository productRepository;
@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
}
productRepository.saveAll(productList);
when(productService.findAllByCategoryUuid(categoryUuid)
.thenReturn(productList);
}
我的问题:
1. 为了测试服务方法,上述方法是否正确?我认为我不应该在服务方法内部处理,只需通过categoryUuid 并检查该方法的结果进行测试?这是真的吗?
2. 在测试类中,我使用@Autowired 访问服务方法,但我不确定是否应该@Mock。有错吗?
任何帮助将不胜感激。
更新:我还使用 DiffBlue 插件创建单元测试,它会生成如下所示的测试方法。但我认为它似乎是作为测试存储库方法而不是服务方法。不是吗?
@Test
public void testFindAllByCategoryUuid() {
when(this.productRepository.findAllByCategoryUuid((UUID) any()))
.thenReturn(new ArrayList<Product>());
assertTrue(this.productService.findAllByCategoryUuid(UUID.randomUUID())
.isEmpty());
verify(this.productRepository).findAllByCategoryUuid((UUID) any());
// ...
}
【问题讨论】:
-
我对 testFindAllByCategoryUuid 的评论 - 它使用模拟 productRepository 来测试 productService(productService 正在测试中,因为它在 assert 语句中),看起来对我有效
-
理想情况下,JUnit 测试应该在实际代码之前编写,因此它可以作为开发人员的规范,据我在 TDD 书中记得。如今,当人们拥有高测试覆盖率时,他们似乎更快乐,但我不确定是否所有代码都需要所有这些测试。 CRUD 测试对我来说听起来像是浪费时间,恕我直言
-
您似乎误解了什么是模拟。必须将模拟配置为返回某些内容。 DiffBlue 生成的测试确实设置了模拟以返回一个已知值(在这种情况下为空列表),但我不明白对
assertTrue(...)和verify(...)的调用应该测试什么。 -
@justice 如果它的格式正确,我可能会回答这个问题。
标签: java spring spring-boot unit-testing testing