首页 > 解决方案 > 使用 @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");
    }
}

本地配置.properties:

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

但是当我运行测试时, canPixaRepositoryRepository 为空

标签: spring-bootjpajunitspring-data-jpaspring-data

解决方案


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

  1. 将 h2 依赖项添加到您的测试范围中。Spring Boot 将自动配置它并在测试阶段使用它来替换运行时 DataSource。
  2. 用 注释您的测试@DataJpaTest。然后EntityManager,您的存储库和测试目的TestEntityManager在 Spring 应用程序上下文中可用。

在这里查看我的示例

(Spring 5/Spring Boot 2 添加了 Junit 5 支持,它不需要,@Runwith或者@Extendwith如果您正在使用 Junit 5 集成,DataJpaTest 本身是一个元注释,在 Spring 2.4 之前,要启用 Junit5,您必须从其中排除 JUnit 4 spring-boot-test 并手动添加 JUnit 5。在即将发布的 Spring Boot 2.4 中,JUnit 5 是默认的测试运行器)


推荐阅读