如何在Controller Test中设置RedirectAttributes

时间:2016-08-14 11:16:34

标签: 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 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。那么,在我的测试中,我必须在何处以及如何设置RedirectedAttribute?

1 个答案:

答案 0 :(得分:0)

RedirectAttributes中没有问题,sCart Mock未初始化。 我相信你不需要像其他参数那样给出RedirectAttributes请求。