Spring Boot Test if web server starts on a specific port
Below is a Spring Boot Test example to test whether the web server started on port 8181.
P.S. Tested with Spring Boot 3 and JUnit 5.
application.properties
server.port = 8181
WebServerTests.java
package com.mkyong;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebServerTests {
@LocalServerPort
private int port;
@Test
public void testServerPort() {
assertEquals(8181, port, "Server is not running on port 8181");
}
}
- The
@LocalServerPort
annotation injects the actual web server port.
Download Source Code
$ git clone https://github.com/mkyong/spring-boot.git
$ cd spring-boot-change-port
$ mvn spring-boot:run
References
About Author
Comments
Subscribe
0 Comments