Juan Villalobos
Juan Villalobos

Reputation: 71

How to get the running server port in a SpringBoot test?

I'm creating some unit tests for a spring boot application with an Apache Camel route, using Spock as testing framework, and I need to mock a response from another application. I made a mock controller for that, but i need to inject the port that the test is running in to a property. Is there a way to get the port that the test is running on?

I tried with

@LocalServerPort
private int port 

and with

@Autowired Environment environment;
String port = environment.getProperty("local.server.port");

but both return a -1, I don´t know any other ways to get the port

My test is configured with the following annotations:

@RunWith(SpringRunner)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles('test')

Also, is there a way to inject that random port in the application-test.yml file? Ideally I would need to do something like this in my application-test.yml file:

app:
  service: localhost:${server.port}

Where the port is the random port that the test is running on.

Upvotes: 7

Views: 5963

Answers (1)

Abder KRIMA
Abder KRIMA

Reputation: 3678

Could you try this :

@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
    public class test{

    @LocalServerPort
    private int rdmServerPort;

    @LocalManagementPort
    private int rdmManagementPort;
        ...
}

Upvotes: 4

Related Questions