2016-08-14 1 views
1

Ich brauche meine Controller-MethodeWie Satz 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; 
} 

Mein Test-Code sieht aus wie testen:

@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)); 
} 

Aber ich bekomme NestedServledException Fehlermeldung, denke ich sein, weil in meiner Controller-Methode Ich versuche, mit RedirectedAttributes zu arbeiten, aber es ist null. Also, wo und wie muss ich RedirectedAttributes in meinem Test initiieren und setzen?

Antwort

0

Problem war nicht in RedirectAttributes, da war sCart Mock nicht initialisiert. Ich glaube, dass Sie nicht RedirectAttributes mit Anfrage als andere Parameter geben müssen.