Unable to mock Grails Service method when unit testing Controller - MissingMethodException

[亡魂溺海] 提交于 2019-12-04 09:31:54

Assuming there is an action in VController as:

def myAction() {
    vService.isOk('Hello')
}

below test should pass

void 'test service'() {
    given:
    def vServiceMock = mockFor(FormatService)
    vServiceMock.demand.isOk { String yeah -> return true }
    controller.vService = vServiceMock.createMock()

    when:
    def isO = controller.myAction() 

    then:
    isO == true
}

There are few things to optimize here including using a method isOk instead of a closure as best practices.

One is not expected to test a method which is being mocked. When we mock a method, we just assume its implementation is correct and has already been tested (in some other unit test). The purpose of mocking is to limit our focus of testing to limited lines of code (mostly commonly one method), in your case the your controller action. So the above test case could have been written as:

Assuming your action is like this:

def myAction(){
 [iso: vServiceMock.isOk()] // assuming isOk returns boolean true
}

void "test myAction"() {
        given:
        def vServiceMock = mockFor(VService)
        vServiceMock.demand.isOk { String yeah -> return true }
        controller.vService = vServiceMock.createMock()

        when:
        def model = controller.myAction() 

        then:
        model.iso   //you can skip comparison with true 
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!