Testing a custom Grails TagLib method that uses request object

与世无争的帅哥 提交于 2019-12-12 03:09:30

问题


Total 'testing newbie' wanting to test the addJsFile method of my custom TagLib. What am I missing?

TagLib:

import com.company.group.application.helper.Util
...   
class MyTagLib {
    static namespace = 'mytag'
    def util
    ...
    def addJsFile = {
        if (util.isSecureRequest(request)) {
            out << '<script src="https://domain.com/jsfile.js"></script>'
        } else {
            out << '<script src="http://domain.com/jsfile.js"></script>'
        }
    }
}

Test (as far as I could get):

import org.springframework.http.HttpRequest
import com.company.group.application.helper.Util

@TestFor(MyTagLib)
class MyTagLibTests {
    def util
    ...
    void testAddJsFileSecure() {
        def mockUtil = mockFor(Util)
        mockUtil.demand.isSecureRequest() { HttpRequest request -> true }
        def jsCall = applyTemplate('<mytag:addJsFile />')
        assertEquals('<script src="https://domain.com/jsfile.js"></script>', jsCall)
    }
    void testAddJsFileNotSecure() {
        def mockUtil = mockFor(Util)
        mockUtil.demand.isSecureRequest() { HttpRequest request -> false }
        def jsCall = applyTemplate('<mytag:addJsFile/>')
        assertEquals('<script src="http://domain.com/jsfile.js"></script>', jsCall)
    }
}

Util isSecureRequest

boolean isSecureRequest(request) {
    return [true or false]
}

Error

org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <mytag:addJsFile>: Cannot invoke method isSecureRequest() on null object

回答1:


You need to set the mocked util in tagLib in order to use it.

void testAddJsFileSecure() {
    def mockUtilControl = mockFor(Util)
    mockUtilControl.demand.isSecureRequest() { HttpRequest request -> true }

    //"tagLib" is the default bind object provided 
    //by the mock api when @TestFor is used
    tagLib.util = mockUtilControl.createMock()

    //Also note mockFor() returns a mock control 
    //which on createMock() gives the actual mocked object

    def jsCall = applyTemplate('<mytag:addJsFile />')
    assertEquals('<script src="https://domain.com/jsfile.js"></script>', jsCall)

    //In the end of test you can also verify that the mocked object was called
    mockUtilControl.verify()
}

You would not need def util in the test then.



来源:https://stackoverflow.com/questions/18283044/testing-a-custom-grails-taglib-method-that-uses-request-object

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