1

想要测试我的自定义 TagLib 的 addJsFile 方法的总“测试新手”。我错过了什么?

标签库:

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>'
        }
    }
}

测试(据我所知):

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)
    }
}

使用 isSecureRequest

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

错误

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

1 回答 1

3

您需要设置模拟util才能tagLib使用它。

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()
}

那么你就不需要def util在测试中了。

于 2013-08-16T22:39:07.413 回答