簡要描述一下,為了測試客戶端,我們需要一個本地服務器,該服務器可以返回記錄的JSON響應。 rest-client-driver是一個模擬RESTful服務的庫。 您可以對測試期間希望接收的HTTP請求設置期望值。 因此,這正是我們Java客戶端所需的。 請注意,當我們開發RESTful Web客戶端以連接到第三方開發的服務(例如Flickr Rest API , Jira Rest API , Github …)時,該項目對于編寫RESTful Web客戶端非常有用。
首先要做的是添加rest-client-driver依賴項:
<dependency><groupId>com.github.rest-driver<groupId><artifactId>rest-client-driver<artifactId><version>1.1.27<version><scope>test<scope><dependency>
下一步,我們將創建一個非常簡單的Jersey應用程序,該應用程序僅對所需的URI調用get方法。
public class GithubClient {private static final int HTTP_STATUS_CODE_OK = 200;private String githubBaseUri;public GithubClient(String githubBaseUri) {this.githubBaseUri = githubBaseUri;}public String invokeGetMethod(String resourceName) {Client client = Client.create();WebResource webResource = client.resource(githubBaseUri+resourceName);ClientResponse response = webResource.type('applicationjson').accept('applicationjson').get(ClientResponse.class);int statusCode = response.getStatus();if(statusCode != HTTP_STATUS_CODE_OK) {throw new IllegalStateException('Error code '+statusCode);}return response.getEntity(String.class);}}
現在我們要測試一下invokeGetMethod是否確實獲得了所需的資源。 讓我們假設生產代碼中的此方法將負責從github上注冊的項目中獲取所有問題名稱。
現在我們可以開始編寫測試了:
@Rulepublic ClientDriverRule driver = new ClientDriverRule();@Testpublic void issues_from_project_should_be_retrieved() {driver.addExpectation(onRequestTo('reposlordofthejarsnosqlunitissues').withMethod(Method.GET), giveResponse(GET_RESPONSE));GithubClient githubClient = new GithubClient(driver.getBaseUrl());String issues = githubClient.invokeGetMethod('reposlordofthejarsnosqlunitissues');assertThat(issues, is(GET_RESPONSE)); }
- 我們使用ClientDriverRule @Rule批注將客戶端驅動程序添加到測試中。
- 然后使用RestClientDriver類提供的方法記錄期望值。
- 了解我們如何使用driver.getBaseUrl()設置基本URL
使用rest-client-driver,我們還可以使用GiveEmptyResponse方法記錄http狀態響應:
@Test(expected=IllegalStateException.class)public void http_errors_should_throw_an_exception() {driver.addExpectation(onRequestTo('reposlordofthejarsnosqlunitissues').withMethod(Method.GET), giveEmptyResponse().withStatus(401));GithubClient githubClient = new GithubClient(driver.getBaseUrl());githubClient.invokeGetMethod('reposlordofthejarsnosqlunitissues');}
很明顯,我們可以記錄一個推桿動作:
driver.addExpectation(onRequestTo('reposlordofthejarsnosqlunitissues')..withMethod(Method.PUT).withBody(PUT_MESSAGE, 'applicationjson'), giveEmptyResponse().withStatus(204));
請注意,在此示例中,我們設置請求應包含給定的消息正文以響應204狀態碼。
這是一個非常簡單的示例,但請記住,該示例也可用于gson或jackson之類的庫。 rest-driver項目還附帶一個模塊,該模塊可用于斷言服務器響應(如REST保證的項目),但本主題將在另一篇文章中解決。
參考:在One Jar To Rule Them All博客上測試我們的JCG合作伙伴 Alex Soto 的RESTful服務的客戶端 。
翻譯自: https://www.javacodegeeks.com/2012/09/testing-client-side-of-restful-services.html