use*_*132 2 unit-testing mocking spring-mvc spring-boot
我想使用 @WebMvcTest 注释测试依赖于 1 个服务和 1 个存储库的单个控制器。整个应用程序中还有其他 5 个服务/存储库,我不想在这个单元测试中模拟它们。
我已经嘲笑了所需的 2 个服务/存储库。在这里,我正在测试一个简单的端点,它甚至不访问存储库,但是当我尝试在 Spring Boot 中对该特定控制器进行单元测试时,如下所示
@RunWith(SpringRunner.class)
@WebMvcTest(WebController.class)
public class LoginTest {
@MockBean
private CustomerRepository customerRepository;
@MockBean
private CustomerService customerService;
private MockMvc mockMvc;
@Test
public void serverRunning() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(content().string("Server is running"))
.andDo(print());
}
}
Run Code Online (Sandbox Code Playgroud)
我明白了
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restaurantRequestRepository': Cannot create inner bean '(inner bean)#60b4d934' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#60b4d934': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
注意:如果我使用@SpringBootTest,它可以工作,但我不想实例化整个应用程序以进行简单的测试。
我遇到了完全相同的问题。这是由于@EnableJpaRepositories我的主 Spring 应用程序类上有注释引起的。webmvc 测试禁用完全自动配置,但仍必须加载基本应用程序类。
幸运的是,修复很简单,只需创建一个新的配置类并将@EnableXRepository注释移至该类,它们就不会包含在您的 webmvc 测试中!
@Configuration
@EnableJpaRepositories
class PersistenceConfiguration {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1019 次 |
| 最近记录: |