Mockito:HttpServeletRequest 返回模拟 Cookie 未按预期工作

Kil*_*ast 5 cookies spring-mvc mockito

我有一个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
}
Run Code Online (Sandbox Code Playgroud)

因此,每当我尝试模拟并返回此 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.
Run Code Online (Sandbox Code Playgroud)

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

sec*_*ond 6

继@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;
    }
Run Code Online (Sandbox Code Playgroud)

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

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

    Mockito.when(request.getCookies()).thenReturn(new Cookie[]{mockCookie});    
Run Code Online (Sandbox Code Playgroud)

改成这样,静态方法就可以照常工作了。
你不需要费心去嘲笑它。