【问题标题】:@DataJpaTest stops working with @Profile annotation@DataJpaTest 停止使用 @Profile 注释
【发布时间】:2017-01-23 13:24:37
【问题描述】:

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

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

    @Autowired
    private TestEntityManager testEntityManager;
    ...
    @Autowired
    private MyJpaRepository myJpaRepository;
}

失败并出现以下错误:

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

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

UPD 这是我的MyJpaConfig

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

【问题讨论】:

  • 可以发布你的spring配置吗?
  • @AngeloImmediate 添加。其他配置无所谓。可能是空的

标签: spring spring-boot spring-data-jpa spring-test


【解决方案1】:

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

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

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

我想这一切的目的是让TestingConfig 仅在运行单元测试时启用?这里需要添加@Profile注解:

@Configuration
@Profile("myTestProfile")
public class TestingConfig {
}

【讨论】:

  • 是的,我的测试配置看起来像你写的。现在它起作用了!我只是使用了错误的注释。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-01-07
  • 2013-03-07
  • 2019-12-12
  • 2021-11-15
  • 2015-09-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
相关资源
最近更新 更多