title: How do I unit test code which calls the Jersey Client API?
body: <p>I wrote code which calls the Jersey client API which in turn calls a web service which is out of my control. I do not want my unit test to call the actual web service.</p>
  
  <p>What is the best approach for writing a unit test for code which calls the Jersey client API? Should I use the Jersey server API to write a JAX-RS web service and then use the Jersey Test Framework for the unit test? Or should I mock out the Jersey web service calls? I have access to JMock. Or should I try another approach?</p>
  
  <p>During my research, I found <a href="http://jersey.576304.n2.nabble.com/Unit-Testing-code-that-uses-the-Jersey-Client-API-td7071519.html" rel="noreferrer">this discussion</a> describing various options, but I did find a complete solution. Are there any code examples available showing a suggested JUnit approach? I could not find any in the Jersey documentation.</p>
  
  <p>Here is the relevant source code:</p>
  
  <pre><code>public String getResult(URI uri) throws Exception {
    // error handling code removed for clarity
    ClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);
    WebResource service = client.resource(uri);
    String result = service.accept(accept).get(String.class);
    return result;
  }
  </code></pre>
  
  <p>Here are examples of test code I would like to pass. I would like to test (1) passing in a valid URI and getting a valid string back and (2) passing in an invalid (for whatever reason -- unreachable or unauthorized) URI and getting an exception back.</p>
  
  <pre><code>@Test
  public void testGetResult_ValidUri() throws Exception {
    String xml = retriever.getResult(VALID_URI);
    Assert.assertFalse(StringUtils.isBlank(xml));
  }
  
  @Test(expected = IllegalArgumentException.class)
  public void testGetResult_InvalidUri() throws Exception {
    retriever.getResult(INVALID_URI);
  }
  </code></pre>
  
  <p>Everything above is the simple description of what my code does. In reality, there is a layer on top of that that accepts two URIs, first tries calling the first URI, and if that URI fails then it tries calling the second URI. I would like to have unit tests covering (1) the first URI succeeds, (2) the first URI fails and the second URI succeeds, and (3) both URIs fail. This code is sufficiently complex that I want to test these different scenarios using JUnit, but to do this I either need to run actual stand-in web services or mock out the Jersey client API calls.</p>