Spring Test MVC:测试重定向到另一个控制器的控制器

时间:2015-11-04 11:19:01

标签: java spring unit-testing spring-mvc

我正在尝试使用Spring Test MVC来测试控制器方法。

我有一个处理表单提交的控制器,并持有一个新的数据库条目。

如果方法成功,则控制器执行重定向到另一个控制器(第二个控制器从路径变量中检索实体的ID,从数据库中检索它,填充模型属性并显示新的详细信息页面坚持实体)。

在第一个控制器中,没有属性添加到Model或RedirectAttributes。

这是我试图测试的控制器方法:

@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";
    }

如果此方法成功执行,则第二个控制器中的以下代码将使用某些属性填充模型:

@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模型属性为空。

如果第二个控制器已成功执行,则将填充configTemplate。为什么expectedView是正确的,但第二个控制器似乎没有执行?

1 个答案:

答案 0 :(得分:0)

我不确定,但我假设:

您有此路径与控制器相关联

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

此路径与视图相关

/admin/gateway/config/parameter/

如果是这样,您将重定向到视图

/admin/gateway/config/template/

第二个控制器从未执行过,这是因为您重定向的结果视图从未执行过。因此,如果您检查预期视图是否正确,但控制器永远不会执行。

相关问题