gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:25:03 24 4
gpt4 key购买 nike

总“测试新手”想要测试我的自定义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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com