如何模拟:
Long countryId = RequestContextHolder.currentRequestAttributes()?.session.country_id?.toLong();
Country country = Country.get(countryId)
在 STS 中使用 Groovy 和 Grails 框架进行 junit 测试?
最佳答案
你可以在测试中设置RequestAttributes 例如:
要测试的方法
def someMethod () {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attr.getRequest();
...
return null;
}
测试方法
def testSomeMethod() {
given:
RequestAttributes mockRequest = new ServletWebRequest(new MockHttpServletRequest("GET", "/test"))
RequestContextHolder.setRequestAttributes(mockRequest)
when:
def result = userDetailsService.someMethod()
then:
...
}
关于grails - 如何在 junit 测试 groovy 和 grails 中模拟 RequestContextHolder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46360176/