views:

49

answers:

2

This is the class I'm trying to test (it calculates the size of HTTP page):

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.*;
public class Loader {
  private Client client;
  public Loader(Client c) {
    this.client = c;
  }
  public Integer getLength(URI uri) throws Exception {
    return c.resource(uri) // returns WebResource
      .accept(MediaType.APPLICATION_XML) // returns WebResource.Builder
      .get(String.class) // returns String
      .length();
  }
}

Of course it just an example, not a real-life solution. Now I'm trying to test this class:

public class LoaderTest {
  @Test public void shouldCalculateLength() throws Exception {
    String mockPage = "test page"; // length is 9
    Client mockedClient = /* ??? */;
    Loader mockedLoader = new Loader(mockedClient);
    assertEquals(
      mockPage.length(), 
      mockedLoader.getLength(new URI("http://example.com"))
    );
  }
}

How should I mock com.sun.jersey.api.client.Client class? I'm trying to use Mockito, but any other framework will be OK, since I'm a newbie here..

A: 

Not really related to your question, but may come in handy later, is the Jersey Test Framework. Check out these blog entries by one of the Jersey contributors;

http://blogs.sun.com/naresh/entry/jersey_test_framework_makes_it

http://blogs.sun.com/naresh/entry/jersey_test_framework_re_visited

Back on topic, to test your Loader class you can simply instantiate it with a Client obtained from Client.create(). If you are using Maven you can create a dummy test endpoint (in src/test/java) to call and the Jersey Test framework will load it in Jetty.

Qwerky
A: 
01