1
我需要测试我控制器的方法怎么设置RedirectAttributes
@RequestMapping(path="/add", method = RequestMethod.POST)
public RedirectView addToCart(@ModelAttribute(value="productId") long productId, @ModelAttribute(value="quantity") int quantity, RedirectAttributes redirectAttributes) throws ProductNotFoundException {
RedirectView redirect = new RedirectView("/product/");
redirect.setExposeModelAttributes(false);
try {
redirectAttributes.addFlashAttribute("flash", shoppingCartService.addQuantity(sCart, productId, quantity));
} catch (ExceedsProductQuantityException e) {
e.printStackTrace();
redirectAttributes.addFlashAttribute("flash", new FlashMessage(e.getMessage(), FlashMessage.Status.FAILURE));
}
return redirect;
}
我的测试代码如下所示:
@Test(expected = ExceedsProductQuantityException.class)
public void addTooManyToCartTest1() throws Exception {
Product product = productBuilder();
product.setQuantity(15);
Purchase purchase = purchaseBuilder(product); // First purchase
when(productService.findById(1L)).thenReturn(product);
when(sCart.getPurchase()).thenReturn(purchase);
mockMvc.perform(MockMvcRequestBuilders.post("/cart/add")
.param("quantity", String.valueOf(product.getQuantity() + 1))
.param("productId", "1"))
.andExpect(MockMvcResultMatchers.model().attribute("flash", "rdValue"))
.andExpect(MockMvcResultMatchers.flash().attribute("flash", FlashMessage.class));
}
,但我得到NestedServledException错误信息,我认为它是因为在我的控制方法我尝试使用RedirectedAttributes,但它是空的。那么,我在哪里以及如何在我的测试中初始化和设置RedirectedAttributes?