java模拟servlet_java-模拟的HttpServletResponse实例中的getContent...

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值