如何防止弹簧在测试中影响其背景

时间:2017-08-13 18:26:14

标签: java spring-cloud spring-cloud-netflix spring-cloud-config

我在运行测试时遇到问题,因为在某个时刻,spring会重新加载上下文,再次搜索config-server设置,我注意到它总是在第二条消息后重新加载:

2017-08-13 15:05:54.411  INFO [payment,,,] 3360 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@76c548f: startup date [Sun Aug 13 15:05:54 BRT 2017]; root of context hierarchy
2017-08-13 15:05:54.681  INFO [payment,,,] 3360 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$719706d0] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

在执行40次测试期间,此消息显示4次,使弹簧重新加载上下文4次。我使用Spring Cloud生态系统(Config,Hystrix)有没有人知道它是什么?

事实上,我还想知道是什么导致spring重新加载上下文

注意:我不使用@DirtiesContext

4 个答案:

答案 0 :(得分:0)

  

事实上,我还想知道是什么导致spring重新加载上下文

默认情况下,Spring Test会自动在每个测试类上启动新上下文。我假设它被重新加载了4次,因为你有4个测试类。

答案 1 :(得分:0)

我的测试总是扩展到PaymentApplicationTests类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PaymentApplication.class, 
    properties = { "spring.cloud.config.enabled:true", "management.security.enabled=false"})
@RabbitListenerTest
@Transactional
@ActiveProfiles("test")
public abstract class PaymentApplicationTests {

    public static final String JSON_MEDIA_TYPE = "application/json;charset=UTF-8";

    @Autowired
    protected EntityManager em;

    protected MockMvc mockMvc;

    @Autowired
    protected WebApplicationContext wac;

    @SpyBean
    protected DomainEventPublisher domainEventPublisher;

    @Autowired
    public RabbitListenerTestHarness harness;

    public static EmbeddedAMQPBroker broker;

    @BeforeClass
    public static void startBroker() throws Exception {
        if (broker == null) {
            broker = new EmbeddedAMQPBroker();
            int port = broker.port();
            System.setProperty("spring.rabbitmq.port", String.valueOf(port));
        }
    }
}

答案 2 :(得分:0)

添加如下所示的抽象类:

package <package>;

import com.realty.project.AbstractTestController;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(locations = "classpath:/application-test.properties")
public abstract class AbstractTestApplication {
}

在测试类中继承此类,这将停止在每个测试类中创建上下文。这样可以确保不重新加载spring上下文的原因是所有测试类共享相同的上下文。如果你在每个类的顶部都有注释@SpringBootTest,那么spring必须一次又一次地重新创建上下文。

此处解释了更多上下文:http://www.nurkiewicz.com/2010/12/speeding-up-spring-integration-tests.html

答案 3 :(得分:0)

我发现了问题,它是@ MockBean的使用,它强制spring在每个使用它的类中重新加载上下文。这是小费。