gpt4 book ai didi

java - 如何测试 resp.getOutputStream()

转载 作者:行者123 更新时间:2023-12-02 01:05:38 27 4
gpt4 key购买 nike

我有一个想要测试的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 行是哪一行?

关于java - 如何测试 resp.getOutputStream(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57732625/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com