gpt4 book ai didi

java - 如何使用 MockMvc 对象测试使用 Post 方法检索数据的 Controller ?

转载 作者:行者123 更新时间:2023-11-30 08:06:36 25 4
gpt4 key购买 nike

大家好,我正在使用 Spring MVC 框架,我想测试我的 Controller 。其中之一使用 Post 方法从 View 中检索数据,但我不知道如何测试它。

这是我的 Controller :

@RequestMapping(value="/index", method=RequestMethod.POST)
public String postMessage(@RequestParam("newLetter") String lttr, Model model)
{
Letter newLetter = lttr;
this.letterService.insertLetter(newLetter);
this.allLetters = this.letterService.getAllLetters();
model.addAttribute("allLetters", this.allLetters);
return "redirect:/index";
}

这是我尝试过的测试,但显然不起作用。

@Test
@WithMockUser("randomUser")
public void aTest() throws Exception
{
Letter lttr = new Letter();
mockMvc.perform(post("/index").with(testSecurityContext()))
.andExpect(status().isOk())
.requestAttr("newLetter", lttr)
.andExpect(model().attributeExists("allLetters"));
}

最佳答案

我想你想要:

mockMvc.perform(post("/index").with(testSecurityContext())
.param("newLetter", lttr))
.andExpect(status().isOk())
.andExpect(model().attributeExists("allLetters"));

注意第三行的 param 而不是 requestAttr。它是您要在 Controller 方法中查找的参数,带有 @RequestParam 注释,而不是属性。

关于java - 如何使用 MockMvc 对象测试使用 Post 方法检索数据的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com