Monday 27 August 2018

JUnit test case sample code Snippet to Perform save/ persist using JPA

Following is the JUnit  sample code snippet to perform save/ persist on the database using JPA

 @Test
    public void addApplication() throws Exception {

       // Constructing mock Json for post operation
        String mockApplicationJson = "{\"name\":\"Test Application\",\"description\":\"A test application.\",\"owner\":\"Kotresh Matada\"}";

        //Create a post request with an accept header for application\json
        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post("/tza/application/")
                .accept(MediaType.APPLICATION_JSON).content(mockApplicationJson)
                .contentType(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        MockHttpServletResponse response = result.getResponse();

        //Assert that the return status is CREATED
        assertEquals(HttpStatus.CREATED.value(), response.getStatus());

        //Get the location from response header and assert that it contains the URI of the created resource
        assertEquals("http://localhost/application/1",
                response.getHeader(HttpHeaders.LOCATION));
    }

No comments:

Post a Comment