【发布时间】:2019-12-02 20:56:49
【问题描述】:
我正在编写一个 Spring Boot Rest 服务,在该服务中尝试对使用 @Service 注释的类进行单元测试。 此服务类在内部使用另一个服务类。 这是代码:
@Service
public class TieredClaimServiceImpl implements TieredClaimService {
//this is the second service used within
// commented out setter injection and used constructor injection
// @Autowired
private DiscountTierService discountTierService;
@Autowired
public TieredClaimServiceImpl(MerchRepository merchRepository,SalesRepository
salesRepository,DiscountTierService discountTierService) {
this.merchRepository = merchRepository;
this.salesRepository = salesRepository;
this.discountTierService = discountTierService;
}
这是我需要进行单元测试的类中的方法:
@Override
public List <TieredClaimDto> calculateClaim(ClaimRequestDto claimRequestDto,String xAppCorelationId) throws SystemException {
/** get the discount tier config data - this is where we are using the other service **/
List<DiscountTierDto> discountTierList = discountTierService.get();
我想模拟在“TieredClaimServiceImpl”中使用的“DiscountTierService”
在我的单元测试课程中,我尝试模拟对该服务的调用:
DiscountTierService discountTierService = mock(DiscountTierService.class);
或
DiscountTierService discountTierService = spy(new DiscountTierServiceImpl());
这些都不起作用。
虽然没有直接关系,但我有一个与整个解决方案相关的问题here
【问题讨论】:
-
你的单元测试是什么样子的?你是如何创建
TieredClaimServiceImpl的——你是在启动整个 spring 上下文以将它们创建为 bean,还是使用new在没有上下文的情况下手动创建? -
Mocking 是这里的合适工具。请解释“没用”。
标签: java spring spring-boot unit-testing mocking