2013-12-19 51 views
2

是否有人知道如何模拟以下内容?嘲笑模拟页面的httpRequestContext

pageContext.getRequest().getParameter("par");// here I get a null pointer exception on getParameter 

有什么办法可以在模拟pageContext对象中注入httpRequest吗?

在此先感谢。

+0

如果你需要对象包含一个特定的值,你应该阅读** mockito中的** stubbing **。 –

+0

查看Mockito的[在API](http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html)第13章“侦察真实物体”下的间谍功能 –

+1

考虑使用spring-mock,它具有MockHttpServletRequest的MockPageContext。 http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/mock/web/MockPageContext.html – Pieter

回答

0

桩可以用于连锁。下面的片段显示了这个想法

PageContext pageContext = mock(PageContext.class); 
    HttpServletRequest request = mock(HttpServletRequest.class); 
    when(request.getParameter("par")).thenReturn("what you want"); 
    when(pageContext.getRequest()).thenReturn(request);