使用Mockito时为PageControl获取NPE

问题描述

虽然我可以在测试类中使用Mockito来获取PageControl的模拟值。但是在调试时,我在受测类中看到pagecontrol在下面的行中为null-

HttpSession hSess = ((HttpServletRequest)pageContext.getRequest()).getSession();

供我测试的课程参考-

public class ViewTagTest {
    HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);
    HttpSession Hsess =     Mockito.mock(HttpSession.class);
    Context Ctx =     Mockito.mock(Context.class);
    ServletContext application = Mockito.mock(ServletContext.class);
   PageContext pageContext = Mockito.mock(PageContext.class);

    @Test
    public void test() throws JspException {
    
        Mockito.when((HttpServletRequest)pageContext.getRequest()).thenReturn(httpServletRequest);
      Mockito.when(((HttpServletRequest)pageContext.getRequest()).getSession()).thenReturn(Hsess);
                   


        ViewTag ot = new ViewTag();
        assertEquals(2,ot.doStartTag());
    }

我正在为其编写本junit的ViewTag类代码-

private void processFields(String[] fields,TemplateEvaluator te) throws ConfigException
{
    HttpServletRequest  request     = (HttpServletRequest)pageContext.getRequest();
    ServletContext      application = pageContext.getServletContext();
    ContextImpl Context = new ContextImpl(request,pageContext.getResponse(),request.getSession(false),application);
    
     HttpServletRequest req = Context.getHttpServletRequest();

//         for (Enumeration e = req.getParameterNames() ; e.hasMoreElements() ;)
//         {
//             String pn = (String)e.nextElement();
//             logger.debug("FormElements(...)","parameter "+pn+" = "+req.getParameter(pn));
//         }
        final String method="processFields(...)";
        if(fields!=null && fields.length>0)
        {
            for(int i=0;i<fields.length;i++)
            {
                String data = null;
                String formName =doc.getName();
                try{ data = doc.getData(i); } catch(Exception e){}

                try{ te.put("field."+fields[i]+".name",fields[i]); } catch(Exception e){}

            try
            {
                String labelText = doc.getLabel(i);
                te.put("field."+fields[i]+".label",labelText); // set labels in thtml
                if(state.equalsIgnoreCase("submitted") && !doc.isValid(i))
                {
                    String basicErrorLabelText = labelText;
                    int colonIndex=labelText.indexOf(":");
                    if(colonIndex>-1)basicErrorLabelText=labelText.substring(0,colonIndex);
                    logger.debug(method+"label="+labelText+",index="+colonIndex+",basic error label text = "+basicErrorLabelText,ViewTag.class.getSimpleName(),httpResponseStatus,null);
                }
            }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)