ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-模拟的HttpServletResponse实例中的getContentType()返回为null

2019-11-09 02:02:36  阅读:12  来源: 互联网

标签:mockito java



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

解决方法:

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

response.setContentType("text/plain");

是无人操作;模拟没有状态,除了记录它发生的情况外,没有对set调用执行任何操作.

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

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


标签:mockito,java

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有