How to Mock RequestContextHolder in junit testing groovy and grails

Viewed 2838

How to mock:

Long countryId = RequestContextHolder.currentRequestAttributes()?.session.country_id?.toLong();
Country country = Country.get(countryId) 

in junit testing using Groovy and Grails framework in STS?

1 Answers

you can set RequestAttributes in test eg:

method to be test

def someMethod () {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attr.getRequest();

    ...

    return null;
}

test the method

def testSomeMethod() {
    given:
    RequestAttributes mockRequest = new ServletWebRequest(new MockHttpServletRequest("GET", "/test"))
    RequestContextHolder.setRequestAttributes(mockRequest)

    when:
    def result = userDetailsService.someMethod()

    then:
    ...
}
Related