java - Spring Boot Integration 测试随机空闲端口

标签 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();
    }

    ...
}

关于如何实现这一目标有什么想法吗?

最佳答案

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

int redisPort = SocketUtils.findAvailableTcpPort();

关于java - Spring Boot Integration 测试随机空闲端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38977633/

相关文章:

spring-boot - 如何生成包含一些自定义声明的 JWT 访问 token ?

java - 双向数据绑定(bind) : Unable to change EditText value when value updated from an inner class

java - 粗线和矩形相交java

Spring Cloud Gateway+Consul 配置

html - 如何国际化html页面

java - ANT 到 Maven 的迁移。 build.xml 的 Maven 替代方案

java - 将字符串转换为 'Instant'

java - 如何在Android中显示统计数据等数据?

java - 带有多个参数的 Spring 消息标签

spring-boot - 使用CrudRepository中的外键进行Spring Boot