我有一个使用 JPA 存储库(CrudRepository
接口(interface))的 Spring 应用程序。当我尝试使用新的 Spring 测试语法 @WebMvcTest(MyController.class)
测试我的 Controller 时,它失败了,因为它试图实例化我的一个使用 JPA 存储库的服务类,有没有人知道如何解决这个问题?该应用程序在我运行时有效。
这是错误:
***************************
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.
最佳答案
根据文档
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).
此注解仅适用于 Spring MVC 组件。
如果您希望加载完整的应用程序配置并使用 MockMVC,您应该考虑
@SpringBootTest
结合 @AutoConfigureMockMvc
而不是这个注解。
关于Spring Annotation @WebMvcTest 在具有 Jpa 存储库的应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39950614/