我有一个控制器:
@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";
}
这个控制器有一个将书籍添加到数据库的方法。方法具有params="add"值的@RequestMapping注释。
我正在尝试将此参数标准设置为控制器单元测试方法:
@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.sperform(post("/bookForm","add")
根本不起作用。
以下内容应该有效。
mockMvc.perform(post("/bookForm?add="))
使用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();