我想使用 @WebMvcTest 注释测试依赖于 1 个服务和 1 个存储库的单个 Controller 。整个应用程序中还有其他 5 个服务/存储库,我不想在这个单元测试中模拟它们。
我已经 mock 了所需的 2 个服务/存储库。在这里,我正在测试一个简单的端点,它甚至不访问存储库,但是当我尝试在 Spring Boot 中对该特定 Controller 进行单元测试时,如下所示
@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());
}
}
我明白
引起:org.springframework.beans.factory.BeanCreationException:创建名称为“restaurantRequestRepository”的bean时出错:设置bean时无法创建类型为[org.springframework.orm.jpa.SharedEntityManagerCreator]的内部bean“(inner bean)#60b4d934”属性“实体管理器”;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名称为“(inner bean)#60b4d934”的 bean 时出错:设置构造函数参数时无法解析对 bean“entityManagerFactory”的引用;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为“entityManagerFactory”的bean可用
注意:如果我使用@SpringBootTest,它可以工作,但我不想实例化整个应用程序来进行简单的测试。
最佳答案
我遇到了完全相同的问题。这是由于我的主 Spring 应用程序类上有 @EnableJpaRepositories
注释引起的。 webmvc 测试禁用完全自动配置,但仍必须加载基本应用程序类。
很容易修复,幸运的是,只需创建一个新的配置类并将您的 @EnableXRepository
注释移至该类,它们将不会包含在您的 webmvc 测试中!
@Configuration
@EnableJpaRepositories
class PersistenceConfiguration {}
关于unit-testing - 为什么单元测试尝试在 Spring Boot 中的 Controller 特定单元测试中查找其他 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44535371/