簡體   English   中英

如何在控制器測試中設置RedirectAttributes

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM