Java 如何在控制器测试中设置重定向属性

Java 如何在控制器测试中设置重定向属性,java,unit-testing,spring-mvc,model-view-controller,Java,Unit Testing,Spring Mvc,Model View Controller,我需要测试我的控制器方法 @RequestMapping(path="/add", method = RequestMethod.POST) public RedirectView addToCart(@ModelAttribute(value="productId") long productId, @ModelAttribute(value="quantity") int quantity, RedirectAttributes redirectAttributes) throws Prod

我需要测试我的控制器方法

@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错误消息,我想这是因为在我的控制器方法中,我尝试使用RedirectedAttribute,但它是空的。所以,我必须在哪里以及如何在测试中初始化和设置RedirectedAttribute?

问题不在RedirectAttributes中,而是sCart Mock未初始化。 我相信您不需要像其他参数一样在请求时提供重定向属性