gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:00:11 24 4
gpt4 key购买 nike

我有一个方法 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。如您所见,我也为此返回了一些值。仍然收到此错误。有人遇到过这个问题吗?我该如何解决这个问题?

最佳答案

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

将其更改为此,静态方法可以像往常一样完成它的工作。
你不需要费心模拟它。

关于spring-mvc - Mockito:HttpServeletRequest 返回模拟 Cookie 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com