I am new to Spring Boot and am trying to understand how testing works in SpringBoot. I am a bit confused about what is the difference between the following two code snippets
@SpringBootTest annotation tells Spring Boot to go and look for a main configuration class (one with @SpringBootApplication for instance), and use that to start a Spring application context. SpringBootTest loads complete application and injects all the beans which can be slow.
@WebMvcTest - for testing the controller layer and you need to provide remaining dependencies required using Mock Objects.
Few more annotations below for your reference.
Testing slices of the application Sometimes you would like to test a simple “slice” of the application instead of auto-configuring the whole application. Spring Boot 1.4 introduces 4 new test annotations:
@WebMvcTest - for testing the controller layer
@JsonTest - for testing the JSON marshalling and unmarshalling
@DataJpaTest - for testing the repository layer
@RestClientTests - for testing REST clients
Refer for more information : https://spring.io/guides/gs/testing-web/
@SpringBootTest
is the general test annotation. If you're looking for something that does the same thing prior to 1.4, that's the one you should use. It does not use slicing at all which means it'll start your full application context and not customize component scanning at all.
@WebMvcTest
is only going to scan the controller you've defined and the MVC infrastructure. That's it. So if your controller has some dependency to other beans from your service layer, the test won't start until you either load that config yourself or provide a mock for it. This is much faster as we only load a tiny portion of your app. This annotation uses slicing.
Reading the doc should probably help you as well.
MVC tests are intended to cover just the controller piece of your application.
HTTP requests and responses are mocked so the real connections are not
created. On the other hand, when you use @SpringBootTest
, all the
configuration for the web application context is loaded and the connections
are going through the real web server. In that case, you don’t use the
MockMvc
bean but a standard RestTemplate
instead (or the new alternative
TestRestTemplate
).
So, when should we choose one or the other? @WebMvcTest
is intended to
test unitarily the controller from the server side. @SpringBootTest
, on the
other hand, should be used for integration tests, when you want to interact
with the application from the client side.
That doesn’t mean that you can’t use mocks with @SpringBootTest
; if
you’re writing an integration test, that could still be necessary. In any case,
it’s better not to use it just for a simple controller’s unit test.
source - Learning Microservices with Spring Boot