test api 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: API/Webservices with RestAssured Library?

import static io.restassured.RestAssured.* ;
URI uri = new URI(" ... / methods(get, post)”)
GET;
Response response =
given().accept(ContentType.JSON).
when().get(URI);
response.
then().assertThat().statusCode(200).
and().assertThat().ContentType(ContentType.JSON);

POST;
Response response =
given().ContentType(ContentType.JSON).with().
accept(ContentType.JSON).and().body(JSONbody).
when().post(URI);
response.
then().assertThat().statusCode(200);

Tags:

Misc Example