Reputation: 445
I have a third party service that returns HttpClientErrorException.NotFound
. When it returns this exception, I throw the exception from my application saying the input is invalid but for all other exceptions like service unavailable and all, I need to use a default value and proceed further.
My code block is as below:
public String callService(String input)
{
String value = "";
try
{
value = service.callMethod(input);
}
catch(HttpClientErrorException.NotFound e1)
{
throw new ApplicationException("Invalid Input")
}
catch(Exception e)
{
value = "US";
}
return value;
}
When I am writing JUnit for this, how do I mock the call for service.callMethod(input) and return HttpClientErrorException.NotFound
?
I tried mocking and sending the status code as below but it does not work.
Junit Test case method is as below:
@Test(expected = ApplicationException.class)
public void callServiceInvalidInput() throws ApplicationException
{
String inputValue = "JLR";
when(externalService.callMethod(inputValue))
.thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));
String result = handler.callService(inputValue);
}
When I mock the service call, the catch clause that gets executed is Exception e and not the previous one. The reason is object e is instanceof HttpClientErrorException when mocked; but when the actual service call happens, it is instance of HttpClientErrorException$NotFound
Upvotes: 3
Views: 7725
Reputation: 445
I found an answer when I tried to check how the NotFound is actually set.
when(externalService.callMethod(inputValue))
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "not found", null, null, null));
I called the create method to return that particular inner class.
Upvotes: 6