Search code examples
unit-testinggrailsjunit4grails-controller

Cant use grailsApplication.getMetadata.get(" ") while performing unit test for controller in grails


In my grails application, in the controller, I use following kind of a thing :

class SampleController {
   def action1 = {
     def abc = grailsApplication.getMetadata().get("xyz")
     render abc.toString()
   }
}

While running the app, it correctly reads the property "xyz" from application.properties and works fine. But when I write a unit test case for the above controller as follows :

class SampleControllerTests extends ControllerUnitTestCase {
  SampleController controller

  protected void setUp() {
    super.setUp()
    controller = new SampleController()
    mockController(SampleController)
    mockLogging(SampleController)
  }

  void testAction1() {
    controller.action1()
    assertEquals "abc", controller.response.contentAsString
  }
}

But when I do "grails test-app", I expect that it will pick up the property "xyz" from application.properties and will return as expected. But it gives error as "No such property : grailsApplication".

I understand, I guess I need to mock grailsApplication object and I tried many of the options also But all those didn't work.

I am new to Grails.


Solution

  • mockController will not mock the GrailsApplication, you will need to do it yourself.

    The fastest solution would be something like:

    protected void setUp() {
            super.setUp()
            mockLogging(DummyController)
            GrailsApplication grailsApplication = new DefaultGrailsApplication()
            controller.metaClass.getGrailsApplication = { -> grailsApplication }
        }
    

    This solution is not perfect - it will create a new DefaultGrailsApplication during each setup and mockController also creates some additional instances of DefaultGrailsApplication.

    Note that you do not need to call mockController by yourself it will be done by the ControllerUnitTestCase for you.