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)

Daimon
  • 345
  • 1
  • 5
  • 21
  • see this answer https://stackoverflow.com/questions/5434419/how-to-test-my-servlet-using-junit – Lemmy Feb 01 '19 at 08:56

1 Answers1

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();
    }
Barath
  • 5,093
  • 1
  • 17
  • 42
  • Thanks, But the problem is httpservletresponse. I don't know how to pass it) – Daimon Feb 01 '19 at 09:58
  • I have mocked response and I need to pass it and check if method addCookie was invoked – Daimon Feb 01 '19 at 09:58
  • You can do response.getCookies and verify the response. You could also use Mockito.verify to check addCookie was called. – Barath Feb 01 '19 at 09:59