2015-11-04 113 views
1

我试图使用Spring测试MVC测试控制器方法。春季测试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是正确的,但第二个控制器似乎没有执行?

+0

你能添加更多信息吗?就像控制器代码一样,不是完整的代码,而是方法定义,模型的改变以及方法与视图的返回。 – reos

+0

我添加了您请求的信息。 –

回答

0

我不知道,但我假设是:

你有这样的路径与控制器

/admin/gateway/config/parameter/ 

联系人,这条路径可欣赏

/admin/gateway/config/template/ 

如果产生密切相关是真的,你重定向到一个视图

return "redirect:/admin/gateway/config/template/details" + newTemplate.getId()+ "#tab_3"; 

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

+0

但我似乎仍然在空模型属性上得到thymeleaf异常。 所以现在我只是专注于测试第一个控制器,然后在第二个阶段看第二个控制器。 –