【问题标题】:Integration Testing With @DataJpaTest使用 @DataJpaTest 进行集成测试
【发布时间】:2021-02-03 02:15:52
【问题描述】:

我的项目中有这个测试:

@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-boot jpa junit spring-data-jpa spring-data


    【解决方案1】:

    @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 开始,您不必提供 @ExtendWithannotation 来告诉 Junit 启用 spring 支持,因为它已经提供了诸如 @SpringBootTest@DataJpaTest 之类的注释。

    【讨论】:

      【解决方案2】:

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

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

      检查my example here

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

      【讨论】:

        猜你喜欢
        • 2013-04-07
        • 2019-12-17
        • 2015-12-28
        • 2020-05-26
        • 2018-01-02
        • 2015-06-14
        • 2018-12-23
        • 2013-01-17
        • 2020-02-17
        相关资源
        最近更新 更多