我有一个控制器:
@Controller
@RequestMapping(value = "/bookForm")
public class BookFormController {
@Autowired
private BookHttpRequestParser parser;
@Autowired
private BooksService booksService;
@RequestMapping(params = "add", method = RequestMethod.POST)
public String addBook(HttpServletRequest request) {
try {
Book newBook = parser.createBookFromRequest(request);
booksService.addBook(newBook);
} catch (InvalidTypedParametersException e) {
}
return "redirect:index.html";
}
此Controller具有向DB添加书籍的方法。方法的@RequestMapping注释带有 params =“add”值。
我试图将此params标准设置为控制器单元测试方法:
@Test
public void addBook() throws Exception{
HttpServletRequest request = mock(HttpServletRequest.class);
Book book = new Book();
when(parser.createBookFromRequest(request)).thenReturn(book);
mockMvc.perform(post("/bookForm", "add"))
.andExpect(status().isOk())
.andExpect(view().name("redirect:index.html"));
}
在哪里指定@ResuetsMapping参数值?
这:
mockMvc.perform(post(“/ bookForm”,“add”))
根本不起作用。
答案 0 :(得分:0)
以下情况应该有效。
mockMvc.perform(post("/bookForm?add="))
答案 1 :(得分:0)
使用RequestBuilder requestBuilders;
构建请求的对象
requestBuilders = MockMvcRequestBuilders.get("URL/{Pathvariable}","PathvariableValue")
.contentType(MediaType.APPLICATION_JSON)
.header("HeaderName", HeaderValue)
.param("ParameterName", "Value")
.param("ParameterName", "Value")
.accept(MediaType.APPLICATION_JSON);
和性能
mockMvc.perform(requestBuilders)
.andDo(print())
.andExpect(status().isOk())
.andReturn();