1

Can you help me? I need to test this controller method. But don't know what to do with httpservletresponse object.

@Controller
public class HomeController {

    @PostMapping("/signout")
    public String signOut(HttpServletResponse response){
        response.addCookie(new Cookie("auth-token", null));
        return "redirect:http://localhost:3000";
    }
}

Thank you)

1

1 Answer 1

1

Spring MVC Test provides an effective way to test controllers by performing requests and generating responses through the actual DispatcherServlet.


import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;

@RunWith(SpringRunner.class)
@WebMvcTest(controllers=HomeController.class)
public class HomeControllerTest {

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void testSignOut() throws Exception {

        mockMvc.perform(post("/signout"))
            .andDo(print())
            .andExpect(new ResultMatcher() {                
                @Override
                public void match(MvcResult result) throws Exception {              
                    Assert.assertEquals("http://localhost:3000",result.getResponse().getRedirectedUrl());
                }
            });

    }

}

In case of Spring MVC without spring boot, use standalone MockMvc support

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration // or @ContextConfiguration
public class HomeControllerTest{

    @Autowired
    private HomeController homeController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        // Setup Spring test in standalone mode
        this.mockMvc = 
          MockMvcBuilders.standaloneSetup(homeController).build();
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, But the problem is httpservletresponse. I don't know how to pass it)
I have mocked response and I need to pass it and check if method addCookie was invoked
You can do response.getCookies and verify the response. You could also use Mockito.verify to check addCookie was called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.