Skip to content

Spring Boot Integration test random free port

I am able to get Spring Boot integration to generate a random free port to launch itself on. But I also need a free port for 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;
    private int serverPort;

    private RedisServer redisServer;

    public void beforeScenario() throws Exception {
        host = String.format(HOST_TEMPLATE, serverPort);
        redisServer = RedisServer.builder()


Any ideas on how to achieve this?



You can use Spring Framework’s SocketUtils to get an available port:

int redisPort = SocketUtils.findAvailableTcpPort();
7 People found this is helpful