在春季启动测试中如何获取服务器端口

时间:2018-09-12 18:01:25

标签: java spring-boot junit

我有Spring Boot 1.5.3应用程序。 application.properties文件中有一行server.port = 8081。 现在我要测试ping方法:

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);
}

测试:

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

    @Autowired
    private ServerCommunicateService serverCommunicateService;

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

但是它不起作用,因为端口是-1。该环境有4个属性源,其中第一个包含属性server.port = -1。我需要application.properties文件中的端口。

它可以在生产中使用,但不能在测试中使用。

0 个答案:

没有答案
相关问题