Spring Boot Integration测试随机自由端口

时间:2016-08-16 14:30:55

标签: java spring spring-boot integration-testing spring-test

我能够获得Spring Boot集成以生成随机自由端口以启动自身。但我还需要Redis的免费端口。

@ContextConfiguration(classes = {MyApplication.class}, loader = SpringApplicationContextLoader.class)
@WebIntegrationTest(randomPort = true, value = "server.port:0")
@ActiveProfiles(profiles = {"local"})
public class SegmentSteps {

    private static final String HOST_TEMPLATE = "http://localhost:%s";

    // Needs to be a random open port
    private static final int REDIS_PORT = 6380;

    private String host;
    @Value("${local.server.port}")
    private int serverPort;

    private RedisServer redisServer;

    @Before
    public void beforeScenario() throws Exception {
        host = String.format(HOST_TEMPLATE, serverPort);
        redisServer = RedisServer.builder()
                .redisExecProvider(RedisExecProvider.defaultProvider())
                .port(REDIS_PORT)
                .setting("bind 127.0.0.1")
                .build();
        redisServer.start();
    }

    ...
}

关于如何实现这一目标的任何想法?

2 个答案:

答案 0 :(得分:13)

您可以使用Spring Framework的SocketUtils获取可用端口:

int redisPort = SocketUtils.findAvailableTcpPort();

答案 1 :(得分:0)

您也可以使用您选择的Java客户端或利用Overcast在Docker中运行Redis。如果使用Overcast,通过激活public class IntegrationTestBootstrapApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered { public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 4; public static final int PROPERTY_SOURCE_NAME = "integrationTestProps"; private int order = DEFAULT_ORDER; public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); if (!environment.getPropertySources().contains(PROPERTY_SOURCE_NAME)) { CloudHost itestHost = CloudHostFactory.getCloudHost("redis"); itestHost.setup(); String host = itestHost.getHostName(); // fetch the dynamic port from Docker int port = itestHost.getPort(6379); // alternatively, skip the whole CloudHost setup above and just use: // int port = SocketUtils.findAvailableTcpPort(); environment.getPropertySources().addLast( new MapPropertySource( PROPERTY_SOURCE_NAME, Collections.<String, Object> singletonMap( "redis.port", port)); ); } } } 选项,您的Redis将被绑定到主机上的随机端口。

至于如何在上下文中启用属性 - 它需要一些工作但你可以实现一个监听器来启动Docker容器并将端口作为属性放在一个环境中:

test <- seq(1,10,0.33) 
[1] 1.00 1.33 1.66 1.99 2.32 2.65 2.98 3.31 3.64 3.97 4.30 4.63 4.96 5.29 5.62 5.95 6.28 6.61 6.94 7.27 7.60 7.93 8.26 8.59 8.92 9.25 9.58 9.91