对Servlet请求及响应进行mock方法,
通过getMockInstance方法对servlet进行打桩,对servlet提供的方法进行mock,替代真正的servlet请求或响应。
参考链接:
https://stackoverflow.com/questions/31689729/servlet-junit-test-using-jmockit
代码如下:
@RunWith(JMockit.class) public class ImageServletTest3 { @Test public void testImageNotFound() throws Exception { ImageServlet servlet = new ImageServlet(); servlet.doGet( new MockUp<HttpServletRequest>() { @Mock public String getParameter(String id){ return null; } }.getMockInstance(), new MockUp<HttpServletResponse>() { @Mock public void sendError(int num){ Assert.assertThat(num, IsEqual.equalTo(404)); } }.getMockInstance() ); } }