首页 > 解决方案 > 如何通过跳过存储库类来使用 MockMvc 测试 Spring Boot 休息控制器?

问题描述

我正在尝试为 Controller 创建测试类,如下所示:请注意,我们已经为所有存储库和域创建了库(使用 Spring DATA JPA),并在 UserController 所在的实际应用程序中添加了依赖项。

@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserControllerTest {
    @MockBean
    private UserService userService;

    @Autowired
    private MockMvc mvc;

    @Test
    public void testGetUsers() throws Exception {
        when(userService.getAllUser()).thenReturn(new ArrayList<Organization>());
        mvc.perform(get("/users")).andExpect(status().isOk());
    }
}

当我试图运行这个类时,我得到了异常:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#4d41ba0f': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

如何通过跳过存储库类来使用 MockMvc 测试 Spring Boot 休息控制器?

标签: spring-bootspring-data-jpaspring-testspring-test-mvc

解决方案


你的问题是,你没有提供@AutowiredUserController班上的其他豆子。在@WebMvcTestbeans 中不经历标准的 spring 创建过程。

为了快速解决这个问题,只需提供其他 bean 来游览带有注释的测试类@MockBean

示例控制器类:

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    EntityManagerFactory entityManagerFactory;

    @Autowired
    AnotherSillyBean anotherSillyBean;

    ...
}

示例测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserController {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @MockBean
    EntityManagerFactory entityManagerFactory;

    @MockBean
    AnotherSillyBean anotherSillyBean;

    ...
}

推荐阅读