In this quick article, we will understand what is @SpringBootTest and @WebMvcTest annotations and the differences between them.
Before understanding the difference between @SpringBootTest and @WebMvcTest annotations, let's first take a look at a quick overview of these two annotations.
@SpringBootTest Annotation
- MOCK(Default): Loads a web ApplicationContext and provides a mock web environment.
- RANDOM_PORT: Loads a WebServerApplicationContext and provides a real web environment. The embedded server is started and listened to a random port. This is the one that should be used for the integration test.
- DEFINED_PORT: Loads a WebServerApplicationContext and provides a real web environment. NONE: Loads an ApplicationContext by using SpringApplication but does not provide any web environment.
@WebMvcTest Annotation
SpringBoot provides @WebMvcTest annotation to test Spring MVC Controllers. Also, @WebMvcTest based test run faster because it will load only the specified controller and its dependencies only without loading the entire application.
Spring Boot instantiates only the web layer rather than the whole application context. In an application with multiple controllers, you can even ask for only one to be instantiated by using, for example, @WebMvcTest(HomeController.class).
@SpringBootTest vs @WebMvcTest
1. @SpringBootTest annotation loads the full application context so that we can able to test various components. So basically, the @SpringBootTest annotation tells Spring Boot to look for the main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context.
@WebMvcTest annotation loads only the specified controller and its dependencies only without loading the entire application. For example, let's say you have multiple Spring MVC controllers in your Spring boot project - EmployeeController, UserController, LoginController, etc then we can use @WebMvcTest annotation to test only specific Spring MVC controllers without loading all the controllers and their dependencies.
2. Spring Boot provides @SpringBootTest annotation for Integration testing.
Spring boot provides @WebMvcTest annotation for testing Spring MVC controllers (Unit testing).
When to use @SpringBootTest and @WebMvcTest annotations?
- Use @SpringBoot Test annotation for Integration testing.
- Use @WebMvcTest annotation for Unit testing Spring MVC controller.
CRUD Examples for @SpringBootTest and @WebMvcTest annotations
Usage of @SpringBootTest annotation demonstrated in the below tutorial:
Spring Boot Integration Testing MySQL CRUD REST API Tutorial
Usage of @WebMvcTest annotation demonstrated in the below tutorial:
Spring Boot Unit Testing CRUD REST API with JUnit and Mockito
Comments
Post a Comment
Leave Comment