Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 945
Juan Villalobos Avatar asked Nov 28 '18 16:11

Juan Villalobos


People also ask

How do I know which port spring boot is running?

Usually, the most straightforward way to configure the HTTP port of a Spring Boot application is by defining the port in the configuration file application. properties or application. yml.

How do I get local server host and port in spring boot?

To get the server address you can use the InetAddress class to get the local ip-address, for the port you can use ${server. port:8080} is you are using tomcat (this trick would also work for the server. address of course.

How do you get the spring boot host and port address during run time?

You can get this information via Environment for the port and the host you can obtain by using InternetAddress . Getting the port this way will only work, if a) the port is actually configured explicitly, and b) it is not set to 0 (meaning the servlet container will choose a random port on startup).

What is the default server port in spring boot?

Spring Boot applications ship with an embedded server, and the default port for them is 8080 .


1 Answers

Could you try this :

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

    @LocalServerPort
    private int rdmServerPort;

    @LocalManagementPort
    private int rdmManagementPort;
        ...
}
like image 87
TinyOS Avatar answered Oct 04 '22 03:10

TinyOS