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

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

来源: https://codeday.me/bug/20191109/2010936.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值