我正在尝试对具有需要请求对象的方法的服务进行单元测试。
import org.springframework.web.context.request.RequestContextHolder as RCH
class AddressService {
def update (account, params) {
try {
def request = RCH.requestAttributes.request
// retrieve some info from the request object such as the IP ...
// Implement update logic
} catch (all) {
/* do something with the exception */
}
}
}
你如何模拟请求对象?
顺便说一句,我正在使用 Spock 对我的类(class)进行单元测试。
谢谢
最佳答案
此代码似乎适用于基本单元测试( modified from Robert Fletcher's post here ):
void createRequestContextHolder() {
MockHttpServletRequest request = new MockHttpServletRequest()
request.characterEncoding = 'UTF-8'
GrailsWebRequest webRequest = new GrailsWebRequest(request, new MockHttpServletResponse(), ServletContextHolder.servletContext)
request.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, webRequest)
RequestContextHolder.setRequestAttributes(webRequest)
}
它可以作为函数添加到您的标准 Grails 单元测试中,因为函数名称不以“test”开头......或者您可以以其他方式处理代码。
关于unit-testing - 在 Grails 中对服务进行单元测试时如何模拟请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15259307/