unit-testing - 为什么单元测试尝试在 Spring Boot 中的 Controller 特定单元测试中查找其他 bean

标签 unit-testing spring-mvc spring-boot mocking

我想使用 @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/

相关文章:

oop - 如何对非公共(public)逻辑进行​​单元测试

java - 如何在 Spring Batch Junit 测试中模拟编写器?

spring - 在多模块 Java-Config Spring MVC 应用程序中使用 @ComponentScan 的正确方法

java - 我应该在 Post 方法中设置哪个 IP 地址?

java - Gradle、Spring Boot、Maven 发布 - 发布仅包含依赖项和/或约束而没有版本

unit-testing - 无法导入 kotlin.test 以使用 assertFailsWith

c++ - 将线程逻辑与业务逻辑解耦?

java - Spring MVC 在 "/"上打开 index.jsp

Java - SpringMVC - 获取 Controller 中的参数

spring-boot - Spring Boot示例如何从服务器下载文件