我正在尝试使用 Spring Test MVC 来测试 Controller 方法。
我有一个 Controller ,用于处理表单提交并将新条目保存到数据库中。
如果该方法成功, Controller 将执行到另一个 Controller 的重定向(第二个 Controller 从路径变量检索实体的 ID,从数据库检索它,填充模型属性并显示新持久实体的详细信息页面)。
在第一个 Controller 中,没有将任何属性添加到模型或 RedirectAttributes 上。
这是我尝试测试的 Controller 方法:
@RequestMapping("/save/{templateId}/{configParameterId}")
public String saveGatewayPPTPConfigParameter(@PathVariable Long templateId, @PathVariable Long configParameterId, @Valid GatewayPPTPConfigParameterForm configParameterForm, BindingResult bindingResult, HttpServletRequest request,
RedirectAttributes flash, Model model) {
...
...
... Code omitted
...
return "redirect:/admin/gateway/config/template/details" + newTemplate.getId()+ "#tab_3";
}
如果此方法成功执行,那么第二个 Controller 中的以下代码将使用一些属性填充模型:
@RequestMapping(value = "/details/{templateId}", method = RequestMethod.GET)
public String viewConfigTemplateDetails(@PathVariable Long templateId, Model model) throws IOException, ServletException, WifireAdminSessionException, WifireAdminException {
....
....
....Code ommited
....
....
model.addAttribute("configTemplate", gatewayConfig);
return "/admin/gateway/config/template/details";
}
考虑我的测试中的这段代码:
mvc.perform(
post("/admin/gateway/config/parameter/save/{templateId}/{configParameterId}", 6 , 8)
.param("name", "name")
.param("value", "value")
.param("typeId", "3")
.param("parameterId", "2")
.param("readOnly", "false"))
.andDo(
MockMvcResultHandlers.print()
)
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/admin/gateway/config/template/details/"+mapping.getId()+"#tab_3"));
这个测试通过了,但是如果我添加:
.andExpect(model().attribute("configTemplate", hasProperty("id",is(4l))))
由于 configTemplate
模型属性为 null,因此失败。
如果第二个 Controller 已成功执行,则将填充configTemplate
。为什么expectedView
是正确的,但第二个 Controller 似乎没有执行?
最佳答案
我不确定,但我假设:
您将此路径与 Controller 关联
/admin/gateway/config/parameter/
这条路径与 View 相关
/admin/gateway/config/template/
如果这是真的,您将重定向到 View
return "redirect:/admin/gateway/config/template/details" + newTemplate.getId()+ "#tab_3";
第二个 Controller 从未执行,这是因为您重定向的结果 View 从未执行。因此,如果您检查预期 View 是否正确,但 Controller 从未执行。
关于java - Spring 测试MVC : Testing controller that redirects to another controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33520481/