Home > Net >  Mock return value for cookie.getValue() using Mockito
Mock return value for cookie.getValue() using Mockito

Time:01-02

I'm trying to test the getCookieByName method which is used by another method. However, not sure I'm doing this correctly as it seems the method is being called multiple times and it sets the value the first attempt but then is empty on the last call. I think maybe the order for the mock calls may be wrong or some of them may not be needed, but if I remove any of what I still get other errors, so not sure what I'm actually doing wrong.

@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 "";
}

These are my test and mock calls as well as the two times getCookieByName() is being called within the same method.

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

enter image description here

enter image description here

Thank you.

CodePudding user response:

I was using the wrong object under the assertion. The @httpRequest is annotated with @MockBean, whereas request uses @Mock, which is what I should be using for this scenario.

  • Related