使用 HttpSession 对 Servlet Filter with Mockito 进行单元测试



我搜索了很长时间如何使用mockito和类HttpSession进行单元测试。我什么都没找到,所以我在这里问。

我有一个JavaEE的Web应用程序。我实现了三个过滤器,它们使用自定义 User 类登录网站。按用户类型进行一次筛选。我必须用JUnit和Mockito测试它们。这里唯一的问题是,我没有成功地重现httpSession和httpServletRequest的行为。当测试通过过滤器代码时,当涉及到session.getAttribute("User")时,它会返回空指针异常。你能看看这个代码吗?基本上,我需要模拟会话以获取"user"属性并验证重定向是否正确。

过滤器代码:

/**
 * Default constructor.
 */
public RestrictionFilterCaseAdmin ( )
{
    // TODO Auto-generated constructor stub
}

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter( ServletRequest req , ServletResponse res ,
                FilterChain chain )
                throws IOException , ServletException
{
    HttpServletRequest request = ( HttpServletRequest ) req;
    HttpServletResponse response = ( HttpServletResponse ) res;
    HttpSession session = request.getSession( );
    /* Creating temp user */
    if ( session.getAttribute( "User" ) != null ) {
        User userTmp = new User( );
        userTmp = ( User ) session.getAttribute( "User" );
        /**
         * If the user object don't exist, the user is not
         * connected.
         */
        if ( userTmp.getLogin( ) == null ) {
            /* Public page redirection */
            response.sendRedirect( request.getContextPath( )
                            + "/connexion" );
        } else if ( userTmp.getStatus( ).equals( "admin" ) ) {
            /* Restricted page redirection */
            chain.doFilter( request , response );
        } else {
            // User not allowed to dislay the page, go back
            // to home.
            response.sendRedirect( request.getContextPath( )
                            + "/redirect" );
        }
    } else {
        response.sendRedirect( request.getContextPath( )
                        + "/connexion" );
    }
}

@ Override
public void destroy( )
{
    // TODO Auto-generated method stub
}

@ Override
public void init( FilterConfig arg0 ) throws ServletException
{
    // TODO Auto-generated method stub
}

测试代码:

@ Mock
HttpServletRequest  httpServletRequest;
@ Mock
HttpServletResponse httpServletResponse;
@ Mock
FilterChain     filterChain;
@ Mock
User            userTest;
@ Mock
HttpSession     sessionTest;

@ Before
public void setUp( )
{
    httpServletRequest = mock( HttpServletRequest.class );
    httpServletResponse = mock( HttpServletResponse.class );
    filterChain = mock( FilterChain.class );
    userTest = mock( User.class );
    sessionTest = mock( HttpSession.class );
}

@ Test
public void testDoFilter( ) throws IOException , ServletException
{
    userTest.setLogin( "test" );
    userTest.setPwd( "test" );
    userTest.setStatus( "admin" );
    sessionTest.setAttribute( "User" , userTest );
    when( sessionTest.getAttribute( "User" ) )
                    .thenReturn( userTest );
    when( httpServletRequest.getSession( true ) )
                    .thenReturn( sessionTest );
    when( httpServletRequest.getRequestURI( ) )
                    .thenReturn( "/Home.jsp" );
    RestrictionFilterCaseAdmin adminFilter = new RestrictionFilterCaseAdmin( );
    adminFilter.doFilter( httpServletRequest , httpServletResponse ,
                    filterChain );s
    verify( httpServletResponse ).sendRedirect(
                    "/restricted/admin/restrictedAdminTest.jsp" );
}

谢谢!J.K.

筛选器执行此操作以获取会话:

HttpSession session = request.getSession();

但测试这样做是为了设置模拟请求以提供模拟会话:

when( httpServletRequest.getSession(true)).thenReturn(sessionTest);

request.getSession()request.getSession(true) 不是相同的方法签名,它会导致 null 会话对象并引发异常。 尝试将设置更改为:

when(httpServletRequest.getSession()).thenReturn(sessionTest);

旁注 - @Mock注释创建实例(假设测试类是@RunWith(Mockito...((,因此不需要setUp中的代码。

相关内容

  • 没有找到相关文章

最新更新