Hi I have a boolean variable in my class and I was trying to post this class in my spring boot testing.
However I encountered error as below:
2020-07-21 03:42:11.590 WARN 11660 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'spbrResponse' on field 'isSuccess': rejected value [null]; codes [typeMismatch.spbrResponse.isSuccess,typeMismatch.isSuccess,typeMismatch.boolean,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spbrResponse.isSuccess,isSuccess]; arguments []; default message [isSuccess]]; default message [Failed to convert value of type 'null' to required type 'boolean'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [@com.fasterxml.jackson.annotation.JsonProperty boolean] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type]]
The boolean field is called isSuccess and I already have getter and setter method:
public class SpbrResponse<T> {
private boolean isSuccess;
private T result;
private String error;
public void setIsSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public boolean getIsSuccess() {
return isSuccess;
}
}
In unit testing I use ObjectMapper to convert object into JSON:
ReportGenerationResponse response = new ReportGenerationResponse(1, 1, 1, 1, "xx", "yy", "zz");
SpbrResponse<ReportGenerationResponse> wrappedResponse = new SpbrResponse<>(true, response, "");
mockMvc.perform(
post("/ReportComplete")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(wrappedResponse))
)
.andExpect(status().isOk());
I also tried to use
but all failed. Any help is highly appreciated.
The correct answer would be using @JsonProperty annotation. I tried to use this at first but in a wrong way. Correct syntax would be:
public class SpbrResponse<T> {
@JsonProperty("isSuccess")
private boolean isSuccess;
private T result;
private String error;
}