Why should I write unit tests if I already have E2E tests

Viewed 1558

If we're already doing E2E (end-to-end) testing do we also need to write unit tests?

Considering we are doing all functional testing in end-to-end testing, what are the pros and cons of doing both?

2 Answers

Because E2E tests are not a perfect substitution for unit tests.

In particular:

They are slow to run

E2E tests use actual services, not mocks. A real database is vastly slower than an in-memory mock of a database. You also have to build your whole project, set up seed data etc etc.

If I have to wait a long time for a test run to end, I'm probably gonna start skipping it more often.

They don't isolate failure

E2E tests tell you that a whole scenario is broken, i.e 'User login faled'. They don't tell you which part of which component that takes part in that scenario is broken. This makes it harder to tell which part of the code caused the test failure.

They hurt reusability

You can't plug-out a component of your system and drop it in another system with confidence. There's no unit-tests to run for that component, in the new environment.

You can't do per-unit TDD

If you want to carve out a new component(unit) for your system and use TDD while you're at it, you're at a dead-end without unit tests. Unit tests and TDD go hand-in-hand.


That being said:

  • Having both E2E tests and unit-tests is what you should be aiming for, if your resources allow it.
  • Having only E2E tests is always better than having no tests at all.

Here's a nice illustration of the perfect test-suite, called the Testing Pyramid:

Testing Pyramid illustration

This article from the Google Test Blog goes into more detail: Just Say No to More End-to-End Tests. While I don't agree that you shouldn't write E2E tests, it illustrates the pros and cons of each, in-depth.

Unit testing is important aspect of software life cycle to improve its quality. If we have written test cases, any new developer can understand the functionality and check the different output based on conditions. It should be mandatory part of the process.

Related