About Alex Soto

Testing client side of RESTful services

Develop an application that uses RESTful web API may imply developing server and client side. Writing integration tests for server side can be as easy as using Arquillian to start up server and REST-assured to test that the services works as expected. The problem is how to test the client side. In this post we are going to see how to test the client side apart from using mocks.

As a brief description, to test client part, what we need is a local server which can return recorded JSON responses. The rest-client-driver is a library which simulates a RESTful service. You can set expectations on the HTTP requests you want to receive during a test. So it is exactly what we need for our java client side. Note that this project is really helpful to write tests when we are developing RESTful web clients for connecting to services developed by third parties like Flickr Rest API, Jira Rest API, Github
First thing to do is adding rest-client-driver dependency:

 <dependency>
     <groupId>com.github.rest-driver<groupId>
     <artifactId>rest-client-driver<artifactId>
     <version>1.1.27<version>
     <scope>test<scope>
 <dependency>

Next step we are going to create a very simple Jersey application which simply invokes a get method to required URI.

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

And now we want to test that invokeGetMethod really gets the required resource. Let’s suppose that this method in production code will be responsible of getting all issues name from a project registered on github.

Now we can start to write the test:

 @Rule
 public ClientDriverRule driver = new ClientDriverRule();
 
 @Test
 public 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)); 
 
 }
  • We use ClientDriverRule @Rule annotation to add the client-driver to a test.
  • And then using methods provided by RestClientDriver class, expectations are recorded.
  • See how we are setting the base URL using driver.getBaseUrl()

With rest-client-driver we can also record http status response using giveEmptyResponse method:

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

And obviously we can record a put action:

 driver.addExpectation(
    onRequestTo('reposlordofthejarsnosqlunitissues').
      .withMethod(Method.PUT).withBody(PUT_MESSAGE, 'applicationjson'), giveEmptyResponse().withStatus(204));

Note that in this example, we are setting that our request should contain given message body to response a 204 status code.
This is a very simple example, but keep in mind that also works with libraries like gson or jackson. Also rest-driver project comes with a module that can be used to assert server responses (like REST-assured project) but this topic will be addressed into another post.

Reference: Testing client side of RESTful services from our JCG partner Alex Soto at the One Jar To Rule Them All blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


+ 5 = eight



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books