Unit tests considered harmful? No.
I stumbled across this post today, which represents (I think) a widely held belief that unit tests are bad.
The argument here seems to be:
Unit test coverage doesn't guarantee that features actually work, only that regressions can be caught
Tests make code difficult to change
Therefore:
Unit testing is harmful
These are valid (separate) arguments against shitty unit tests, and using test coverage metrics as a proxy for correctness. And the conclusion is dubious at best.
The lesson here isn't "unit tests are harmful", the answer is get better at listening to what your code is telling you.
Unit tests are an invaluable tool for knowing whether your code is well factored. If it's hard to test the behavior (not the implementation) of your code, then your code is trying to tell you something very important, and it's not "test my implementation". We need to listen to our code when it talks to us like this.
When unit tests are done poorly, they inhibit change, give you false confidence, and make you worse at your job. When done well, they are the wind at your back, the green light to refactoring, and an invaluable signal that helps guide the design of your domain model.
It took me a good 20 years to learn this lesson. Why? Arrogance, the curse of experience, and because very few organizations actually do this well. And, of course, because it’s hard.
Here are questions I ask myself when I find it hard to unit test a class in my design:
Is it hard to test this because it has side effects that can’t be simply mocked or accounted for?
Am I trying to test implementation or behavior?
Is this object too big? Can I make it smaller?
Should this object be multiple smaller objects?
Does this object depend on other objects? How many? Can I inject them?
Hopefully you recognize some of the SOLID principles here 😀.
Don’t avoid unit tests - avoid poor unit tests.