Should Unit Tests and Integration Tests Be Separated?

Architectureintegration-testsunit testing

I have to write unit tests and integration tests for a project.

  • Should all tests be put into a single tests folder?
  • Or should unit tests and integration tests each be in a separate tests folder?
  • Or should I even put them into separate projects?

If I keep them together, are there any advantages or drawbacks with this approach?

Best Answer

In general: yes, you should put integration tests and unit tests into different folders. Often, programmers don't draw a clear line between these two kinds of tests and just write whatever kind of test is useful. But integration tests tend to be slower, because they often involve:

  • Database queries
  • Network requests
  • Time-dependent behaviour
  • Large amounts of data

In contrast, an unit test would mock any expensive operations, so unit tests tend to run quickly (in fact, the slowest part of running the test is often the test framework itself).

When a programmer is working on the system they are in an edit–test cycle. The faster they get test feedback and the shorter the cycle is, the more productive they can be. So there we want to only run important test that complete quickly. The complete test suite would only be executed as part of a QA process, e.g. on a CI server.

This means that large test suites should be categorized. Can we only select unit tests for a particular component? Can we exclude slow tests? One simple way to do this is to maintain different test suites in different directories. If you only have very few tests, a single directory would also be OK as long as a programmer can easily select a subset of tests.

Whatever allows a programmer to get feedback quickly is good. The most comprehensive test suite doesn't matter if it isn't executed regularly.

Further reading: