Unit testing a method dependent to the request context
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...
}
Spring-test has a flexible request mock called MockHttpServletRequest.
MockHttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));