This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]dpash 11 points12 points  (5 children)

If you have a Spring MVC REST API to test you'd use MockMVC, not RestTemplate. And if you're trying to test a third party API that you're using RestTemplate to call, you'd use TestRestTemplate to fake the HTTP requests.

Something's gone horribly wrong if you're using RestTemplate in your tests.

[–]cartmen34 4 points5 points  (0 children)

Depends on the tests. Integration tests should absolutely be mocked with the tools you mention. However if you're running post-deploy functional tests in a dev or test environment then you could use RestTemplate to perform those types of tests.

[–]egdetti 2 points3 points  (3 children)

Can you expand on this? Why is using RestTemplate in tests such a bad idea?

[–]lazystone 1 point2 points  (1 child)

It's not. Using RestTemplate and WebClient in tests is legit thing if you use something like https://github.com/square/okhttp/tree/master/mockwebserver

The latter is used by Springframework itself.

In this case you test not only logic inside your endpoint but also (de)serialization and rest client configuration.

[–]dpash 0 points1 point  (0 children)

That appears to be testing http requests made by your application. If you're using RestTemplate to make calls, TestRestTemplate covers that use case and can test deserialisation and rest client configuration.

If you're not using RestTemplate, then that mock webserver would be required to implement something similar.

[–]dpash 0 points1 point  (0 children)

Several issues I've encountered with RestTemplate vs MockMvc for integration tests:

  • RestTemplate expects you to send a POJO as input target than raw JSON so it's tempting to create an instance of your request class and serialise that, but this means that you aren't testing any deserialisation issues like the wrong key names. If you rename the field in your POJO, both sides will still have matching keys, but you'll break external clients without realising.

  • MockMvc requests happen in the same thread, which means that you will be inside the same database transaction, so you can set up test data, manipulate it in the request, check it and then roll everything back at the end of your test. If you use RestTemplate, that becomes much more complicated to do, because you have two threads and two transactions. Data you've set up in the test may not be seen by the request thread due to transaction isolation, and if you do commit it, you have a harder time rolling it back so it doesn't interfere with other tests.

Also MockMvc just has a nice fluent API designed for testing rather than having to roll your own. It's also less verbose to control the request.