How to get server port in spring boot test

一曲冷凌霜 提交于 2020-01-02 20:10:29

问题


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.

来源:https://stackoverflow.com/questions/52301056/how-to-get-server-port-in-spring-boot-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!