java - How to test nested Object in with Spring MockMVC? -
i have controller post method test. method post book reader's reading list. grab authenticated user reader. book
class has field reader
type. following code uses contains(samepropertyvaluesas(expectedbook))
, reader
instance location different expectedreader
created obviously.
what correct way test such nested object in 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 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)))); }
update - additional post signature.
@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"; } }
so there hastostring()
matcher used in hamcrast done.
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()))));
Comments
Post a Comment