use of org.springframework.web.context.request.RequestContextHolder in project spring-framework by spring-projects.
the class RequestContextFilterTests method testFilterInvocation.
private void testFilterInvocation(final ServletException sex) throws Exception {
final MockHttpServletRequest req = new MockHttpServletRequest();
req.setAttribute("myAttr", "myValue");
final MockHttpServletResponse resp = new MockHttpServletResponse();
// Expect one invocation by the filter being tested
class DummyFilterChain implements FilterChain {
public int invocations = 0;
@Override
public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
++invocations;
if (invocations == 1) {
assertThat(RequestContextHolder.currentRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST)).isSameAs("myValue");
if (sex != null) {
throw sex;
}
} else {
throw new IllegalStateException("Too many invocations");
}
}
}
DummyFilterChain fc = new DummyFilterChain();
MockFilterConfig mfc = new MockFilterConfig(new MockServletContext(), "foo");
RequestContextFilter rbf = new RequestContextFilter();
rbf.init(mfc);
try {
rbf.doFilter(req, resp, fc);
assertThat(sex).isNull();
} catch (ServletException ex) {
assertThat(sex).isNotNull();
}
assertThatIllegalStateException().isThrownBy(RequestContextHolder::currentRequestAttributes);
assertThat(fc.invocations).isEqualTo(1);
}
Aggregations