【问题标题】:BeanCreationNotAllowedException after junit test in spring-boot projectspring-boot项目中junit测试后的BeanCreationNotAllowedException
【发布时间】:2018-04-06 08:07:28
【问题描述】:

我有一个 Spring Boot 项目。
可以成功启动。
我添加了一个这样的测试:

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SopStart.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class Test{
    @Test
    public void test(){
        System.out.println("success!");
    }
}

“成功!”可以打印成功。但最后我得到了一个例外:

2017-10-25 17:00:42.481  INFO [bootstrap,,,] 7280 --- [      Thread-15] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@758d0555: startup date [Wed Oct 25 17:00:09 CST 2017]; parent: org.springframework.web.context.support.GenericWebApplicationContext@75d4a80f
2017-10-25 17:00:42.492  WARN [bootstrap,,,] 7280 --- [      Thread-15] s.c.a.AnnotationConfigApplicationContext : Exception thrown from ApplicationListener handling ContextClosedEvent

org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'eurekaAutoServiceRegistration': Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:216)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    ...

【问题讨论】:

    标签: java spring-boot junit spring-cloud


    【解决方案1】:

    它使用默认的Application 类。尝试为排除某些自动配置的bean(包括EurekaClientAutoConfiguration)的测试类定义您赢得的配置,这是您的测试抱怨的主要原因。

    您可能也不需要@WebAppConfiguration。您甚至可能会收到java.lang.IllegalStateException

    这是一个例子,

    @ActiveProfiles("test")
    //@WebAppConfiguration
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = TestExample.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @ContextConfiguration(classes = {Test.CustomConfiguration.class})
    public class Test {
    
        @Configuration
        @EnableConfigurationProperties
        @EnableAutoConfiguration(exclude = {HibernateJpaAutoConfiguration.class,
                JpaRepositoriesAutoConfiguration.class,
                DataSourceAutoConfiguration.class,  
                EurekaClientAutoConfiguration.class})
        static class CustomConfiguration {
    
        }
    
        @Test
        public void test() {
            System.out.println("success!");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 2019-10-26
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      相关资源
      最近更新 更多