I am using Spring Boot 1.5 for my application. In integration testing I want to fetch the runtime port number of the web server(note: TestRestTemplate is not useful in my case.). There are a few approaches I have tried but none of them seem to work. Below are my approaches.
First Approach
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.DEFINED_PORT)
public class RestServiceTest {
@LocalServerPort
protected int port;
In my src/main/resources/config/application.properties file I have defined server port as
server.port = 8081
But With this code I am getting error
Could not resolve placeholder 'local.server.port' in value "${local.server.port}"
Second Approach
I have changed
webEnvironment =WebEnvironment.DEFINED_PORT
to
webEnvironment =WebEnvironment.RANDOM_PORT
and in my src/main/resources/config/application.properties file I have defined
server.port = 0
This throws the same as error as the first approach.
Third Approach
In third approach I have tried to use
protected int port;
@Autowired
Environment environment
this.port = this.environment.getProperty("local.server.port");
this returns null value
Fourth Approach
Lastly I have tried to use ApplicationEvents to find out the port number by creating an event listener to listen to EmbeddedServletContainerIntialize
@EventListener(EmbeddedServletContainerInitializedEvent.class)
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
this.port = event.getEmbeddedServletContainer().getPort();
}
public int getPort() {
return this.port;
}
Added the same to TestConfig
Now, In my test class I have tried use this listener to get the port
@SpringBootTest(classes = TestConfig.class, webEnvironment =WebEnvironment.RANDOM_PORT)
public class RestServiceTest {
protected int port;
@Autowired
EmbeddedServletContainerIntializedEventListener embeddedServletcontainerPort;
this.port = this.embeddedServletcontainerPort.getPort();
this returns 0. Also, I have found out listener event is never triggered.
It is very straight forward as in the docs and other posts but somehow It is not working for me. Help is much appreciated.
Aucun commentaire:
Enregistrer un commentaire