grails - 如何在 junit 测试 groovy 和 grails 中模拟 RequestContextHolder

标签 grails groovy junit

如何模拟:

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/

相关文章:

带有 Dagger 2 的 Android 普通 Junit

hibernate - HQL Hibernate 排序依据

java - 在ServletContextListener中访问 session 变量

groovy - 在 Groovy 和 Jenkins Pipeline 中组合多个 collectEntries

postgresql - Grails 2.5.11/Postgresql 10,在GSP中上传图像并显示

junit - 如何使用 junit 的 assertThat 检查列表是否仅包含某些不相关的类类型?

grails - Grails域类单元测试

html - 您如何在Grails/HTML中设置我的网站的起始部分

groovy - 在常规中,如何返回零填充范围?

selenium - Java/JUnit 和 Selenium RC - 是否有包装库?