2

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.

Virkom
  • 373
  • 4
  • 22
  • check this links: https://stackoverflow.com/questions/30312058/spring-boot-how-to-get-the-running-port – tharanga-dinesh Sep 12 '18 at 18:20
  • you probably need to set you envirnoment to DEV somewhere – Gnk Sep 12 '18 at 18:21
  • @tharanga-dinesh profile is dev. It doesn't work. Also `local.server.port` is null – Virkom Sep 12 '18 at 18:32
  • 2
    By default `@SpringBootTest` runs with a mocked environment and hence doesn't have a port assigned. If you want to run with an actual port change the `webEnvironment` of `@SpringBootTest` to something else. – M. Deinum Sep 12 '18 at 18:57
  • @M. Deinum, thank you very much. It works now. – Virkom Sep 12 '18 at 19:00

0 Answers0