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 full application context. Whereas @WebMvcTest annotation will make Spring Framework create application context with a limited number of beans(only those related to Web Layer).

You will use @SpringBootTest annotation to create integration tests that involve all three layers of your application (i.e. Web layer, Service layer, 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 Service or Data layer will need to be mocked.

@SpringBootTest Annotation

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

@WebMvcTest annotation will exclude classes annotated with @Component, @Service@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 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 absolute beginners and you do not need to have any 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!