December is for many people a period of reflection or thought. So I decided to reflect upon last yearβs things and thoughts β each day until Christmas. This is day 4.
For a Grails integration test it is useful to know at what port your application is currently running.
Spring Boot β and consequently Grails which is built on top of it β exposes the at-startup-randomly-selected port through a property, called local.server.port.
When Googling it for Grails specifically, one usually comes on mrhakiβs Grails Goodness: Use Random Server Port In Integration Tests page β an excellent source of Grails Goodness β which clearly shows how to get the value of the local.server.port property using @Value.
You can see it in action below, in my own example.
import grails.plugins.rest.client.RestBuilder
import grails.plugins.rest.client.RestResponse
import grails.test.mixin.integration.Integration
import org.springframework.beans.factory.annotation.Value
import spock.lang.Specification
@Integration
class SomeIntegrationSpec extends Specification {
@Value('${local.server.port}')
Integer serverPort
void "health check works"() {
when:
String url = "http://localhost:${serverPort}/example/health"
def response = new RestBuilder().get(url)
then:
response.status == 200
}
}Somewhere last year I realized: I donβt need this at all.
@Integration
class SomeIntegrationSpec extends Specification {
// no serverPort!
void "health check works"() {
when:
String url = "http://localhost:${serverPort}/example/health"
def response = new RestBuilder().get(url)
then:
response.status == 200
}
}WAT? No serverPort property β and youβre still using it in "http://localhost:${serverPort}/example/health"?
Jip, at least in Grails 3.3.0 this functionality, the exact property Integer serverPort initialized with the corrct value, is added to the test class directly by the @Integration annotation β specifically: its AST transformation helper class.
As Bristish fiction author Arthur C. Clarke already stated:
Any sufficiently advanced annotation is indistinguishable from magic.
So true.
| Published on Java Code Geeks with permission by Ted Vinke, partner at our JCG program. See the original article here: X-Mas Musings #4 β Do Not Use Random Server Port in Grails Integration Tests Opinions expressed by Java Code Geeks contributors are their own. |
Thank you!
We will contact you soon.
Ted VinkeDecember 5th, 2017Last Updated: December 5th, 2017

This site uses Akismet to reduce spam. Learn how your comment data is processed.