I have a SpringBoot MVC application, and I want to cover it with tests.
I have the controller, service and repository layers.
What is the best practice to cover the application by tests?
Why do people use @SpringBootTest
while it seems it could be tested by layers by @WebMvcTest
& @DataJpaTest
and service unit tests? It is faster and more granular, isn't it?
AFAIK when @SpringBootTest
is used it is called Integration tests, so does it mean it shouldn't appear too often?
I suppose that every chunk of code should be unit test covered, is it the same for integration covered? Or should integration tests work on stage environment but not on test environment?
Isn't it the same (in terms of performance) if I create a @SpringBootTest
but mock other layers? (Suppose I create multiple @SpringBootTest
s and mock other layers).
@SpringBootTest
loads full application context, exactly like how you start a Spring container when you run your Spring Boot application.
@WebMvcTest
loads only the web layer, which includes security, filter, interceptors, etc for handling request/response. Typically you would write tests for methods under @Controller
or @RestController
.
@DataJpaTest
loads only configuration for JPA. It uses an embedded in-memory h2 if not specified otherwise.
Service layer tests should ideally not have any annotations (except for ones that aid in mocking) because this is where your business logic (independent of any configurations) sits.
Regarding best practice, it's really just separation of concerns. I rarely ever used @SpringBootTest
unless it's meant for some ad-hoc integration test on my local. Annotations like @WebMvcTest
keep your tests more 'modularized' and slightly faster.