How to get server port in spring boot test

2019-05-27 01:27发布

问题:

I have Spring Boot 1.5.3 application. There is a line server.port = 8081 in application.properties file. Now I want to test ping method:

private final Environment environment;

@Autowired
public ServerCommunicateServiceImpl(Environment environment) {
    this.environment = environment;
}

@Override
public boolean pingHost(String host) {
    int port = environment.getProperty("server.port", Integer.class, DEFAULT_PORT);
    return pingHost(host, port, DEFAULT_TIMEOUT);
}

Test:

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

    @Autowired
    private ServerCommunicateService serverCommunicateService;

    @Test
    public void pingHost() {
        boolean result = serverCommunicateService.pingHost("localhost");
        assertThat(result, is(true));
    }
}

But it doesn't work because port is -1. The environment have 4 property sources and first of it contains property server.port = -1. I need port from application.properties file.

It works on production but not works in tests.