【问题标题】:spring boot tests - how to start embedded server before spring boot?spring boot 测试 - 如何在 spring boot 之前启动嵌入式服务器?
【发布时间】:2015-11-06 15:53:05
【问题描述】:

经常编写集成测试时,需要在临时端口上启动一些服务器(例如 redis、zookeeper),然后将该端口作为属性传递给 Spring。问题是实际使用的端口在服务器启动前是未知的,所以无法通过注解传递:

@IntegrationTest(["redis.port=???"])
class RedisTest {
    @Before
    before(){
       int port = startRedis(
    }
}

实现这一目标的惯用方法是什么?理想情况下,我想把它放到一个 junit 规则中。

这对我有用,但看起来不太好(通过静态变量传递端口):

@IntegrationTest(initializers=Initializer.class)
public class RedisTest {
    public static int port;

    public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        public void initialize(ConfigurableApplicationContext ctx){
            port = startRedis()
            EnvironmentTestUtils.addEnvironment(ctx, "redisPort=" + port)
        }
    }
}

【问题讨论】:

    标签: java spring spring-boot integration-testing


    【解决方案1】:
    //set server.port=0 and then inject the actual (‘local’) port as a @Value
    
    @WebIntegrationTest("server.port:0")    
    public class RedisTest{
    
        @Autowired
        EmbeddedWebApplicationContext server;
    
        @Value("${local.server.port}")
        int port;    
    
    } 
    

    http://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html#howto-discover-the-http-port-at-runtime

    【讨论】:

    • 与问题无关...我的问题与环境中的其他服务器有关,与Spring Boot中嵌入的http无关。
    猜你喜欢
    • 1970-01-01
    • 2019-02-18
    • 2019-10-11
    • 2018-07-12
    • 2018-10-09
    • 2021-07-18
    • 2021-05-18
    • 2017-09-20
    • 2021-03-15
    相关资源
    最近更新 更多