我的目标是为我的Adapter类获得代码覆盖率。我已经为读取SocketTimeoutException(读取超时)编写了Junit测试用例,它没有调用getSampleStatus()方法。如何从我的Test类中调用此getSampleStatus()。
rest class:
===========
class MyAdapter
{
@Autowired
BDSRequestForSubmitGIApp bdsRequestForSubmitGIApp;
@Autowired
RestTemplate restTemplate;
public BDSSubmitResponse submitGIApplicationToBDS(String channelId,String customerId,String cinSuffix, String countryCode) throws CrossSellOffersException {
BDSSubmitResponse bdsSubmitResponse = null;
try {
bdsSubmitResponse = restTemplate.postForObject(env.getProperty("bds_submit_gi_url"),
bdsRequestForSubmitGIApp, BDSSubmitResponse.class);
} catch (ResourceAccessException e) {
if (e.getCause().getClass().equals(SocketTimeoutException.class)) {
retrun getSampleStatus();// Junit is not covering this line
} else {
throw new CrossSellOffersException("DOMAIN_CONNECT_FAILURE",
"Couldn’t contact domain sub-system(s). Please try after some time.");
}
}
return bdsSubmitResponse;
}
private BDSSubmitResponse getSampleStatus(){
//business logic
}
}
Junit :
=======
@RunWith(MockitoJUnitRunner.class)
class MyAdapterTest
{
@InjectMocks
private MyAdapter crossSellOffersBDSAdapter;
@Mock
private RestTemplate restTemplate;
@Mock
BDSRequestForSubmitGIApp bdsRequestForSubmitGIApp;
@Test
public void submitGIApplicationToBDSReadTimeoutTest() throws Exception {
final String ERROR_MESSAGE =
"I/O error on POST request for \"https://message-publisher.uat.apps.cs.sgp.dbs.com/message\": Read timed out; nested exception is java.net.SocketTimeoutException: Read timed out";
Mockito.when(env.getProperty("bds_submit_gi_url")).thenReturn("https://message-publisher.uat.apps.cs.sgp.dbs.com/message");
Mockito.when(restTemplate.postForObject(env.getProperty("bds_submit_gi_url"),
bdsRequestForSubmitGIApp, BDSSubmitResponse.class)).thenThrow(new ResourceAccessException(ERROR_MESSAGE));
BDSSubmitResponse response = crossSellOffersBDSAdapter.submitGIApplicationToBDS(requestBody, "MBSG", "S9718016D", "00");
}
}
如何获取getSampleStatus()方法的代码覆盖率?
最佳答案
只是让您的模拟抛出SocketTimeoutException即可!
when(restTemplate.postForObject(
env.getProperty("bds_submit_gi_url"),
bdsRequestForSubmitGIApp,
BDSSubmitResponse.class)
).thenThrow(new SocketTimeoutException(ERROR_MESSAGE));