我正在使用Mockito编写Servlet的测试用例。
在Servlet响应中使用ServletOutputStream设置。
我发送请求servlet正在正常工作,也可以在控制台中输出输出,但是在TestClass中,我没有上课。以下是设置响应的代码:
protected void commitResponseBuffer(String buffer, ServletResponse response) throws IOException
{
response.setContentType("text/plain");
System.out.println("Uncompressed Response Buffer : Size = " + buffer.length());
// write to ZipOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream ();
ZipOutputStream out = new ZipOutputStream(bos);
out.putNextEntry(new ZipEntry("response.txt"));
out.write(buffer.getBytes("UTF-8"));
//out.flush();
out.closeEntry();
out.close ();
bos.close();
// encode to Base64 string
String b64String = Base64.encodeBase64String(bos.toByteArray());
// set the response
ServletOutputStream servletOut = response.getOutputStream();
response.setContentLength(b64String.length());
System.out.println("Compressed Response Buffer : Size = " + b64String.length());
servletOut.print(b64String);
System.out.println(b64String);
servletOut.close();
}
和在测试类中
when(response.getOutputStream()).thenReturn(servletOut);
new xlCollaborationService().service(request, response);
System.out.println("Response Buffer in mock :"+response.getContentType());
任何人都可以建议我如何阅读测试课中的响应吗???预先感谢。
看来您在正确的轨道上。
您可以使用Mockito的参数captor捕获传递给模拟并"捕获"该值的参数。文档在这里
ServletResponse response = mock(ServletResponse.class);
ServletOutputStream servletOut = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(servletOut);
new xlCollaborationService().service(request, response);
// Capture argument
ArgumentCaptor<String> bufferCaptor = ArgumentCaptor.forClass(String.class);
verify(servletOut).print(bufferCaptor.capture());
String responseBody = bufferCaptor.getValue();
System.out.println(responseBody);