【问题标题】:How to test spring Boot rest controllers with MockMvc by skipping repository classes?如何通过跳过存储库类来使用 MockMvc 测试 Spring Boot 休息控制器?
【发布时间】:2018-11-23 06:45:27
【问题描述】:

我正在尝试为 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 rest 控制器?

【问题讨论】:

  • 我理解错误你的问题。我将删除我的问题。您在实体管理器配置上遇到了某种问题。你的 pom.xml 上有 spring-boot-starter-data-jpa 吗?
  • 是的。问题是当我运行特定的测试类时,它会扫描@SpringBootApplication 中提到的所有组件。如何克服那个?
  • 您是否为 entityManagerFactory 尝试了一些 @MockBean ???。或者使用debug=true 属性运行测试,查找并禁用不必要的自动配置bean - 例如JpaRepositoriesAutoConfiguration

标签: spring-boot spring-data-jpa spring-test spring-test-mvc


【解决方案1】:

您的问题是,您没有在 UserController 类中提供其他 bean,它们是 @Autowired。在@WebMvcTest 中,bean 不经过标准的 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;

    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2014-05-31
    • 2019-02-01
    • 2018-10-17
    相关资源
    最近更新 更多