Unit testing a method dependent to the request context
I'm writing a unit test for a method that contains the following line:
String sessionId = RequestContextHolder.currentRequestAttributes().getSessionId();
I get the following error:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
The reason is quite obvious — I'm not running the test in a request context.
The question is, how can I test a method that contains a call to a method dependent to the request context in a test environnment?
Thank you very much.
Solution 1:
Spring-test has a flexible request mock called MockHttpServletRequest.
MockHttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
Solution 2:
You can mock/stub the RequestAttributes
object to return what you want, and then call RequestContextHolder.setRequestAttributes(RequestAttributes)
with your mock/stub before you start your test.
@Mock
private RequestAttributes attrs;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
RequestContextHolder.setRequestAttributes(attrs);
// do you when's on attrs
}
@Test
public void testIt() {
// do your test...
}