我有一个应用程序配置类
@Configuration
@EnableScheduling
public class AppConfig {
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
}
我正在进行测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:test.properties")
public class CollectiveOneWebappApplicationTests {
@Test
public void testDecisionAlgorithm() throws IOException {
...
}
工作正常。现在我想更改测试的configuartion类,所以我创建了
public class TestConfig {
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
}
并将测试更新为
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:test.properties")
@ContextConfiguration(classes = TestConfig.class)
public class CollectiveOneWebappApplicationTests {
@Test
public void testDecisionAlgorithm() throws IOException {
...
}
但它不起作用。它无法找到Hibernate实体工厂的bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory]
我想了一下,使用
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@TestPropertySource(locations="classpath:test.properties")
@ContextConfiguration(classes = AppConfig.class)
public class CollectiveOneWebappApplicationTests {
@Test
public void testDecisionAlgorithm() throws IOException {
...
}
会让我回到默认行为,但事实并非如此。关于为什么@ContextConfiguration(classes = AppConfig.class)
与没有注释完全不同的任何想法?
答案 0 :(得分:0)
而不是@ContextConfiguration
你应该:
@TestConfiguration
sessionFactory()
标记@Primary
方法,以确保在生产配置中选择了测试bean。