DEV Community

Discussion on: How to write unit tests

peerreynders profile image

Testing is also about improving design.

The Flawed Theory Behind Unit Testing:

  • "One very common theory about unit testing is that quality comes from removing the errors that your tests catch. … It’s a nice theory, but it’s wrong."

  • "All of these techniques have been shown to increase quality. And, if we look closely we can see why: all of them force us to reflect on our code. When you write unit tests, … you scrutinize, you think, and often you prevent problems without even encountering a test failure."

  • "I like the fact that the tests we end up with using TDD give us additional leverage: they make it easier to change our code and know that it is still working without having to re-reason through the entirety of the code base."

  • "Quality is a function of thought and reflection - precise thought and reflection."

  1. Tests are supposed to enable "Refactoring Mercilessly"
  2. Code has to be structured in a certain way to be testable. That tends to drive designs towards loose coupling across internal boundaries around cohesive capabilities.

One caveat: Michael Feathers is a classicist (Detroit/Chicago style), not a mockist (London style); i.e.

"The problem that I saw with the mock object approach was that it only tested individual classes, not their interactions."

Which means overuse/abuse of mocks can undermine the beneficial design pressures that tests can bring to bear; typically mocks are OK for dependencies you don't control but a classicist would generally not mock code that is under their control.

Now people will often quote DHH's Test-induced design damage to support that TDD doesn't improve design. However that is from the perspective of a framework author. A framework (or library) imposes design pressures of it's own which often compete with those of the application domain.

With a framework a problem is always solved on the framework's terms somehow coercing the various application concerns in there. So TDD will always place frameworks (like Rails, React) with the Horrible Outside World.

marcinwosinek profile image
Marcin Wosinek Author

Well said! Thanks for your comment.