Mockito when...thenResult 总是返回 null [英] Mockito when...thenResult always returns null

查看:232
本文介绍了Mockito when...thenResult 总是返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With the above code I always get an error in line of test

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 上下文.

is a chained call; you're trying to stub both the request, and the servlet context that the request returns.

您可以这样做,但您需要使用 深存根:

You can do that, but you need to use deep stubs:

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

这篇关于Mockito when...thenResult 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆