【问题标题】:How to test mvc controller method with http response argument?如何使用 http 响应参数测试 mvc 控制器方法?
【发布时间】:2019-06-25 19:45:31
【问题描述】:

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

@Controller
public class HomeController {

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

谢谢)

【问题讨论】:

标签: java spring spring-mvc junit


【解决方案1】:

Spring 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 没有 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();
    }

【讨论】:

  • 谢谢,但问题是 httpservletresponse。我不知道如何通过它)
  • 我已经模拟了响应,我需要传递它并检查是否调用了方法 addCookie
  • 您可以执行 response.getCookies 并验证响应。你也可以使用 Mockito.verify 来检查 addCookie 是否被调用。
猜你喜欢
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
相关资源
最近更新 更多