0

I'm using org.springiframework.web.client.RestTemplate For some Java tests to write unit tests for some new code. I expect these calls to fail (I'm testing authentication.)

Instead of returning a 401 code which is expected, or even a 500 code, the call throws an exception org.springiframework.web.client.HttpServerErrorException$InternalServerError.

Here's the call:

try {
    e  = restTemplate.exchange("https://myserver.local:8090/findByThread/100000", HttpMethod.GET, new HttpEntity(headers), Map.class, 100000L);
    assertNotEquals(200, e.getStatusCode().value());
} catch(Exception ex) {
    logger.info("Error");
    ex.printStackTrace();
}

I suspect I'm missing something completely obvious, but I don't know what it is. Shouldn't this simply return a EntityResponse with a statusCode=401?

user1071914
  • 3,155
  • 10
  • 46
  • 75
  • Perhaps being pedantic here but if you are testing authentication, you should expect only 401 (definitely not 500 as it does not indicate authentication failed or succeeded) – blurfus Jun 02 '22 at 15:11
  • @blurfus True, 401 was the expected response but I'm getting 500. I probably should edit the question to reflect that. Thanks! – user1071914 Jun 02 '22 at 15:15
  • internal server error would mean 500 to me. This seems correct. I'd run the service locally if i could and set a breakpoint to see where the server error happens. – duffymo Jun 02 '22 at 15:17
  • As per the [`RestTemplate`'s documentation](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#exchange-java.lang.String-org.springframework.http.HttpMethod-org.springframework.http.HttpEntity-java.lang.Class-java.lang.Object...-) throwing an exception is the standard for error cases. See also [`RestClientException`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestClientException.html). – Seelenvirtuose Jun 02 '22 at 15:18
  • can you test the endpoint manually (with Postman or similar) to ensure the endpoint is working as expected? I am afraid there could be something else at play. – blurfus Jun 02 '22 at 15:26

1 Answers1

0

I actually found a solution here: How do I retrieve HTTP status code and response body when an RestClientException is thrown?

Apparently throwing an exception instead of returning a response the "regular way" is just the way it works. I didn't understand that. By catching HttpClientErrorException and looking at the field rawStatusCode I was able to determine that I was getting the 401 as expected.

Thank you everyone for your help with this, your quick responses were invaluable. StackOverflow is a great resource.

user1071914
  • 3,155
  • 10
  • 46
  • 75