Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Annotation @WebMvcTest does not work in an app that has Jpa repositories

I have a Spring App that uses JPA repositories (CrudRepository interfaces). When I try to test my controller using the new Spring test syntax @WebMvcTest(MyController.class), it fails coz it tries to instantiate one of my service class that uses JPA Repository, does anyone has any clues on how to fix that? The app works when I run it.

Here is the error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.myapp.service.UserServiceImpl required a bean of type 'com.myapp.repository.UserRepository' that could not be found.

Action:

Consider defining a bean of type 'com.myapp.repository.UserRepository' in your configuration.
like image 504
dickyj Avatar asked Oct 10 '16 02:10

dickyj


1 Answers

According to the doc

Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).

This annotion only apply on the Spring MVC components.

If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than this annotation.

like image 175
Liping Huang Avatar answered Sep 19 '22 19:09

Liping Huang