我想模拟并测试这段Java代码:
public class BusterClient {
public BusterClient() {
}
@Autowired
public BusterClient(PromoCodeService promoCodeService) {
this.promoCodeService = promoCodeService;
}
private Optional<PromoCode> getPromoCode(CustomerRegistrationEvent event) {
Optional<Long> campaignId = getCampaignIdAsLong(event);
if (!event.hasPromoCode() || !campaignId.isPresent()) {
return Optional.empty();
}
return promoCodeService.findByCampaignPromoCodeIds(campaignId.get(), event.getPromoCode());
}
}
我创建了以下测试代码:
@InjectMocks
private BusterClient app = new BusterClient();
@Test
public void testTrackedReferralNotMatchingPromoCode() throws Exception {
PromoCodeService o = mock(PromoCodeService.class);
when(o.findByCampaignPromoCodeIds(Long.valueOf(12), "test")).thenReturn(Optional.of(PromoCode.builder().id(Long.valueOf(1)).build()));
try {
Method method = BusterClient.class.getDeclaredMethod("getPromoCode", CustomerRegistrationEvent.class);
method.setAccessible(true);
method.invoke(app, customerRegistrationEvent);
} catch (InvocationTargetException e) {
e.getCause().printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
但我得到错误:promoCodeService.findByCampaignPromoCodeIds(java.lang.Long, String)" because "this.promoCodeService" is null
你知道什么是正确的方式来模仿PromoCodeService
服务吗?
2条答案
按热度按时间5cg8jx4n1#
你一定要这样做
hujrc8aj2#
尝试将模拟对象注入到正在创建的客户机中,并在测试方法中创建客户机,而不是将其设置为类变量