Api Integration

This tutorial will focus on the basic principles and mechanics of testing a REST API with live Integration Tests with a JSON Results.
For an internal application, this kind of testing will usually run as a late step in a continuous Integration process, consuming the REST API after it has already been deployed.
When testing a REST resources, there are usually a few orthogonal responsibilities the tests should focus on:




  • the HTTP response code
  • other HTTP headers in the response
  • the payload (JSON, XML)
Testing The Status Code :


@Test
public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsReceived()
throws ClientProtocolException, IOException{
// Given


String name = RandomStringUtils.randomAlphabetic( 8 );
HttpUriRequest request = new HttpGet( "https://api.github.com/users/" + name );
// When

HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request );
// Then
assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_NOT_FOUND));
}

Testing The Media Type :

@Test

public void

givenRequestWithNoAcceptHeader_whenRequestIsExecuted_thenDefaultResponseContentTypeIsJson()

throws ClientProtocolException, IOException{

// Given

String jsonMimeType = "application/json";

HttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );

// When

HttpResponse response = HttpClientBuilder.create().build().execute( request );

// Then

String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertEquals( jsonMimeType, mimeType );

}


Testing The JSON Payload :

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

}