Killer Beast
Killer Beast

Reputation: 499

Mocked HttpServletRequest not returning expected method value

I have a filter in Spring that does some logic based on Method type of the incoming request. Below is the filter code:

public class TestFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (HttpMethod.GET.equals(httpRequest.getMethod())) {
            // do something
        } else {
            // do something else
        }
        chain.doFilter(request, httpResponse);
    }
}

In the above code, I am trying to set some header in my response called GETHEADER whenever the request method is GET whereas it doesn't happen in POST.

And I am trying to test it using the below testcase code:

@Mock
HttpServletResponse response;

@Mock
HttpServletRequest request;

@Mock
FilterChain chain;

@Autowired
TestFilter testFilter;

@Test
public void testGetRequest() throws Exception {
    when(request.getMethod()).thenReturn(HttpMethod.GET.toString());
    testFilter.doFilter(request, response, chain);
    Assert.assertNotNull(response.getHeader("GETHEADER"));
}

In my code coverage, I can only see the else part being executed but never the if part. Is it not returning the value I try to supply or is there some problem with how I am returning?

UPDATE: Tried these as below:

code: if (HttpMethod.GET.toString().equals(httpRequest.getMethod()))

testcase: when(request.getMethod()).thenReturn(HttpMethod.GET.toString())

also

code: if ("GET".toString().equals(httpRequest.getMethod()))

testcase: when(request.getMethod()).thenReturn("GET")

Upvotes: 0

Views: 289

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

An enum value is never equal to a String. HttpMethod.GET is an enum value. httpRequest.getMethod() is a String.

Upvotes: 1

Related Questions