首页 > 解决方案 > 如何使用 http 响应参数测试 mvc 控制器方法?

问题描述

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

@Controller
public class HomeController {

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

谢谢)

标签: javaspringspring-mvcjunit

解决方案


Spring MVC Test通过执行请求并通过实际的 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没有 Spring Boot,请使用独立的 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();
    }

推荐阅读