rest api testing with java code example

Example 1: java unit test an api

@Test
public void
  givenUserExists_whenUserInformationIsRetrieved_thenRetrievedResourceIsCorrect()
  throws ClientProtocolException, IOException {
  
    // Given
    HttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );
 
    // When
    HttpResponse response = HttpClientBuilder.create().build().execute( request );
 
    // Then
    GitHubUser resource = RetrieveUtil.retrieveResourceFromResponse(
      response, GitHubUser.class);
    assertThat( "eugenp", Matchers.is( resource.getLogin() ) );
}

Example 2: rest assured script

The syntax of Rest Assured.io is the most beautiful part, as it is very
BDD like and understandable.

Given(). (lets you set a background)
		param("customer_id", "102").
        header("z", "w").
when(). (marks the premise of your scenario. For ex: get url)
Method(). (replace it with any of CRUD operations like get post put delete)
Then(). (your assert and matcher conditions goes here)
		statusCode(xxx).
        Body("x, "y", equalTo("z"));

Tags:

Misc Example