title: Unit testing a servlet that makes an URL call
body: <p>I want to write a unit test for a servlet class that makes a call to a web service through java.net.URL.</p>
  
  <p>I can create mock request and response objects to send to the servlet's doGet method easily (using the techniques from the pragmatic programmer text on junit), i.e., creating MockHttpServletRequest, MockHttpServletResponse, and passing these to doGet. </p>
  
  <p>The part I'm having trouble with is the URL open in the servlet. </p>
  
  <p>Right now, i'm just choosing between a call to a function that opens the URL and returns a string (the production code) and a call to a function that returns that directly returns a string for a fixed URL (the test code)</p>
  
  <p>Ideally i'd like to have a doGet method in which the testing code is invisible -  the choice between the function that makes the network access, and the one that directly returns a string should be transparent to doGet.</p>
  
  <p>i can think of a number of ways of achieving this, but none feel right.</p>
  
  <ul>
  <li><p>Example 1: wrap the function in a class that has a testOn boolean, and a setTestMode method; junit init can set the testMode to true, default is false. the testOn decides which method to call. negative is that i need a new class, seems like it could get out of hand.</p></li>
  <li><p>Example 2: have two classes implementing the network access, one of which is the mock; have junit reload the mock class, production code load the regular class (or somehow remap the production class to the mock class). negative: not sure how this would be done; seems clumsy.</p></li>
  <li><p>Example 3: have a class with static fields indicating if i want to use mocks, and condition the URL access in the servlet based on the field values. negative: feels like global variables.</p></li>
  <li><p>Example 4: extend URL, so that the production code will work fine if i switch to URL only (but java.net.URL is final).</p></li>
  </ul>
  
  <p>I couldn't find quite the right answer through a morning of searches, hence my turning to the collective wisdom of SO.</p>
  
  <p>Thanks,
  Adnan</p>
  
  <p>ps - I should mention that I don't have to use java.net.URL, anything that's equivalent will work.</p>