Issue
I am using spring boot and I have a RestController with method
addBook(@Validated @RequestBody BookDto bookDto)
BookDto has a field annotated with write only
@JsonProperty(access = Access.WRITE_ONLY)
@NotNull(message = "cannot be empty")
@Size(min = 1, max = 20)
private String isdnNo;
This works as expected and I have to provide isdnNo while i do a post request. And when I get it don't bring the isdnNo in reponse which is fine. Issue here is in JUnit test case. I am using stand alone setup to test controller.
MockMvcBuilders.standaloneSetup(bookController).build();
MockHttpServletRequestBuilder postRequest = MockMvcRequestBuilders.post("/books/").contentType(JSON)
.accept(JSON);
postRequest.content(asJsonString(bookDto));
ResultActions result = mvc.perform(postRequest);
This JUnit test case gives exception org.springframework.web.bind.MethodArgumentNotValidException
and says idnNo cannot be empty even though I have provided isdnNo in bookDto on performing post. What can be the issue here.
if I remove @JsonProperty(access = Access.WRITE_ONLY)
the test case works fine.
Thanks in advance !
Solution
You want to keep Access.WRITE_ONLY
removed because, according to the documentation, during serialization (ie writing it to a string) it will not read the value for serialization. You're method asJsonString is serializing the object thus removing the value.
AUTO:
Access setting which means that visibility rules are to be used to automatically determine read- and/or write-access of this property.
READ_ONLY:
Access setting that means that the property may only be read for serialization, but not written (set) during deserialization.
READ_WRITE
Access setting that means that the property will be accessed for both serialization (writing out values as external representation) and deserialization (reading values from external representation), regardless of visibility rules.
WRITE_ONLY
Access setting that means that the property may only be written (set) for deserialization, but will not be read (get) on serialization, that is, the value of the property is not included in serialization.
Answered By - locus2k
Answer Checked By - Clifford M. (JavaFixing Volunteer)