0

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();

    }

}
jreznot
  • 2,694
  • 2
  • 35
  • 53
Lakshan G
  • 366
  • 3
  • 9
  • 7
    You should really consider splitting those scenarios. It's good practice to have a test for each case / scenario – Martín Zaragoza Aug 22 '18 at 13:06
  • what is returned from the controller in case when it is not success? – pvpkiran Aug 22 '18 at 13:06
  • It returns the JSON as follows, { "message": "Failure" } – Lakshan G Aug 22 '18 at 13:30
  • @MartínZaragoza In my scenario I have to PASS the test class even if the JSON returns Failure {"message": "Failure"}. Is there any possibility to put .andExpect statement after returning(.andReturn()) the (MvcResult) result – Lakshan G Aug 22 '18 at 13:35
  • 1
    Martin is correct, split these up. why would posting the same request return success sometimes and failure other times? it's a unit test, you should have enough control for the inputs to specify the outcome. – Nathan Hughes Aug 22 '18 at 13:42

1 Answers1

1

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.