6

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.

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123

1 Answers1

4

Could you try this :

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

    @LocalServerPort
    private int rdmServerPort;

    @LocalManagementPort
    private int rdmManagementPort;
        ...
}
Abder KRIMA
  • 3,418
  • 5
  • 31
  • 54
  • 3
    `WebEnvironment.RANDOM_PORT` is key here. If you use the default mock web environment, no embedded container is started. As a result, there's no port involved and `-1` will be injected. – Andy Wilkinson Nov 28 '18 at 16:47
  • @AndyWilkinson looks like op is already using that. If using `RANDOM_PORT` is there a way to reference it in the property file like OP says `app.service=localhost:${server.port}` (with server.port not beind explicitly defined) – Federico Piazza Nov 28 '18 at 18:04