簡體   English   中英

如何使用MockMvc對象測試使用Post方法檢索數據的Controller?

[英]How to test a Controller, which retrieves data with Post method, using a MockMvc object?

大家好,我正在使用Spring MVC框架,並且我想測試我的控制器。 其中之一使用Post方法以便從View檢索數據,但我不知道如何對其進行測試。

這是我的控制器:

@RequestMapping(value="/index", method=RequestMethod.POST)
public String postMessage(@RequestParam("newLetter") String lttr, Model model)
{
    Letter newLetter = lttr;
    this.letterService.insertLetter(newLetter);
    this.allLetters = this.letterService.getAllLetters();
    model.addAttribute("allLetters", this.allLetters);
    return "redirect:/index";
}

這是我嘗試過的測試,顯然不起作用。

@Test
@WithMockUser("randomUser")
public void aTest() throws Exception
{
    Letter lttr = new Letter();
    mockMvc.perform(post("/index").with(testSecurityContext()))
                                    .andExpect(status().isOk())
                                    .requestAttr("newLetter", lttr)
                                    .andExpect(model().attributeExists("allLetters"));
}

我想你要:

mockMvc.perform(post("/index").with(testSecurityContext())
                              .param("newLetter", lttr))
                              .andExpect(status().isOk())
                              .andExpect(model().attributeExists("allLetters"));

注意param而不是第三行的requestAttr 這是您要在控制器方法中尋找的參數,帶有@RequestParam批注,而不是屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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