spring 启动集成测试 - 数据库未使用 @WebMvcTest 自动装配

spring boot integration test - database not autowired with @WebMvcTest

我有这个 sprig boot(版本 1.5.6)应用程序,它使用以下内容:

现在,我正在为此应用程序创建单元测试。在一个测试用例中,我有以下注释:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "spring.cloud.enabled=false" })

该测试正确初始化了 jpa 存储库,我能够对其进行测试。

然后我有另一个带有以下注释的测试:

@RunWith(SpringRunner.class)
@WebMvcTest(MyRestController.class)

此测试设置 Mockmvc,但不初始化 JPA 存储库。它只初始化配置的 MVC 部分。但我也需要初始化 JPA 存储库。我使用 data.sql 文件设置了测试数据,该文件作为内存中的 H2 数据库加载。我得到的错误是:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

我试过很多东西都没有成功:

我在上下文初始化时确实看到了以下内容:

.s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!

既然 spring 能够在第一次测试中自动装配 jpa 存储库并且它在应用程序中运行良好,我认为它也应该能够在 webMvc 测试用例中自动装配存储库。

我可以创建一个配置文件并在测试包中初始化实体管理器、数据源等,但是如果有一种方法可以使用 spring 进行自动装配,那么我不想管理它配置。

求推荐。

我看到你有 @WebMvcTest 注释。那个特定的是为了只测试 web 层,它不会加载整个应用程序上下文,只加载 web 上下文。您可能需要切换到 @SpringBootTest@AutoConfigureMockMvc 来测试整个堆栈。

使用 Spring Boot 进行 JPA 测试的方式是使用 @DataJpaTest 注释。它会自动配置所有内容,前提是您在类路径中有一个内存数据库(如果您使用 Maven,请确保它在 "testing" 范围内)。它还提供 TestEntityManager,这是 JPA 的 EntityManager 接口的实现,具有一些有用的测试功能。

示例:

@RunWith(SpringRunner.class)
@DataJpaTest
pubic class EntityTest {
    @Autowired TestEntityManager entityManager;

    @Test
    public void saveShouldPersistData() throws Exception {
        User saved = entityManager.persistFlushFind(new User("username", "password"));
        assertNonNull(saved);
    }
}

并且在您的 pom.xml 中您可以添加 H2 数据库(Spring Boot 也可以自动配置 Derby 和 HSQLDB)

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>test</scope>
</dependency>