- Is it right to use @SpringBootTest (or) @ContextConfiguration in Unit Test?
Starting spring for each test is a very expensive operation. It’s not a unit test anymore rather integration test. @SpringBootTest goes further and tries to mimic the processes added by Spring Boot framework for creating the context: Decides what to scan based on package structures, loads external configurations from predefined locations optionally runs autoconfiguration starters and so on and so forth. @SpringBootTest loads the necessary beans and inject into each other.
When using @ContextConfiguration you present way to filter what exactly should be run, what beans to load and to inject into each other. - How to Optimize the Unit test by selectively loading the resource?
You can selectively load the resource during unit test- To test your Respository : use @DataJpaTest annotation for test slice.
- To test your Service layer : use JUnit and Mockito. Here you will mock your Repository
- To test your Controller layer : use @WebMvcTest annotation for test slice or use JUnit and Mockito. Here you will mock your Service in both cases
- To test a Component, such as a third party library wrapper or load some specific beans: use @ExtendWith(SpringExtension.class) and @ContextConfiguration/@Import or @SpringJUnitWebConfig which is the combinaison of the both.
- To do an integration test : use @SpringBootTest
- When to use @SpringBootTest and @ExtendWith(SpringExtension.class)
Use @ExtendWith(SpringExtension.class) without loading the entire application context that is included with @SpringBootTest. As you say it’s a lighter weight approach if you just want to mock beans with @MockBean. @SpringBootTest does in fact include @ExtendWith(SpringExtension.class)Use @SpringBootTest when,
- You need to test the application as a whole, including multiple layers like the web layer, service layer, and repository layer.
- You require an embedded server to run the test, such as when testing web controllers.
- You want to verify the integration of all components in a fully loaded application context.
Use SpringRunner/@ExtendWith(SpringExtension.class) when,
- You are writing unit tests or lightweight integration tests that only need certain features of Spring, such as dependency injection or transaction management, without loading the full application context.
- You want to test specific layers (e.g., service layer) in isolation without the overhead of starting the entire Spring application.