X-Mas Musings – Do Not Use Random Server Port in Grails Integration Tests
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. |





