我有一个带POST方法的控制器进行测试。该方法将书籍发布到读者的阅读清单。它将抓取当前经过身份验证的用户作为阅读器。 Book
类的字段为Reader
类型。以下代码使用contains(samePropertyValuesAs(expectedBook))
,但reader
实例位置与我明显创建的expectedReader
不同。
在MockMVC中测试这种嵌套对象的正确方法是什么?
@Test
@WithUserDetails("z")
public void addBookShouldShowTheBookInReadingList() throws Exception {
final String bookTitle = "BOOK A";
final String bookAuthor = "JK";
final String isbn = "1234567890";
final String description = "Yet another book.";
mockMvc.perform(post("/readingList")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("title", bookTitle)
.param("author", bookAuthor)
.param("isbn", isbn)
.param("description", description)
.with(csrf()))
.andExpect(status().is3xxRedirection())
.andExpect(header().string("Location", "/readingList"));
Reader expectedReader = new Reader();
expectedReader.setUsername("z");
expectedReader.setPassword("test");
expectedReader.setFullName("Z H");
Book expectedBook = new Book();
expectedBook.setId(1L);
expectedBook.setTitle(bookTitle);
expectedBook.setAuthor(bookAuthor);
expectedBook.setIsbn(isbn);
expectedBook.setDescription(description);
expectedBook.setReader(expectedReader);
mockMvc.perform(get("/readingList"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("books"))
.andExpect(model().attribute("books", hasSize(1)))
.andExpect(model().attribute("books", contains(samePropertyValuesAs(expectedBook))));
}
更新 - 其他POST签名。
@Controller
@RequestMapping(value = "/readingList")
public class ReadingListController {
private ReadingListService readingListService;
private VersionConfig versionConfig;
@Autowired
public ReadingListController(final ReadingListService readingListService,
final VersionConfig versionConfig) {
this.readingListService = readingListService;
this.versionConfig = versionConfig;
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String readersBooks(Reader reader, Model model) {
readingListService.findByReader(reader)
.ifPresent(books -> {
model.addAttribute("books", books);
model.addAttribute("reader", reader);
model.addAttribute("releaseId", versionConfig.getReleaseId());
});
return "readingList";
}
@RequestMapping(value = "", method = RequestMethod.POST)
public String addToReadingList(Reader reader, Book book) {
book.setReader(reader);
readingListService.save(book);
return "redirect:/readingList";
}
}
答案 0 :(得分:0)
因此可以在hamcrast中使用hasToString()
匹配器来完成此任务。
mockMvc.perform(get("/readingList"))
.andExpect(status().isOk())
.andExpect(model().attributeExists("books"))
.andExpect(model().attribute("books", hasSize(1)))
.andExpect(model().attribute("books", contains(hasToString(expectedBook.toString()))));