2
votes

I have a situation in a Controller where I'm surrounding pieces of code in if(Environment.Current == Environment.PRODUCTION) blocks because the block of code is calling methodA in restService that makes a REST call to a URL that is only available when the app is deployed onto a specific production server. However doing so means that area of code is unreachable when running tests, which makes me a bit uncomfortable.

In the Development environment I'm not concerned with making the call to methodA as I'm stubbing out what the methodA would return and passing it on to the next Controller, so changing the if statement to if(Environment.Current != Environment.DEVELOPMENT) allows me to test the code better and not have to make calls to places I can't reach during dev.

Ideally though I would like to try and inject a Service into a Controller dependent on the grails environment; so I could have two Services like this:

class RestService {
  def methodA() {
    // go do a REST call
  }
}

and

class FakeRestService() {
  def methodA() {
    // return some stubbed response
  }
}

and in my Controller restService would be an instance of FakeRestService in DEVELOPMENT and TEST environments, and an instance of RestService in PRODUCTION

class SearchController {
  def restService

  def index() {
    restService.methodA()
  }

I'm a bit stumped on how I could achieve this in a 'Grailsy'/Spring way. I've been looking into creating some sort of Service Factory which would return an instance of either RestService or FakeRestService dependent on the environment, but it would be nice if I could define what Service to inject into restService in config or something similar.

Any advice would be great!

2

2 Answers

3
votes

You can add an alias for the bean name in resources.groovy when environment is TEST.

import grails.util.Environment

beans = {
    if ( Environment.current == Environment.TEST ) {
        springConfig.addAlias 'restService', 'fakeRestService'
    }
}

RuntimeSpringConfiguration is available in resources.groovy by getSpringConfig().

0
votes

Here is a more Grails-y version of dmahapatro's answer:

import grails.util.Environment

beans = {
    Environment.executeForCurrentEnvironment {
        environments {
            development {
                springConfig.addAlias 'restService', 'fakeRestService'
            }
        }
    }
}