当我尝试判断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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。