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

时间:2019-07-18 20:23:48

标签: spring-mvc cookies 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
}

因此,每当我尝试模拟并返回此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。如您所见,我也为此返回了一些值。仍然出现此错误。有人遇到过这个问题吗?我该如何解决?

1 个答案:

答案 0 :(得分:2)

在@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});    

将其更改为静态方法可以照常完成其工作。
您无需费心对其进行模拟。