Spring Boot and MockServer with GET 'body' lead to different result with test env and actual app run

40 Views Asked by At

Well I have JUnit 5 test which do API checking, and client which has common code like this

ResponseEntity<T> responseEntity = restTemplate.exchange(url, method, httpEntity, clazz);

but with GET method httpEntity must not contain body, only headers. And I thought it will be ignored, but in reality it throw an exception

java.lang.IllegalArgumentException: method GET must not have a request body. at okhttp3.Request$Builder.method(Request.kt:258)

Which is ok, but none of my test with

var mockServer = MockRestServiceServer.createServer(restTemplate);

can catch it. In fact tests are working just fine, but fail with real request. I believe this is because no real underlined client has used. But how I can be sure that I can test whole stack? It's probably really corner case, but still exists.

1

There are 1 best solutions below

0
johyunkim On

The problem is that MockRestServiceServer doesn't perform HTTP requests over the network. It only mocks the behavior of RestTemplate, so this is why your tests are passing.

If you want to test the whole stack, I'll suggest these 2 things.

0. TestRestTemplate

It behaves more like a real RestTemplate in a full Spring application context, making real HTTP requests.

1. Integration Testing

Use @SpringBootTest and send real HTTP requests while testing! This will ensure that the entire stack, including the HTTP client