mockito.when返回空值时

时间:2019-10-09 13:14:19

标签: java junit mockito

在CrossSellOffersServiceAdapter类中,此语句:

crossSellOffersConnectBDS.getBDSCustomerInfo(channelId, customerId, cinSuffix,
                    countryCode);

应在模拟时返回该值。但是它在CrossSellOffersServiceAdapterTest类中返回空值。

public class CrossSellOffersServiceAdapter implements CrossSellOffersService {

    @Autowired
    private CrossSellOffersConnectBDS crossSellOffersConnectBDS;

    @Autowired
    private CrossSellOffersConnectCMP crossSellOffersConnectCMP;

    @Autowired
    private BDSCustomerHoldings bdsCustomerHoldings;

    private static final Logger LOGGER = LoggerFactory.getLogger(CrossSellOffersServiceAdapter.class);

    @Override
    public Offers getApplicableOffers(String channelId, String customerId, String cinSuffix, String countryCode,
            String interactionPoint, String sessionId, Integer numberOfOffers) throws CrossSellOffersException {

        bdsCustomerHoldings = crossSellOffersConnectBDS.getBDSCustomerInfo(channelId, customerId, cinSuffix,
                countryCode);

        CMPOffer cmpOffer = crossSellOffersConnectCMP.getCMPOffers(bdsCustomerHoldings, interactionPoint, sessionId,
                numberOfOffers);

        Offers offers = getOffers(cmpOffer);

        return offers;
    }



}


public class CrossSellOffersServiceAdapterTest {

    @InjectMocks
    private CrossSellOffersServiceAdapter crossSellOffersService;

    @Mock
    private CrossSellOffersConnectBDSAdapter crossSellOffersConnectBDS;

    @Mock
    private CrossSellOffersConnectCMPAdapter crossSellOffersConnectCMP;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    OffersRequest offersRq;

    @Mock
    private BDSRequest bdsRequest ;

    @Mock
    private BDSCustomerHoldings bdsResponse;

    @Test
    public void getApplicableOffersTest() throws CrossSellOffersException {
        Mockito.when(crossSellOffersConnectBDS.getBDSCustomerInfo("MBSG", "S9718016D", "00", "SG")).thenReturn(sampleBDSResponse());
        Mockito.when(crossSellOffersConnectCMP.getCMPOffers(bdsResponse, "NEW_CC_ADDON", "IBOXS007", 1)).thenReturn(CrossSellOffersConnectCMPAdapterTest.sampleCMPOffer());
        Offers offers = crossSellOffersService.getApplicableOffers("MBSG", "IBOXS007", "00", "SG","NEW_CC_ADDON", "S9718016D", 1);
        assertNotNull(offers, "response is not null");
    }
}

1 个答案:

答案 0 :(得分:0)

认为您缺少了模拟初始化:

  import org.mockito.MockitoAnnotations;

  @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
  }