title: Stub external service requests for functional tests with symfony di container
body: <p><strong>question summary</strong></p>
  
  <p>Is it possible to inject stubs/mocks to the symfony di container in my test cases to simulate different external api responses?</p>
  
  <ul>
  <li>test that my application sends an email if the api returns an error (i want to inject a stub for my http client class that returns a HTTP 500)</li>
  <li>test that my application returns the correct result using 2 different APIs as source (i want to inject both HTTP Clients as stub with a specific result body)</li>
  </ul>
  
  <p><strong>details</strong></p>
  
  <p>i want to write functional tests for an silex application that uses the symfony di container. The application uses multiple API's as backend to fullfill the client reuquests.</p>
  
  <p>The code injects an abstracted http client to the api client where i'm able to inject a http api client stub.</p>
  
  <pre><code>class AwesomeApiClient
     __construct(MyHttpClient $httpClient);
  
  class MyApiHttpClient
  </code></pre>
  
  <p>This does work pretty good with unit testing.</p>
  
  <p>Now i want to write functional tests.
  I extended the silex <code>WebTestCase</code> and implemented the application initialization.
  The MyApiHttpClient is injected with the symfony di container.</p>
  
  <p>Now i want to do something like this:</p>
  
  <pre><code># symfony di container does not allow this
  $this-&gt;getDiContainer()-&gt;set('my_http_client', $myHttpClientStubInstance);
  </code></pre>
  
  <p>i want to configure my stub in every test so i'm able to test different (e.g. error, success) responses for the same request.</p>
  
  <p>things i've tried:</p>
  
  <p><strong>using setter injection at runtime</strong></p>
  
  <p><code>$his-&gt;getDiContainer()-&gt;get('MyApiClient')-&gt;setHttpClient($myMock);</code></p>
  
  <p>The DiContainer returns a new instance for everytime i call the get method. That does make absolutely sense. So this does not work.</p>
  
  <p><strong>overriding the http client in the di container</strong></p>
  
  <p><code>$this-&gt;getDiContainer-&gt;set('MyHttpClient', $myHttpClientStub);</code></p>
  
  <p>Does not work because symfony does not allow to change definitions at runtime. Also it seems to take a definition, not an instance.</p>
  
  <p><strong>PHP-VCR</strong></p>
  
  <p>Does work with a few changes in my production code because it messes up the HTTP Headers in my curl header callbacks. Does not work for other services (rabbitmq...)</p>