title: Java Unit Testing by Creating a mock object of an interface which does some work
body: <p><em>Im not sure how to word what I want to do so I apologise in advance</em></p>
  
  <p>I'm currently writing unit tests for some legacy code as part of my job. One of these bits of code is a (Java) HttpServlet which provides a re-direct URL. Essentially the code looks like this:</p>
  
  <pre><code>public class Server extends HttpServlet {
    ...
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
      ...
      String url = "....";
      .. // do some work to create that url
      response.sendRedirect(url);
    }
    ...
  }
  </code></pre>
  
  <p>As part of my unit test for this class I want to test that redirect URL created. So I would do something along the lines of:</p>
  
  <pre><code> Server server = new Server();
   ..
   server.doGet(request, response);
   String url = getRedirectURL(response);
   // test URL returned
   ...
  </code></pre>
  
  <p>What's the best way to 'getRedirectURL' from the response?</p>
  
  <p>I'm currently using <strong>Junit</strong> and <strong>Jmock</strong> (both latest versions). I create a Mock HttpServletRequest and I can easily create a mock HttpServletResponse and add an expectation for the sendRedirect(url) method IF I knew the expected format of the URL, however I do not.</p>
  
  <p>My attempt was to create a mock class, implementing HttpServletResponse which stored the value of the url and then allowed me to retrieve it later. i.e.</p>
  
  <pre><code>  private class MockHttpServletResponse implements HttpServletResponse {
    String url;
    public String getURL() {
       return url;
    }
    public void sendRedirect(String url) {
       this.url = url;
    }
   }
  </code></pre>
  
  <p>However, because it implements an interface Java wants me to implement ALL the methods in HttpServletResponse which I really don't want to do.</p>
  
  <p>Thank you in advance :) i'll try and re-word this</p>