使用 Mockito 模拟 cookie.getValue() 的 return 值

Mock return value for cookie.getValue() using Mockito

我正在尝试测试另一个方法使用的 getCookieByName 方法。但是,不确定我是否正确执行此操作,因为该方法似乎被多次调用并且它在第一次尝试时设置了值,但在最后一次调用时为空。我认为模拟调用的顺序可能有误,或者其中一些可能不需要,但如果我删除任何内容,我仍然会遇到其他错误,所以不确定我到底做错了什么。

@Service
public class CookieSessionUtils {

private static final String VIADUCT_LOCAL_AMP = "viaductLocalAmp"; // Value to be changed when the test runs to test the "if Y" scenario.


public boolean verifyState(HttpServletRequest request, String state) {

    String viaductLocalAmp = getCookieByName(request, VIADUCT_LOCAL_AMP); 

    if (viaductLocalAmp.equalsIgnoreCase("Y")) {
        return true;
    }

    return false;
}

public String getCookieByName(HttpServletRequest request, String cookieName) {
    try {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    return cookie.getValue();
                }
            }
        }
    } catch (Exception e) {
        ExceptionLogger.logDetailedError("CookieSessionUtils.getCookieByName", e);
        log.error("Error on Cookie " + e.getMessage());
    }
    return "";
}

这些是我的测试和模拟调用,以及在同一方法中两次调用 getCookieByName()。

@Autowired
private CookieSessionUtils cookieSessionUtils;

@Mock
private HttpServletRequest request;

   @Test
public void testVerifyStateWhenCookieNameStartsWithY() {

    Cookie mockCookie = Mockito.mock(Cookie.class);
    when(mockCookie.getName()).thenReturn("viaductLocalAmp");
    when(mockCookie.getValue()).thenReturn("viaductLocalAmp");

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

    when(cookieSessionUtils.getCookieByName(request, "viaductLocalAmp")).thenReturn("Y");

    assertTrue(cookieSessionUtils.verifyState(httpServletRequest, "viaductLocalAmp"));
}

谢谢。

我在断言下使用了错误的对象。 @httpRequest 使用@MockBean 注释,而请求使用@Mock,这是我应该在这种情况下使用的。