In automated tests, mock out non-intrinsic dependencies whenever possible

Unless you are writing a full, end-to-end integration test, mock out any significant calls to other services or classes where the implementation is assumed to be correct for the purposes of your test.

Ideally, use dependency injection (e.g. Spring framework) to make it easy to switch from mocks to the real dependency and vice-versa so the same tests can be run in mocked mode or full integration mode.

Why?

This will

  1. protect your tests from being hijacked by bugs in some other code that you are calling; if your test fails due to bugs in code you are calling that you assume is correct, it might mean bugs in the code you are intending to test remain undetected while those unrelated bugs are addressed.
  2. protect your tests if frequent changes are being made to the interface of the service or class you are calling; you choose when to update to the latest interface of that service or class and are not forced to do so by each breaking change.
  3. protect your tests from unavailability of external services you are dependent upon; you can still run your test even if the service you are dependent upon is down or unresponsive.
  4. make your tests faster to execute providing faster feedback especially in larger continuous integration (CI) pipelines.
  5. enable you to switch out mocks easily and run the same tests in a full integration pipeline reducing the need to duplicate test code for different CI environments.

Leave a Reply

Your email address will not be published. Required fields are marked *