我希望使用特定的弹簧测试配置文件进行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 {
}
答案 0 :(得分:4)
使用@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 {
}