grailsApplication access in Grails unit Test

后端 未结 3 1667
猫巷女王i
猫巷女王i 2021-02-15 04:20

I am trying to write unit tests for a service which use grailsApplication.config to do some settings. It seems that in my unit tests that service instance could not access the c

相关标签:
3条回答
  • 2021-02-15 04:33

    Constructing grailsApp using DefaultGrailsApplication would work.

    class ZazzercodeUnitTestCase extends GrailsUnitTestCase {
        def grailsApplication = new org.codehaus.groovy.grails.commons.DefaultGrailsApplication()
        def chortIndex= grailsApplication.config.zazzercode.chortIndex
    }
    
    0 讨论(0)
  • 2021-02-15 04:55

    If you use @TestFor Grails (2.0) already mock grailsApplication for you, just set your configs, but do not declare the grailsApplication. Doing that overrides the mocked instance.

    @TestFor(MyService)
    class MyServiceTests {
    
      @Before
      public void setUp() {
        grailsApplication.config.something = "something"
      }
    
      @Test
      void testSomething() {
        MyService service = new MyService()
        service.grailsApplication = grailsApplication
        service.doSomething()
      }
    
    
    }
    

    EDIT:

    You declared a String, to add to config you must parse this. See here an example.

    Basically you use the ConfigSlurper().parse() to get a ConfigObject, and use grails.config.merge() to add the contents to the config.

    0 讨论(0)
  • 2021-02-15 04:56

    Go to http://ilikeorangutans.github.io/2014/02/06/grails-2-testing-guide

    Grails’ config is usually accessed via an injected instance of GrailsApplication using the config property. Grails injects GrailsApplication into unit tests, so you can access it directly:

    @TestMixin(GrailsUnitTestMixin)
    class MySpec extends Specification {        
        private static final String VALUE = "Hello"
        void "test something with config"() {
            setup:
            // You have access to grailsApplication.config so you can 
            //modify these values as much as you need, so you can do
            grailsApplication.config.myConfigValue = VALUE
    
            assert:             
            grailsApplication.config.myConfigValue == VALUE
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题