Difference Between @SpringBootTest and @WebMvcTest

In this blog post, you will learn the difference between @SpringBootTest and @WebMvcTest annotations.

The main difference between @SpringBootTest and @WebMvcTest annotations is that @SpringBootTest annotation will start the full application context. Whereas @WebMvcTest annotation will make Spring Framework create application context with a limited number of beans(only those related to the Web Layer).

You will use @SpringBootTest annotation to create integration tests that involve all three layers of your application (i.e. Web, Service, and Data layer). And you will use @WebMvcTest annotation when you need to create integration tests or unit tests of the Web MVC Layer only (i.e. controllers). Because when using @WebMvcTest annotation dependencies on the Service or Data layer will need to be mocked.

@SpringBootTest Annotation

@SpringBootTest annotation will make Spring Framework scan your application’s three layers(Web layer, Service layer, and Data layer). By default, Spring Framework will start scanning your application classes from the root package. Those classes annotated with annotations like @Component, @Repository, @Service, and @Controller will be converted into Beans and placed into the application context.

@WebMvcTest annotation will exclude classes annotated with @Component, @Service, and @Repository and will not create Beans for them.

@WebMvcTest Annotation

The @WebMvcTest annotation will make Spring Framework scan the controller classes and classes related to MVC infrastructure only (i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver). Classes annotated with @Component, @Service or @Repository will be skipped.

You will use @WebMvcTest annotation to test the Web Layer only.

Also, you can use @WebMvcTest annotation to specify which Controllers to scan. In this case, Spring Framework will scan only specified Controllers.

@WebMvcTest(controllers = UsersController.class)
class UsersControllerTest {
  // Some code

Also, if your controller class has a dependency on a @Service or a @Repository object, then you will need to mock this dependency using @MockBean annotation.

Video Lessons

I hope this tutorial was helpful to you. If you like learning by watching a series of step-by-step video lessons then have a look at my video course called “Testing Java with JUnit and Mockito“. This video course is for beginners, and you do not need to have prior knowledge of testing Java applications to enrol. Otherwise, there are many other useful tutorials you will find in the JUnit category of this site.

Happy learning!