Isolated test
Make each unit test isolated from the others. A test-driven development pattern. Ideally, one problem should cause one test to fail.
How perfect should test isolation be?
Treat it as a risk to manage consciously, rather than striving for perfection:
Notice that we have opened ourselves up to a risk. If the test for equality fails to accurately check that equality is working, then the test for multiplication could also fail to accurately check that multiplication is working. This is a risk that we actively manage in TDD. We aren’t striving for perfection. —Chapter 4, Test-driven development: by example
Test isolation and high cohesion and low coupling
My first experience with automated tests was with GUI-based tests for a debugger I was building, which ran all night. Every morning when I arrived, a pile of paper with the previous night’s results awaited me on my chair. On lucky days, there was just one sheet saying nothing had broken. Other days there were many, many sheets, each with a failure. A pile of paper on my chair meant a nightmare of a day was beginning.
I learned two lessons. One was to make tests fast enough that I could run them myself, frequently. Then I could catch my own errors before anyone else, and there would be no more nightmare mornings. The second was that an enormous pile of paper did not necessarily mean an enormous number of problems. Often, an early test failed and left the system in an unpredictable state for the tests that followed. …
The main lesson is that every test should be completely independent of every other test. One problem should cause just one test to fail, and two problems should cause just two tests to fail.
One implication of isolated tests is that tests become independent of execution order. If you want to run only some tests, you should be able to do so without worrying that they might fail because earlier tests were not run. … Another implication is that you must work to split the problem into small pieces, making the environment for each test easy and quick to set up. The work of isolating tests results in a system made up of highly cohesive, loosely coupled objects. I had always heard that designing systems this way was good, and was happy when I achieved it. But until I made isolated testing a daily habit, I never quite understood how to produce that high cohesion and low coupling.
—p206-207, Test-driven development: by example
Test coupling
Test coupling has an obvious nasty effect, in that breaking one test causes the next ten to fail even though the code is correct. Test coupling can have a subtle but very nasty effect, in situations in which the order of tests matters: If I run test A before test B, they both work, but if I run test B before test A, then test A fails. Or even nastier, the code exercised by test B is wrong, but because test A ran first, the test passes. —Chapter 19, Test-driven development: by example