在模拟的 HttpServletResponse 实例中返回的 getContentType() 为空



当我尝试判断response.getContenttype()的返回值时,运行控制台显示:

java.lang.AssertionError: 
Expected :text/plain
Actual   :null

但是当我尝试判断stringWriter()的返回值时,还可以:

Process finished with exit code 0

源代码:

业务代码段:

设置内容类型:

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("utf-8");
process(request, response);
}

写印刷作家:

@Override
protected void process(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
JSONObject resultObject = queryMXRatioData(request);
response.getWriter().write(resultObject.toJSONString());
}

测试类:

public class TestServlet extends Mockito {
private HttpServletRequest request = mock(HttpServletRequest.class);
private HttpServletResponse response = mock(HttpServletResponse.class);
private HttpSession session = mock(HttpSession.class);
private StringWriter stringWriter = new StringWriter();
private PrintWriter printWriter = new PrintWriter(stringWriter);
@Before
public void setup() throws Exception {
when(request.getParameter("start")).thenReturn("0");
when(request.getSession()).thenReturn(session);
when(response.getWriter()).thenReturn(printWriter);
}
@Test
public void testGetContentType() throws Exception {
new MXRatioDataLoader().doPost(request, response);
assertEquals("text/plain", response.getContentType());
}
@Test
public void testStringWriter() throws Exception {
new MXRatioDataLoader().doPost(request, response);
String expect = "{"total":1,"data":[{"U":"230.36575","LOWLIMIT":"200","OID":"5629499552628739","NAME":"220kV","RATIO":"104.7%","LIMIT":"250"}]}";
assertEquals(expect, stringWriter.toString());
}

因为HttpServletResponse被模拟,所以调用的代码

response.setContentType("text/plain");

是一个无操作;模拟没有状态,除了记录它发生之外,不会对设置的调用做任何事情。

更好的测试是验证是否进行了适当的调用,即

new MXRatioDataLoader().doPost(request, response);
verify(response).setContentType("text/plain");

相关内容

  • 没有找到相关文章

最新更新