【发布时间】: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是对的。