Spring mvc 单元测试 - 磁贴视图的不同 forwardedUrl() 模式

Spring mvc unit testing - different forwardedUrl() pattern for tiles views

我正在为使用图块的 spring 应用程序编写单元测试,对于一个控制器,forwardedUrl 与视图名称不同,对于另一个控制器,它们是相同的,但据我所知一切都是这样连上也是一样。

谁能告诉我为什么?

我有一个控制器方法:

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView root(Locale locale, Model model) {
    ModelAndView mv = new ModelAndView("base/index/view");
    mv.addObject("display_title", "Home");

    return mv;
}

及其单元测试:

@Test
public void testApplicationRootUrl() throws Exception {
mockMvc.perform(get("/"))
    .andExpect(status().isOk())
    .andExpect(view().name("base/index/view"))
    .andExpect(forwardedUrl("/WEB-INF/views/base/index/view.jsp"));         
}

forwardedUrl 是 /WEB-INF/views/base/index/view。jsp 所以我希望相同的模式适用于另一个控制器。

这里我有另一种控制器方法(在不同的控制器中):

@RequestMapping(value = "/products", method = RequestMethod.GET)
public ModelAndView getAllProducts(Locale locale, Model model) {
    logger.info("Getting all products");

    List<Product> allProducts = productService.getAllProducts();

    ModelAndView mv = new ModelAndView("base/product_list/view");

    mv.addObject("products", allProducts);

    return mv;
}

单元测试:

@Test
public void testGetAllProducts() throws Exception {
    when(productService.getAllProducts()).thenReturn(getAllProducts());

    mockMvc.perform(get("/products"))
    .andExpect(status().isOk())
    .andExpect(view().name("base/product_list/view"))
    .andExpect(forwardedUrl("/WEB-INF/views/base/product_list/view.jsp"))
    .andExpect(model().attributeExists("products"))
    .andExpect(model().attribute("products", hasSize(1)))
    .andExpect(model().attribute("products", hasItem(
                                    allOf(
                                        hasProperty("id", is(1)),
                                        hasProperty("productName", is("Yellow")),
                                        hasProperty("material", is("Wood"))
                                    )
    )));

    verify(productService, times(1)).getAllProducts();  
}

此测试因以下断言错误而失败,这是我不理解的,因为整个应用程序都使用了 tile,因此我希望 forwardedUrl 在模式方面保持一致:

java.lang.AssertionError: Forwarded URL expected:</WEB-INF/views/base/product_list/view.jsp> but was:<base/product_list/view>

如果在极少数情况下有人对此感到疑惑并想知道答案,那是因为为测试创建 mockMvc 对象的方式不同。

对于没有模拟服务的导航测试,我使用的是 WebApplicationContext:

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
    mockMvc =   MockMvcBuilders.webAppContextSetup(this.wac).build();        
}

但是对于需要模拟服务的其他测试,我使用 Mockito 和 standaloneSetup 来构建 mockMvc 对象:

@Mock
private ProductService productService;

@InjectMocks
private ProductController productController;

private MockMvc mockMvc;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);  
    mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
}

似乎他们 return 不同的 forwardedUrl,尽管整个过程中都使用了 tile,并且实际控制器没有区别,只是在测试中。