【问题标题】:Mocking an autowired field using mockito gives null response in rest call使用 mockito 模拟自动装配的字段在休息调用中给出空响应
【发布时间】:2020-02-18 21:26:10
【问题描述】:

我正在使用 spring boot 和 mockito。我已经自动装配了一个类,即 BDSRequest,在 Junit Test 类中,我使用了 @Spy 和 @InjectMocks 注释。但是在 Junits 中调用休息服务时,我收到响应(bdsCustomerHoldings)为空并且断言失败。如何在没有像 mockito.when(restTemplate.postForObject(Constants.BDS_REST_URL, bdsRequest, BDSCustomerHoldings.class) ?

class BDSRestCall
{

    @Autowired
    BDSRequest bdsRequest;

    public BDSCustomerHoldings getBDSCustomerInfo(String channelId, String customerId, String cinSuffix,
            String countryCode) {

        logger.info("prepareRequestForBDS");
        Header header = new Header();
        header.setMsgId(RandomStringUtils.randomAlphanumeric(20));
        header.setChannelId(channelId);
        header.setCountryCode(countryCode);
        header.setRecordTimeStamp(DateTimeFormatter.ofPattern(Constants.DATE_FORMATTER).format(LocalDateTime.now()));

        TxnRequest txnRequest = new TxnRequest();
        txnRequest.setIdDoc(customerId);
        txnRequest.setIdDocSuffix(cinSuffix);
        txnRequest.setIdDoctype("");
        txnRequest.setInsurerCode("");

        bdsRequest.setHeader(header);
        bdsRequest.setTxnRequest(txnRequest);

        logger.info("BDS request " + bdsRequest);

        BDSCustomerHoldings bdsResponse = restTemplate.postForObject(Constants.BDS_REST_URL, bdsRequest,
                BDSCustomerHoldings.class);
        logger.info("BDS Response : " + bdsResponse);

        return bdsResponse;
    }
}

朱尼特:

@RunWith(MockitoJUnitRunner.class)
class BDSRestCallTest
{
    @InjectMocks
    private BDSRestCall bdsRestCall;

    @Mock
    private RestTemplate restTemplate;

    @Spy
    private BDSRequest bdsRequest;



    @Test
        public void getBDSCustomerInfoExceptionTest() {
            BDSCustomerHoldings bdsCustomerHoldings = bdsRestCall.getBDSCustomerInfo("SG", "S9718016D",
                    "00", "SG");
            System.out.println("response is " + bdsCustomerHoldings);
            assertNotNull("response is not null", bdsCustomerHoldings);
        }

}

【问题讨论】:

  • 你需要模拟 restTemplate.postForObject() 调用
  • 我想在不模拟 restTemplate.postForObject() 的情况下进行测试
  • 然后注入一个真正的 RestTemplate 而不是注入一个模拟的。除了你告诉它做的事情之外,一个 mock 不会做任何事情。
  • 我建议您模拟 restTemplate 调用,因为实际的 API 调用可能会在不同的条件下产生不同的响应。例如,如果您正在调用的服务已关闭,即使您的测试用例也会导致状态 500是对的。

标签: rest junit mockito


【解决方案1】:

由于我们使用@RunWith(MockitoJUnitRunner.class),所以我们应该像下面这样模拟restTemplate的响应

Mockito.when(restTemplate.postForObject(Mockito.anyString(), bdsRequest, BDSCustomerInsuranceHoldings.class)).thenReturn(sampleBDSCustomerInsuranceHoldings());

然后它会给出模拟响应。

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多