我有要测试的servlet。我想测试Mockito的doGet。
在srvlet的主要代码信息中,转到PrintWriter的页面/ json。
在我的测试中,我想将文件保存在要获取测试信息的位置。并且我无法测试PrintWriter(我不知道如何)

我尝试使用而不是测试中的PrintWriter

StringWriter sw = new StringWriter();
PrintWriter pw  =new PrintWriter(sw);
when(new PrintWriter(resp.getOutputStream())).thenReturn(pw);


这是我的Servlet doGEt

 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json");
        PrintWriter writer = new PrintWriter(resp.getOutputStream());
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(list);
        writer.append(jsonString);
        writer.flush();
    }


这是我的测试,不起作用

@Test
    public void whenShouldCheckJsonSrevlet() throws ServletException, IOException {
        String fileWay = "D:\\CODE_WORK\\JAVA\\java-a-to-z\\lesson8Aplication\\src\\main\\java\\persistent\\test.txt";
        final JSONControllers servlet = new JSONControllers();
        HttpServletRequest req = mock(HttpServletRequest.class);
        HttpServletResponse resp = mock(HttpServletResponse.class);
        PrintWriter writer = new PrintWriter(new FileWriter(fileWay));
        BufferedReader reader = new BufferedReader(new FileReader(fileWay));
        when(new PrintWriter(resp.getOutputStream())).thenReturn(writer);
        when(req.getReader()).thenReturn(reader);
        servlet.doGet(req,resp);
        servlet.doPost(req,resp);
    }

java.lang.NullPointerException
    at java.io.Writer.<init>(Writer.java:88)
    at java.io.OutputStreamWriter.<init>(OutputStreamWriter.java:109)
    at java.io.PrintWriter.<init>(PrintWriter.java:148)
    at java.io.PrintWriter.<init>(PrintWriter.java:131)
    at servlets.JSONControllersTest.whenShouldCheckJsonSrevlet(JSONControllersTest.java:62)

最佳答案

您要传入映射器的writeValueAsString的对象“列表”是什么? JSONControllersTest.java的哪一行是62?

10-07 16:01
查看更多