Initially, I'm using MockMvc in Java Spring Boot Junit testcase. I'm sending a JSON with a message as Success {"message": "Success"}, if the message is not Success, without throwing an AssertionError Exception. It should check the message Failure statement which is under the catch block.
Without adding the catch block statement, Is there any feasible way to get Success,Failure scenario together. Below code explains what I have tried,
@Test
public void test() throws Exception {
try {
result = mockMvc.perform(post("/test/{testId}", "44")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"order\": \"desc\"}")
.accept(MediaType.APPLICATION_JSON)).andExpect(status().is(200))
.andExpect(jsonPath("message").value("Success"))
.andReturn();
} catch (AssertionError e) {
result = mockMvc.perform(post("/test/{testId}", "44")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"order\": \"desc\"}")
.accept(MediaType.APPLICATION_JSON)).andExpect(status().is(200))
.andExpect(jsonPath("message").value("Failure"))
.andReturn();
}
}
Try this
result = mockMvc.perform(post("/test/{testId}", "44")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"order\": \"desc\"}")
.accept(MediaType.APPLICATION_JSON)).andExpect(status().is(200))
.andExpect(jsonPath("message").value(org.hamcrest.CoreMatchers.anyOf(is("Failure"), is("Success"))))
.andReturn();
But I would suggest you try splitting these test cases into separate tests as Martin did.