Sunday, June 28, 2020


Mockito perform a simple restful API testing:

@ExtendWith(SpringExtension.class)
@WebMvcTest(HelloWorldController.class)
class HelloWorldControllerTest {

    @Autowired    private MockMvc mockMvc;

    @Test    public void helloWorld_basic() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get("/hello-world").accept(MediaType.APPLICATION_JSON);
        MvcResult mvcResult = mockMvc.perform(request).andExpect(status().isOk()).andExpect(content().string("Hello World")).andReturn();
        assertEquals("Hello World", mvcResult.getResponse().getContentAsString());
    }

@Testpublic void testPost() throws Exception {
    String json = "{\n" +
            "  \"title\": \"Greetings\",\n" +
            "  \"value\": \"hello\"\n" +
            "}";
    mockMvc.perform(MockMvcRequestBuilders.post("/hello/post")
            .contentType(MediaType.APPLICATION_JSON)
            .content(json))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.title", Matchers.is("Greetings")))
            .andExpect(jsonPath("$.value", Matchers.is("hello")))
            .andExpect(jsonPath("$.*",Matchers.hasSize(2)));
}
}

<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-all</artifactId>
   <version>1.10.19</version>
   <scope>test</scope>
</dependency>

No comments:

Post a Comment