Spring 注解 @WebMvcTest 在具有 Jpa 存储库的应用程序中不起作用

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

我有一个使用 JPA 存储库(CrudRepository 接口)的 Spring 应用程序。当我尝试使用新的 Spring 测试语法 @WebMvcTest(MyController.class) 测试我的控制器时,它失败了,因为它试图实例化我的一项服务 class 使用 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 结合使用,而不是使用此注释。

我遇到了同样的问题。使用 @SpringBootTest@AutoConfigureMockMvc 非常适合我。

我能够通过实施 junit 5 并使用 @SpringJUnitConfig@WebMvcTest 对 Rest Controller 进行单元测试。我正在使用 Spring Boot 2.4.5,这是我的示例:

@SpringJUnitConfig
@WebMvcTest(controllers = OrderController.class)
class OrderControllerTest {

    @Autowired
    private MockMvc mockMvc;

    // This is a Mock bean of a Spring Feign client that calls an external Rest Api
    @MockBean
    private LoginServiceClient loginServiceClient;

    // This is a Mock for a class which has several Spring Jpa repositories classes as dependencies
    @MockBean
    private OrderService orderService;

    @DisplayName("should create an order")
    @Test
    void createOrder() throws Exception {

        OrderEntity createdOrder = new OrderEntity("123")

        when(orderService.createOrder(any(Order.class))).thenReturn(createdOrder);

        mockMvc.perform(post("/api/v1/orders").contentType(MediaType.APPLICATION_JSON).content("{orderId:123}"))
            .andExpect(status().isCreated())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))TODO: here it will go the correlationId
            .andExpect(jsonPath("$.orderId").value("123"));
    }
}

请仅在实施集成测试时使用 @SpringBootTest