title: Integration testing: Mock external API vs. use external API sandbox
body: <p>We're required to use the API of an external partner. The API is in a good shape and we got access to a sandbox environment we can use for automatic testing.</p>
  
  <p>We already test every single call of the external API using unit tests but are unsure regarding best practices for integration tests when it comes to complex operations on the side of the external partner.</p>
  
  <p>Example: Every user of our service also got a user object at our external partner. When performing external API call X on this user object, we expect object Y to appear inside collection Z of this user (which we have to query using a different call).</p>
  
  <p>What are best practices for testing cases like this?</p>
  
  <ul>
  <li><p><strong>Mock the external API</strong> as much as possible and rely on the unit tests to do their job? Advantages: Tests run fast and independent from an internet connection. Disadvantages: Mistakes is in our mocks could lead to false positives.</p></li>
  <li><p><strong>Integrate the external API sandbox</strong> and run every integration test against it. Advantages: Close to real life API interactions. Disadvantages: Tests can only be run with an open internet connection and take more time.</p></li>
  <li><p><strong>Use a hybrid</strong> of mocked and sandbox data, set a boolean to switch between the internal (=mocked) and external (=sandbox) environment when required. Advantages: Reliable tests. Disadvantages: Could be a pain to set up.</p></li>
  <li><p><strong>Other best practices?</strong></p></li>
  </ul>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>Related: <a href="https://stackoverflow.com/questions/7564038/how-are-integration-tests-written-for-interacting-with-external-api">How are integration tests written for interacting with external API?</a> However, the answer "You don't. You have to actually trust that the actual API actually works." is not sufficient in our opinion.</p>
  
  <p>[EDIT] We fear that integration testing only against our assumptions how the external API should work (even if they are based on unit tests) – and not against the actual API – will leave us with false positives. What we'd need is a test that verifies that our assumptions (mocks) are actually correct – not only in the context of unit tests but also in the context of complex operations with several steps.</p>
  
  <p>Validation might be a good example: What if we mess up the integration code and send malformed data or data that does not make any sense in the context we send it in because we missed a step? Our mock API, which does not validate (or only in very limited range) would still return valid data instead of passing the error we would receive from the real API.</p>