gpt4 book ai didi

java - Mockito when...thenResult 总是返回 null

转载 作者:行者123 更新时间:2023-11-30 10:51:40 26 4
gpt4 key购买 nike

使用上面的代码,我总是在测试行中出错

when(request.getServletContext().getAttribute("SessionFactory"))
.thenReturn(factory);

有什么想法吗?

Java 类

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory");
...............
}

测试类

 @Test
public void testServlet() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);


factory = contextInitialized();
when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory); //Always error here
when(request.getParameter("empId")).thenReturn("35");
PrintWriter writer = new PrintWriter("somefile.txt");
when(response.getWriter()).thenReturn(writer);

new DeleteEmployee().doGet(request, response);

verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
writer.flush(); // it may not have been flushed yet...
assertTrue(FileUtils.readFileToString(new File("somefile.txt"), "UTF-8")
.contains("My Expected String"));
}

最佳答案

when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory);

这个位:

request.getServletContext().getAttribute("SessionFactory")

是链式调用;您正在尝试对请求和请求返回的 servlet 上下文进行 stub 。

你可以这样做,但你需要使用 deep stubs :

HttpServletRequest request = mock(HttpServletRequest.class, RETURNS_DEEP_STUBS);

关于java - Mockito when...thenResult 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623142/

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