使用@DataJpaTest 进行集成测试

Integration Testing With @DataJpaTest

我的项目中有这个测试:

@DataJpaTest
@SpringBootTest
@TestPropertySource(locations = "classpath:local-configuration.properties")
public class CanPixaRepositoryTest  {

    @Autowired
    private CanPixaRepository canPixaRepository;

    public void setUp() throws Exception {
    }

    @Test
    public void testAll() {
        canPixaRepository].getAvui("fqs");
    }
}

本地-configuration.properties:

spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=

但是我运行测试的时候,canPixaRepositoryRepository为null

@SpringBootTest 注释用于设置整个应用程序上下文,而 @DataJpaTest 将设置应用程序上下文以便您可以测试与 jpa 相关的代码,它将设置您的应用程序上下文的一部分对于这个特定的用例。所以不需要将 @SpringBootTest 注释与 @DataJpaTest 一起使用,像这样使用它:

@ExtendWith(SpringExtension.class)
@DataJpaTest
@TestPropertySource(locations = "classpath:local-configuration.properties")
public class CanPixaRepositoryTest  {

    @Autowired
    private CanPixaRepository canPixaRepository;

    public void setUp() throws Exception {
    }

    @Test
    public void testAll() {
        canPixaRepository.getAvui("fqs");
    }
}

从 SpringBoot 2.1 开始,您不必提供 @ExtendWith 注释来告诉 Junit 启用 spring 支持,因为它已经提供了 @SpringBootTest@DataJpaTest.

对于 Spring 引导应用程序,如果您使用的是 JPA 和 Spring Data JPA,最简单的方法是使用带有 H2 的 @DataJpaTest 来测试您的存储库。

  1. 将 h2 依赖项添加到您的测试范围。 Spring Boot 将auto-configure 它并在测试阶段使用它来替换运行时数据源。
  2. @DataJpaTest 注释您的测试。然后 EntityManager、您的存储库和 test-purpose TestEntityManager 在 Spring 应用程序上下文中可用。

检查my example here

(Spring 5/Spring Boot 2 添加了 Junit 5 支持,如果您使用的是 Junit 5 集成,则不需要 @Runwith@Extendwith, DataJpaTest本身是一个meta-annotation,在Spring 2.4之前,要启用Junit5,你必须从spring-boot-test中排除JUnit 4,然后手动添加JUnit 5。在即将到来的Spring Boot 2.4中, JUnit 5 是默认的测试运行器)