Home>
In trouble

I'm trying to test a Servlet class and request.setAttribute() does not call the original method.

  @Test
    public void testDoPostWithoutInputs() {
        HttpServletRequest request = spy(HttpServletRequest.class);
        request.setAttribute("hoge", "fuga");
        System.out.println(request.getAttribute("hoge"));
    }


My understanding is that if you use spy, the implementation of the original method is called as it is, unless you mock the method, so in the above code, i am expecting "fuga" output by System.out.println(). I will.

But it actually displays null.

Is there something wrong?
Maybe it's because of my misrecognition of spy, or because setAttribute() is called correctly, but I don't understand its internal implementation.

We apologize for the inconvenience, but we would appreciate it if you could answer.

  • Answer # 1

    HttpServletRequest is an interface, not an implementation.

    Whether to use MockHttpServletRequest etc. of spring-test
    Create your own MockHttpServletRequest.

    A method that does nothing

    Method that returns ull

    Will be implemented.