spring-boot - 如何通过跳过存储库类来使用 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 休息控制器?
解决方案
你的问题是,你没有提供@Autowired
你UserController
班上的其他豆子。在@WebMvcTest
beans 中不经历标准的 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;
...
}
推荐阅读
- c++ - Make在Boost中找不到.hpp文件
- r - 如何合并重复项
- java - 为什么 Eureka registry evict-task 运行如此缓慢?
- c# - 具有 jwt 令牌和 Azure AD 身份验证的 Blazor WASM 应用
- java - 在 Retrofit 中使用 Get 方法时获取 gson 时出错
- google-cloud-platform - 如何在大查询中在现有表上创建分区和集群?
- python - 如何在带有额外字段的 Tortoise ORM 中实现多对多模型?
- search - SwiftUI - 单击取消时执行操作 - .searchable 函数
- python - 更改 chrome 选项时保持浏览器窗口打开(Selenium Python)
- python - `git filter-repo` 命令在 Windows 上不输出任何内容