【发布时间】:2022-01-06 11:21:16
【问题描述】:
我是单元测试新手,在我的 Java (Spring Boot) 应用程序中使用 JUnit。我有时需要测试更新方法,但是当我在网上搜索时,没有合适的示例或建议。那么,您能否澄清一下如何测试以下更新方法?我认为这可能需要与测试 void 不同的方法。我还认为,在测试时首先模拟记录,然后更新其字段,然后更新。最后再次检索记录并比较更新的属性。但我认为可能有比这个没有经验的方法更合适的方法。
public PriceDTO update(UUID priceUuid, PriceRequest request) {
Price price = priceRepository
.findByUuid(priceUuid)
.orElseThrow(() -> new EntityNotFoundException(PRICE));
mapRequestToEntity(request, price);
Price updated = priceRepository.saveAndFlush(price);
return new PriceDTO(updated);
}
private void mapRequestToEntity(PriceRequest request, Price entity) {
entity.setPriceAmount(request.getPriceAmount());
// set other props
}
【问题讨论】:
-
有没有人从来没有为更新方法写过单元测试?
-
哪段代码实际上在做实体的更新?
-
priceRepository.saveAndFlush(price);amigo. -
那是更新数据库,不过我说的是
price,应该按照request更新吧?这是在哪里完成的? -
mapRequestToEntity(request, price);
标签: java spring-boot unit-testing junit mockito