2
votes

does anybody know why the Spring Boot Guide includes two different types of integration tests? (https://github.com/spring-guides/gs-spring-boot#add-unit-tests)

One with TestRestTemplate and one with MockMvc dependency? In each test type spring boot bootstraps the test environment. So what is the reason for this separation?

1

1 Answers

6
votes

When you use MockMvc you are testing an instance of your application in which the HTTP request cycle has been mocked. So, the test scope here is just the MVC aspects of your application. I don't think this would be typically labelled an "integration test", instead it is closer to a unit test (albeit its scope is considerably larger than a single class).

When you use TestRestTemplate you are testing a real instance of your application i.e. you are 'springing up' an entire application context and invoking it as an external actor. This is typically referred to as an "integration test" and it is likely to be the closest test to your actual usage.

Now, since a 'full stack' integration test invoked via TestRestTemplate can provide a superset of the coverage provided by a MockMVC test you might be wondering why you would bother with a MockMVC test. If so, then I think this is a question of ...

  • Test scope; MockMVC test cases are typically quicker and easier to fire up (since they use less of your application context) than a full integration test. In addition, since they use less of your appolication context you may not have to work as hard to mock out any aspects of your real application context which don't play well in a test.

  • Ease of use; MockMVC comes with static helpers for asserting HTTP status, interrogating and asserting against JSON responses etc. Of course YMMMV but for many people these faciliate an ease of development and help deliver readable test cases.

In practice, you'll perhaps want to use a combination of both approaches:

  • MockMVC tests for detailed testing of the entire controller layer including all mappings, happy and sad paths for all invocations and deep assertions on HTTP status codes, content bodies etc
  • TestRestTemplate tests for the main flows expressed from the users perspective e.g. Save a new Foo, Search for all Foos, Submit an invalid Foo update etc with assertions focussing on the bits which your users see/are interested in.