简体   繁体   中英

Junit Testing a Custom Filter in Spring

I am trying to Junit test a Custom Filter that I'm using with spring-security. I am not sure how to go about it from where I am. I know I have to test both branches of my if statement but I guess I'm not exactly sure how to go about doing that. Here is what I have in my class:

    @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession(false);
    String passwordURL = "/land";

    try {
        SecurityContextImpl sci = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");

        boolean urlRequest = passwordURL.equals(req.getRequestURI());

        MyUser myUser = (MyUser) sci.getAuthentication().getPrincipal();

        if (myUser.isFirstLogin()) {
            if (urlRequest) {
                filterChain.doFilter(request, response);
            } else
                res.sendRedirect(passwordURL);
        }

    } catch (NullPointerException e) {

    }
    filterChain.doFilter(request, response);
}
}

And here is my current test:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HandlerTests {
    CustomFilter customFilter = new CustomFilter();

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testDoFilter() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
        FilterChain filterChain = mock(FilterChain.class);
        SecurityContextImpl sci = mock(SecurityContextImpl.class);



        customFilter.doFilter(request, response, filterChain);

        verify(request).getSession(false);
    }
}

Side note: MyUser is a custom UserDetails class

You can mock it down to the User:

HttpSession session = mock(HttpSession.class);
when(req.getSession(false)).thenReturn(session);
SecurityContextImpl sci = mock(SecurityContextImpl.class);
when(session.getAttribute("SPRING_SECURITY_CONTEXT")).thenReturn(sci);
Authentication auth = mock(Authentication.class);
when(sci.getAuthentication()).thenReturn(auth));
MyUser user = mock(MyUser.class);
when(auth.getPrincipal()).thenReturn(user);
when(user.isFirstLogin()).thenReturn(testCaseSpecific); // two test cases
verify(filterChain).doFilter(req, res); // for true
verify(res).sendRedirect(passwordUrl); // for false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM