mockito 模拟服务的空异常

cl25kdpy  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(302)

我想模拟并测试这段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服务吗?

5cg8jx4n

5cg8jx4n1#

你一定要这样做

@Mock
    private PromoCodeService promoCodeService;
    @InjectMocks
    private BusterClient app;

      @BeforeEach
      void setUp() {

        MockitoAnnotations.initMocks(this);
      }

    @Test
    public void testTrackedReferralNotMatchingPromoCode() throws Exception {

        when(promoCodeService.findByCampaignPromoCodeIds(Long.valueOf(12), "test")).thenReturn(Optional.of(PromoCode.builder().id(Long.valueOf(1)).build()));

        ...
// Test a public method and not a private method. Use one public method that in turn will call your "getPromoCode".
    }
hujrc8aj

hujrc8aj2#

尝试将模拟对象注入到正在创建的客户机中,并在测试方法中创建客户机,而不是将其设置为类变量

var app = new BusterClient(o); //where o is the object you created with mockito

相关问题