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

查看:641
本文介绍了如何在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 to @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天全站免登陆