在mocked HttpServletResponse实例中返回getContentType()为null

时间:2018-05-18 04:14:32

标签: java mockito

当我尝试判断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);
}

写printWriter:

@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());
}

1 个答案:

答案 0 :(得分:3)

因为HttpServletResponse被模拟,所以调用

的代码
response.setContentType("text/plain");

是无操作;模拟没有状态,并且除了记录之外没有对 set 调用做任何事情。

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

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