java在使用mockito时为PageControl获取NPE
当我在测试类中使用mockito获得PageControl的mock值时。然而,在调试时,我在下面一行中看到classunder test中的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);
}
}
共 (0) 个答案