简要描述一下,为了测试客户端,我们需要一个本地服务器,该服务器可以返回记录的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