如何使用http响应参数测试MVC控制器方法?

时间:2019-02-01 08:54:50

标签: java spring spring-mvc junit

你能帮我吗?我需要测试此控制器方法。但是不知道如何处理httpservletresponse对象。

@Controller
public class HomeController {

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

谢谢)

1 个答案:

答案 0 :(得分:1)

<强>弹簧MVC测试按通过实际的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());
                }
            });

    }

}

对于 Spring MVC (没有弹簧启动),请使用独立的MockMvc支持

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