我有一个应用程序配置类

@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)为什么与没有注释完全不同的任何想法?

最佳答案

代替@ContextConfiguration,您应该:


@TestConfiguration注释您的测试配置
sessionFactory()标记您的@Primary方法,以确保在生产配置中选择了测试bean。

10-07 16:56