@DataJpaTest 停止使用 @Profile 注释

Igo*_*nko 0 spring spring-test spring-data-jpa spring-boot

我想使用特定的弹簧测试配置文件进行 JPA 测试。但不知何故,它无法加载弹簧上下文。

@RunWith(SpringRunner.class)
@Profile("myTestProfile")
@DataJpaTest
@ContextConfiguration(classes = {TestingConfig.class, MyJpaConfig.class})
public class JpaPlusOtherStuffTest {

    @Autowired
    private TestEntityManager testEntityManager;
    ...
    @Autowired
    private MyJpaRepository myJpaRepository;
}
Run Code Online (Sandbox Code Playgroud)

失败并出现以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'myJpaRepository': 
Cannot create inner bean '(inner bean)#5e77f0f4' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; 
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#5e77f0f4': 
Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No bean named 'entityManagerFactory' is defined
Run Code Online (Sandbox Code Playgroud)

如果我删除@Profile注释,则测试工作正常。我只是不明白如何无法@DataJpaTest运行附加配置文件。也许有人可以向我解释这一点?

UPD 这是我的MyJpaConfig

@Configuration
@EnableJpaAuditing
@EnableJpaRepositories("com.mycompany.project.jpa")
@EnableTransactionManagement(proxyTargetClass = true)
public class MyJpaConfig {
}
Run Code Online (Sandbox Code Playgroud)

ale*_*xbt 5

using将继承的 Configuration@Profile 标记DataJpaTest配置文件的一部分myTestProfile。但是,您没有激活任何配置文件,因此DataJpaTest被忽略。

要激活配置文件,您需要使用@ActiveProfile

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("myTestProfile")
@ContextConfiguration(classes = {TestingConfig.class, MyJpaConfig.class})
public class JpaPlusOtherStuffTest {
}
Run Code Online (Sandbox Code Playgroud)

我想这一切的目的是TestingConfig只在运行单元测试时启用?这是您需要添加@Profile注释的地方:

@Configuration
@Profile("myTestProfile")
public class TestingConfig {
}
Run Code Online (Sandbox Code Playgroud)