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.
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.
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.
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).
Spring Boot applications ship with an embedded server, and the default port for them is 8080 .
Could you try this :
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class test{
@LocalServerPort
private int rdmServerPort;
@LocalManagementPort
private int rdmManagementPort;
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With