目的是對技術進行介紹,并為基本正確性編寫一些測試。 這些示例將使用最新版本的GitHub REST API。
對于內部應用程序,這種測試通常將在持續集成過程中作為后期步驟運行,并在已部署REST API后使用它。
在測試REST資源時,通常應承擔一些正交的職責,測試應重點關注:
- HTTP 響應代碼
- 響應中的其他HTTP 標頭
- 有效負載 (JSON,XML)
每個測試應僅關注單個職責并包括單個聲明。 專注于清晰的分離總是有好處的,但是當進行這種黑盒測試時,它就顯得尤為重要,因為通常的趨勢是在一開始就編寫復雜的測試方案。
集成測試的另一個重要方面是遵守單一抽象原理–測試中的邏輯應以較高的層次編寫。 諸如創建請求,將HTTP請求發送到服務器,處理IO等之類的細節不應內聯而是通過實用程序方法來完成。
測試HTTP響應代碼
@Test
public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsReceived()throws ClientProtocolException, IOException{// GivenString name = randomAlphabetic( 8 );HttpUriRequest request = new HttpGet( "https://api.github.com/users/" + name );// WhenHttpResponse httpResponse = httpClient.execute( request );// ThenRestAssert.assertResponseCodeIs( httpResponse, 404 );
}
這是一個相當簡單的測試,它驗證基本的快樂路徑在起作用,而不會增加測試套件的復雜性。 如果由于某種原因它失敗了,那么在此URL修復之前,無需檢查該URL的任何其他測試。 由于驗證響應代碼是集成測試套件中最常見的斷言之一,因此將使用自定義斷言 。
public static void assertResponseCodeIs( final HttpResponse response, final int expectedCode ){final int statusCode = httpResponse.getStatusLine().getStatusCode();assertEquals( expectedCode, statusCode );
}
測試HTTP響應的其他標頭
@Test
public void givenRequestWithNoAcceptHeader_whenRequestIsExecuted_thenDefaultResponseContentTypeIsJson()throws ClientProtocolException, IOException{// GivenString jsonMimeType = "application/json";HttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );// WhenHttpResponse response = this.httpClient.execute( request );// ThenString mimeType = EntityUtils.getContentMimeType( response.getEntity() );assertEquals( jsonMimeType, mimeType );
}
這樣可以確保在請求用戶詳細信息時的響應實際上是JSON。 被測試功能有一個邏輯上的進展-首先是響應代碼,以確保請求正常,然后是請求的mime類型,然后才是對實際JSON是否正確的驗證。
測試HTTP響應的JSON有效負載
@Test
public void givenUserExists_whenUserInformationIsRetrieved_thenRetrievedResourceIsCorrect()throws ClientProtocolException, IOException{// GivenHttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );// WhenHttpResponse response = new DefaultHttpClient().execute( request );// ThenGitHubUser resource =RetrieveUtil.retrieveResourceFromResponse( response, GitHubUser.class );assertThat( "eugenp", Matchers.is( resource.getLogin() ) );
}
在這種情況下,我知道GitHub資源的默認表示形式是JSON,但通常應將響應的Content-Type標頭與請求的Accept標頭一起進行測試-客戶端通過Accept請求特定的表示類型,服務器應該兌現。
測試工具
以下是使測試保持較高抽象水平的實用程序:
–使用JSON有效負載(或直接使用POJO)裝飾HTTP請求:
public static < T >HttpEntityEnclosingRequest decorateRequestWithResource( final HttpEntityEnclosingRequest request, final T resource )throws IOException{Preconditions.checkNotNull( request );Preconditions.checkNotNull( resource );final String resourceAsJson = JsonUtil.convertResourceToJson( resource );return JsonUtil.decorateRequestWithJson( request, resourceAsJson );
}public static HttpEntityEnclosingRequest decorateRequestWithJson( final HttpEntityEnclosingRequest request, final String json )throws UnsupportedEncodingException{Preconditions.checkNotNull( request );Preconditions.checkNotNull( json );request.setHeader( HttpConstants.CONTENT_TYPE_HEADER, "application/json" );request.setEntity( new StringEntity( json ) );return request;
}
–從HTTP響應中檢索JSON有效負載(或直接獲取POJO):
public static String retrieveJsonFromResponse( final HttpResponse response )throws IOException{Preconditions.checkNotNull( response );return IOUtils.toString( response.getEntity().getContent() );
}public static < T >T retrieveResourceFromResponse( final HttpResponse response, final Class< T > clazz ) throws IOException{Preconditions.checkNotNull( response );Preconditions.checkNotNull( clazz );final String jsonFromResponse = retrieveJsonFromResponse( response );return ConvertUtil.convertJsonToResource( jsonFromResponse, clazz );
}
–從Java對象(PO??JO)到JSON的轉換實用程序:
public static < T >String convertResourceToJson( final T resource )throws IOException{Preconditions.checkNotNull( resource );return new ObjectMapper().writeValueAsString( resource );
}public static < T >T convertJsonToResource( final String json, final Class< T > clazzOfResource ) throws IOException{Preconditions.checkNotNull( json );Preconditions.checkNotNull( clazzOfResource );return new ObjectMapper().readValue( json, clazzOfResource );
}
依存關系
這些實用程序和測試利用了以下庫,所有這些庫都可以在Maven Central中使用:
- Apache HttpCore和HttpClient
- Apache Commons IO
- Apache Commons Lang
- 杰克遜
- 番石榴
- Hamcrest
結論
這只是完整的集成測試套件應有的一部分。 這些測試著重于確保REST API的基本正確性,而不涉及更復雜的場景,API的可發現性,對同一資源或其他更高級區域使用不同表示形式的情況。 我將在進一步的文章中討論這些問題,同時在github上檢出整個項目 。
參考:我們的JCG合作伙伴 Eugen Paraschiv在baeldung博客上 介紹了RESTful API的Java集成測試 。
- Tomcat 7上具有RESTeasy JAX-RS的RESTful Web服務-Eclipse和Maven項目
- Spring3 RESTful Web服務
- Spring 3使用JUnit 4進行測試– ContextConfiguration和AbstractTransactionalJUnit4SpringContextTests
- 單元和集成測試的代碼覆蓋率
- jqGrid,REST,AJAX和Spring MVC集成
- JUnit 4.9(測試版3)中的規則
- Java教程和Android教程列表
翻譯自: https://www.javacodegeeks.com/2011/10/java-restful-api-integration-testing.html