我正在为servlet编写测试用例。在测试中,我无法使用mockito将servlet上下文变量传递给servlet。我试过但是在servlet中它给出了空指针异常。下面我提供代码和测试代码:
代码是:
public class httpt_vb_getTableNames extends HttpServlet implements SingleThreadModel {
int userId;
String userName;
String userPassword;
public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println( "came to httpt_vb_getTableNames servlet");
response.setContentType( "text/plain");
ServletContext sc = getServletContext();
ServletOutputStream servletOut = response.getOutputStream ();
}
测试代码是:
public class http_vb_getTableNamesServletTest {
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Mock
HttpSession session;
@Mock
RequestDispatcher rd;
@Mock
ServletOutputStream servletOut;
@Mock
ServletContext sc;
@Mock
FilterConfig filterConfig;
public final static String Seperator = new Character((char)1).toString();
public final static String ContentDelimeter = new Character((char)2).toString();
@BeforeClass
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
sc=mock(ServletContext.class);
}
@Test
public void test() throws Exception {
DataSet ds=new DataSet();
String buffer=ds.getUserId()+Seperator+ds.getUsername();
ByteArrayOutputStream bos = new ByteArrayOutputStream ();
ZipOutputStream out = new ZipOutputStream(bos);
out.putNextEntry(new ZipEntry("request.txt"));
out.write(buffer.getBytes("UTF-8"));
out.closeEntry();
out.close();
bos.close();
String b64String = Base64.encodeBase64String(bos.toByteArray());
Reader inputString = new StringReader(b64String);
BufferedReader reqbuffer = new BufferedReader(inputString);
httpt_vb_getTableNames servlet=new httpt_vb_getTableNames();
when(request.getReader()).thenReturn(reqbuffer);
when(request.getServletContext()).thenReturn(sc);
when(response.getOutputStream()).thenReturn(servletOut);
when(sc.getRequestDispatcher("/jsp/admin/chooseNeighborhood.jsp")).thenReturn(rd);
when(sc.getRequestDispatcher("/jsp/admin/joinNeighborhood.jsp")).thenReturn(rd);
servlet.service(request, response);
ArgumentCaptor<String> bufferCaptor = ArgumentCaptor.forClass(String.class);
verify(servletOut).print(bufferCaptor.capture());
String responseBody = bufferCaptor.getValue();
ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(Base64.decodeBase64(responseBody.toString().getBytes())));
zipIn.getNextEntry();
StringBuffer sb = new StringBuffer();
ByteArrayOutputStream out1 = new ByteArrayOutputStream();
IOUtils.copy(zipIn, out1);
sb = new StringBuffer();
sb.append(out1.toString("UTF-8"));
String[] res=sb.toString().split(Seperator);
AssertJUnit.assertEquals("Success",res[0]);
}
}
任何人都可以建议我如何在mocktio中模拟servlet上下文? 在此先感谢