java - 如何使用 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";
}
}
谢谢)
解决方案
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();
}
推荐阅读
- apache-spark - 如何使用过滤器通过 spark 从 Greenplum 读取数据
- google-apps-script - 通过单元格引用更改电子表格名称 - Google 表格/应用程序脚本
- sql - 在 Azure 数据工厂的复制活动中每月自动更改日期,以将数据从 SAP HANA 复制到 Azure SQLDB
- php - 无法访问发布消息中的 html 表单数据 (PHP)
- javascript - useEffect 缺少依赖项:'user'
- python - Discord.py 如何从不和谐消息中读取 int 并将其作为变量发送到嵌入中
- python - 如何根据匹配列旋转数据框
- c++ - constexpr 构造函数不被称为隐式类型转换的 constexpr
- azure-ad-b2c - 收到的身份验证响应没有预期的 accessToken
- laravel - Laravel 显示“FPDF 错误:尚未添加页面”