在 JUnit 测试用例中使用 Try Catch

Using Try Catch inside JUnit Test Case

最初,我在 Java Spring Boot Junit 测试用例中使用 MockMvc。 我正在发送 JSON 消息作为成功 {"message": "Success"},如果消息不成功,则不会抛出 AssertionError例外。它应该检查 catch 块下的消息 Failure 语句。

在不添加catch块语句的情况下,是否有任何可行的方法可以将成功,失败场景结合在一起。下面的代码解释了我的尝试,

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

    }

}

试试这个

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

但我建议您尝试像 Martin 那样将这些测试用例拆分成单独的测试。