将此代码用于servlet html响应:
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/projects.jsp");
dispatcher.forward(request, response);
}
方法工作正常并返回由projects.jsp构建的浏览器HTML。 现在我想测试这个HTML响应,但我可以得到一个JSP输出。
`
@Test
public void doGetTest() {
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
RequestDispatcher requestDispatcher = Mockito.mock(RequestDispatcher.class);
HttpSession session = Mockito.mock(HttpSession.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
try {
when(response.getWriter()).thenReturn(printWriter);
when(request.getSession()).thenReturn(session);
when(request.getRequestDispatcher("/projects.jsp")).thenReturn(requestDispatcher);
} catch (IOException ex) {
fail(ex.getMessage());
}
try {
new Projects().doGet(request, response);
verify(requestDispatcher).forward(request, response);
} catch (ServletException | IOException ex) {
fail(ex.getMessage());
}
printWriter.flush();
System.err.println(stringWriter.getBuffer().toString().trim());
}
`
stringWriter.getBuffer()。toString()。trim()
这里不返回HTML代码,只是空白字符串。我尝试过谷歌和这里,但我找不到JUnit和Java 8的工作示例(例如找到Selenium)。这个测试代码没有jsp的好工作(servlet通过response.getWriter()。println()写入响应。 请告诉我,在这种情况下如何获得JSP HTML响应?