简体   繁体   中英

Grails Unit Testing Issues

I am having issues while testing my grails controllers, as it depends on one service which seems not to be injected. I tried several ways (for ex. Extending classess like grailsunitestcase, specification) but I keep getting errors. The thing is that that service variable is null and I cant test my controller index method (which calls a render view) due to the exception... I really need to know how to do this but I don't have a clue where to start...

Unit tests are just that. There is no grails 'environment' surrounding your controller. If the controller makes use of a service which is normally injected, you have to mock that service yourself.

@TestFor(SomeController)
@Mock([SomeService])
class SomeControllerSpec extends Specification
    def "test some method"() {
        given:
            def mockService = mockFor(SomeService)
            mockService.demand.someServiceMethod() { ->
                return something
            }

            controller.someService = mockService.createMock()
        when:
            controller.someControllerMethod()
        then:
           // whatever checks are appropriate
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM