【问题标题】:Mockito: HttpServeletRequest return mock Cookie not working as expectedMockito:HttpServeletRequest 返回模拟 Cookie 未按预期工作
【发布时间】:2019-07-18 20:23:48
【问题描述】:

我有一个方法hello(HttpServletRequest request) 需要进行单元测试。在这种方法中,我做了类似Cookie cookie = WebUtils.getCookie(request, cookie_name) 的事情。所以基本上,我在这里提取cookie并做我的事情。这是我的测试类的样子:

@Test
public void testHello() {
    Cookie cookie = new Cookie(cookie_name, "");
    Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
    Mockito.when(WebUtils.getCookie(request, cookie_name)).thenReturn(cookie);
    // call the hello(request) and do assert
}

因此,每当我尝试模拟并返回此 cookie 时,我的堆栈跟踪中都会出现类似的结果。

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Cookie cannot be returned by getCookies()
getCookies() should return Cookie[]
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

WebUtils.getCookie() 内部,它基本上执行request.getCookies() 并迭代数组以获得正确的数组。这个 WebUtils 来自 Spring Web。正如你所看到的,我也为此返回了一些价值。仍然收到此错误。有没有人遇到过这个问题?我该如何解决这个问题?

【问题讨论】:

  • WebUtils.getCookie() 是一个静态方法。您将无法使用 Mockito 模拟它。此外,如果您已经模拟了请求对象,然后为 request.getCookies 方法创建了一个存根,那么您不需要再次存根 WebUtils.getCookie() 方法。
  • 无法理解存根是什么意思。你能链接一些例子或展示它是如何完成的吗?

标签: spring-mvc cookies mockito


【解决方案1】:

跟进@Ajinkya 的评论,我想这就是他想要表达的:


getCookie 方法可能看起来像这样(我只是使用了它的某个版本,因此您使用的版本可能有所更改)

public static Cookie getCookie(HttpServletRequest request, String name) {
        Assert.notNull(request, "Request must not be null");
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

由于您模拟了您的请求,因此您可以控制 getCookies() 返回的内容。 要使这个方法工作(不模拟它),你只需要从 getCookies() 返回一个模拟而不是真正的 Cookie。

    Cookie mockCookie = Mockito.mock(Cookie.class);
    Mockito.when(mockCookie.getName()).thenReturn(cookie_name);    

    Mockito.when(request.getCookies()).thenReturn(new Cookie[]{mockCookie});    

把它改成这个,静态方法就可以照常工作了。
你不需要费心去模拟它。

【讨论】:

  • 谢谢@second。这正是我的意思。
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 2018-10-19
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 2015-06-02
相关资源
最近更新 更多