Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
satoshi Avatar asked Feb 23 '12 19:02

satoshi


1 Answers

Spring-test has a flexible request mock called MockHttpServletRequest.

MockHttpServletRequest request = new MockHttpServletRequest(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); 
like image 114
pap Avatar answered Sep 28 '22 03:09

pap