본문 바로가기

Web/spring

[Spring Test] Test a REST API with Java

728x90

https://www.baeldung.com/integration-testing-a-rest-api

 


 

 

 

focus on the basic principles and mechanics of testing a REST API with live Integration Tests (with a JSON payload).

 

When testing a REST resource, 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)

각 테스트는 단일 책임에 포커스를 두고 단일 assertion을 포함한다

 

 

 

 

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 );
}

Response에 실제 JSON data가 포함됨

 

 

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

The client asks for a particular type of representation via Accept

 

 

Utilities for Testing

use Jackson 2 to unmarshall the raw JSON String into a type-safe Java Entity

 

* Object/ XML Mapping, 줄여서 O/X mapping은 Object를 XML문서로 변환하는데 이를 XML Mashalling 또는 Marshalling 이다. 반대로 XML문서를 Object로 변환하는 것은 Unmarshalling

public class GitHubUser {

    private String login;

    // standard getters and setters
}
public static <T> T retrieveResourceFromResponse(HttpResponse response, Class<T> clazz) 
  throws IOException {
 
    String jsonFromResponse = EntityUtils.toString(response.getEntity());
    ObjectMapper mapper = new ObjectMapper()
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(jsonFromResponse, clazz);
}

 

because the Representation of a User Resource on GitHub gets pretty complex, and we don't need any of that information here

 

 

https://www.baeldung.com/jackson-deserialize-json-unknown-properties

 

Jackson Unmarshalling JSON with Unknown Properties | Baeldung

How to unmarshall a JSON that contains Unknown Properties using Jackson.

www.baeldung.com

 

 

 

728x90