![](/img/trans.png)
[英]How to test that method has added redirectAttributes ?(by MockMvc)
[英]How set RedirectAttributes in Controller Test
我需要测试我的控制器方法
@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,但它为null。 因此,在测试中必须在何处以及如何初始化和设置RedirectedAttributes?
问题不在RedirectAttributes中,有sCart Mock未初始化。 我相信您不需要将RedirectAttributes与其他参数一起提供给请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.