【发布时间】: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