unit-testing - 测试使用请求对象的自定义Grails TagLib方法

标签 unit-testing grails mocking httprequest taglib

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

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

测试(据我所知):
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

最佳答案

您需要在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

关于unit-testing - 测试使用请求对象的自定义Grails TagLib方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283044/

相关文章:

java - 验证 JUnit 中的具体异常详细信息

java - 如何在 Java 中获取不同单词的数量?

Laravel:带有点击功能的单元测试

sql - 如何防止 Grails 在 dbCreate 期间生成默认的 Hibernate_sequence?

grails - GGTS不接受来自SDKman安装的较新grails版本

javascript - Angular JS : how to mock localStorgaeService with spyOn?

node.js - "ReferenceError: You are trying to ` 导入 ` a file after the Jest environment has been torn down"与 Mongoose 一起使用 jest 时

c# - 模拟和单例

c# - 在 C# 中使用 Moq 进行模拟

grails - grails "dependency error"如何解决?