如何在 SpringBootTest 的 @DataJpaTest 中导入配置类? [英] How do I import configuration classes in a @DataJpaTest in a SpringBootTest?

查看:22
本文介绍了如何在 SpringBootTest 的 @DataJpaTest 中导入配置类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SpringBoot 应用程序,我有一个配置包

I have a SpringBoot Application and I a config package with

@Configuration
@EnableJpaAuditing
public class PersistenceConfig {
}

但是 PersistenceConfig 不会在 PersonRepositoryTest

@RunWith( SpringRunner.class )
@DataJpaTest
public class PersonRepositoryTest {

    // Tests ...
}

但是,如果我从 @DataJpaTest 更改为 @SpringBootTest,PersonRepositoryTest 将获取配置.

However, if I change from @DataJpaTest to @SpringBootTest, PersonRepositoryTest will pick up the config.

我的包结构

- main
    - java
        - config
              PersistenceConfig.java
        - domain
              Person.java
        - persistence
              PersonRepository.java
          Application.java // @SpringBootApplication

- test
    - java
        - persistence
              PersonRepositoryTest.java

Spring Boot 中的测试改进1.4建议用@DataJpaTest测试持久层

The Testing improvements in Spring Boot 1.4 suggest to test the persistence layer with @DataJpaTest

观察:在 Test 类上做这两个注释仍然不导入配置@SpringBootTest@DataJpaTest

Observation: Doing both annotations on the Test class still do not import the config @SpringBootTest @DataJpaTest

问题 1:使用@DataJpaTest 测试持久层时我如何正确(Spring Boot 中的最佳实践方式)将配置包导入到我的测试中?

Question 1: When testing the Persistence Layer with @DataJpaTest how do I properly (best practise way in Spring Boot) import the config package into my Tests?

问题 2:使用@SpringBootTest 是否可以接受?我知道@DataJpaTest 也是一个元注释,为我的数据库(包括事务管理)提供合理的自动配置.但是如果我不需要它呢?

Question 2: Can it be an acceptable work around using @SpringBootTest? I am aware that @DataJpaTest is also a meta annotation with sensible auto configuration for my database including transaction management. But what If I do not need it?

推荐答案

解决方案是使用 @Import 将您的配置导入到由 @DataJpaTest 完成的配置中.这是我对@Import的理解.

A solution is to use @Import to import your configuration to the configuration done by @DataJpaTest. This is my understanding of @Import.

@RunWith(SpringRunner.class)
@DataJpaTest
@Import(AuditConfiguration.class)
public class AuditTest {
}

带有启用审计的AuditConfiguration

@Configuration
@EnableJpaAuditing
public class AuditConfiguration {
}

这篇关于如何在 SpringBootTest 的 @DataJpaTest 中导入配置类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆