Skip to content

server.port should not be set to -1 if the test does not start an embedded web server #16998

@midstr

Description

@midstr

when i use spring-boot for no-web application, in the spring-boot-test ,"server.port" was be override by org.springframework.boot.test.context.SpringBootContextLoader.getInlinedProperties()
properties.add("server.port=-1") . therefore on my unit test, i cannot start server.

application.properties:

server.port=12345
server.name=myserver`

MyServer.java:

@Component
public class MyServer implements Closeable {

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

    @Value("${server.name}")
    private String serverName;

    private ServerSocket serverSocket;

    @PostConstruct
    public void init() {
        System.out.println("server.port:" + serverPort);
        System.out.println("server.name:" + serverName);
        // start my server on port "server.port"
        ....
    }
   
}

SpringBootDemoApplication.java:

@SpringBootApplication
public class SpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootDemoApplication.class, args);
	}

}

SpringBootDemoApplicationTest.java:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemoApplicationTest {

    @Resource
    private MyServer myServer;

    @After
    public void tearDown() throws Exception {
        myServer.close();
    }

    @Test
    public void contextLoads() throws Exception {
        String message = MyClient.sendToServer();
        assertThat(message, startsWith("hello client!"));
    }


}

spring-boot-demo.zip

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions