I try to write post api endpoint test with MockMvc that send multiple parameters including array of objects and I got this error.
java.lang.AssertionError: Status expected:<201> but was:<400>
with no error message(null) from MockHttpServletResponse.
I think the problem is about sending array of objects which request param model define it as List<Map<String, Object>>
but I can’t figure it out how to solve the problem.
Here is what I try.
Request body :
{
"study_class_id": 1,
"lecture_values": [
{
"topic": 1,
"content": "Lorem ipsum"
},
{
"topic": 2,
"content": "Lorem ipsum"
}
]
}
Controller :
@PostMapping(value = "/lecture")
public ResponseEntity<LecturesResource> addLecture(
@Valid @ModelAttribute("Lecture") LectureAddRequestParam param,
BindingResult bindingResult, Principal principal, HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
return processResult;
}
Request param model :
public class LectureAddRequestParam {
@NotNull
@Min(1)
private int study_class_id;
@NotNull
private List<Map<String, Object>> lecture_values;
// Getter Setter..
}
POST api endpoint test :
// Prepare lecture values param
JSONObject lecture1 = new JSONObject();
lecture1.put("topic", 1);
lecture1.put("content", "Lorem ipsum");
JSONObject lecture2 = new JSONObject();
lecture2.put("topic", 2);
lecture2.put("content", "Lorem ipsum");
JSONArray lectureValues = new JSONArray();
lectureValues.add(lecture1);
lectureValues.add(lecture2);
var responseContent = mockMvc
.perform(
post("/lecture")
.with(csrf())
.param("study_class_id", Integer.toString(studyClassId))
.param("lecture_values", lectureValues.toString()))
.andDo(log())
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getContentAsString();
Request call is success with jQuery ajax :
$.ajax({
url: '/lecture',
type: 'POST',
timeout: this.TIMEOUT_LIMIT,
headers: requestHeader,
data: {
study_class_id: study_class_id,
lecture_values: lecture_values.toJSON()
}
});
the reason here using toJSON() is because it is Backbone.js collection.
I’ve also tried with flashAttr. I create lectureJSONObject that contain
- int study_class_id
- json array objects of lecture_values
flashAttr("lecture", lectureJSONObject)
And tried creating Lecture class that contain
- int study_class_id
- List<Map<String, Object>> lecture_values
by convert jsonarray object to List<Map<String, Object>>
flashAttr("lecture", lectureObject)
add send it with flashAttr but both are not working and there’s no error message.
MMT Yuma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.