How can I remove try-catch block for the assertThat
in the ifPresent()
? The compiler gives me only one option for using assertThat
in ifPresent()
, which is to surround it with try-catch block. Throw the exception again is not allowed too.
@Test
public void testPostRequestThenSaveResponse()
throws HttpStatusCodeException, JsonProcessingException, IllegalArgumentException, IOException {
// Should success.
try {
ServiceAssignmentImpl.httpPostDeliveryOrder(url, token, sod, customerSite, customer, item, uom, driver)
.ifPresent((deliveryOrderResponse) -> {
// increase DO number for next test.
deliveryOrderNum ;
DeliveryOrderResponse savedDOResponse = deliveryOrderResponseRepository
.save(deliveryOrderResponse);
DeliveryOrderResponse fetchedDOResponse = deliveryOrderResponseRepository
.findOne(savedDOResponse.getId());
try {
assertThat(json.write(fetchedDOResponse))
.isEqualTo(objectMapper.writeValueAsString(deliveryOrderResponse));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
} catch (HttpStatusCodeException e) {
// need getResponseBodyAsString() to see detail error message.
System.out.println("** HttpStatusCodeException: " e.getResponseBodyAsString());
throw e;
}
}
CodePudding user response:
Just use .get()
, your test should not pass if the response is not present, so there is no need to make it conditional.
I've adapted your code as best I could without a MCVE.
@Test
public void testPostRequestThenSaveResponse()
throws HttpStatusCodeException, JsonProcessingException, IllegalArgumentException, IOException {
// Should success.
try {
var = deliveryOrderResponseServiceAssignmentImpl.httpPostDeliveryOrder(url, token, sod, customerSite, customer, item, uom, driver).get()
// increase DO number for next test.
deliveryOrderNum ;
DeliveryOrderResponse savedDOResponse = deliveryOrderResponseRepository
.save(deliveryOrderResponse);
DeliveryOrderResponse fetchedDOResponse = deliveryOrderResponseRepository
.findOne(savedDOResponse.getId());
assertThat(json.write(fetchedDOResponse))
.isEqualTo(objectMapper.writeValueAsString(deliveryOrderResponse));
} catch (HttpStatusCodeException e) {
// need getResponseBodyAsString() to see detail error message.
System.out.println("** HttpStatusCodeException: " e.getResponseBodyAsString());
throw e;
}
}