title: How to mock remote REST API in unit test with Spring?
body: <p>Assume I have made a simple client in my application that uses a remote web service that is exposing a RESTful API at some URI <code>/foo/bar/{baz}</code>. Now I wish to unit test my client that makes calls to this web service.</p>
  
  <p>Ideally, in my tests, I’d like to mock the responses I get from the web service, given a specific request like <code>/foo/bar/123</code> or <code>/foo/bar/42</code>. My client assumes the API is actually running somewhere, so I need a local "web service" to start running on <code>http://localhost:9090/foo/bar</code> for my tests.</p>
  
  <p>I want my unit tests to be self-contained, similar to testing Spring controllers with the Spring MVC Test framework. </p>
  
  <p>Some pseudo-code for a simple client, fetching numbers from the remote API:</p>
  
  <pre><code>// Initialization logic involving setting up mocking of remote API at 
  // http://localhost:9090/foo/bar
  
  @Autowired
  NumberClient numberClient // calls the API at http://localhost:9090/foo/bar
  
  @Test
  public void getNumber42() {
      onRequest(mockAPI.get("/foo/bar/42")).thenRespond("{ \"number\" : 42 }");
      assertEquals(42, numberClient.getNumber(42));
  }
  
  // ..
  </code></pre>
  
  <p>What are my alternatives using Spring?</p>