Hacker News new | ask | show | jobs
by amoerie 3620 days ago
Well, I'm not entirely sold on TDD just yet, but after applying it for a few years now, the benefits seem to be:

- Requires you to think about structure before you write the actual code. Code that is unit testable is usually better code. (but not necessarily)

- Requires you to think about the scenarios that you will support beforehand.

- Ensures that every file is unit tested. Without TDD you can have untested files. Why unit tests are great is another topic entirely.

- Ensures that tests cannot return false positives. TDD requires you to write and run your tests before any real code is written, so all tests should be red in the beginning. If you write your tests afterwards, your test could be green when in fact the code is incorrect.

What I don't like about TDD is that it pushes your code towards very easy to test code, which is not always better code. I'm more inclined nowadays to just start with the actual code, refactor iteratively until I'm satisfied, and then write the tests. This reduces the total amount of work, because otherwise you also need to refactor your tests every iteration, which only gets written at the end with my method. The downsides are that unit tests can be forgotten, or that you can write false positive tests. In my experience though, this rarely happens.

The most important part - imho - is to have meaningful unit tests.

Truth be told, I value solid integration tests more than unit tests, because they actually test the input/output of your system, which at the end of the day is the most important thing. Unfortunately integration tests tend to be more fragile and require more maintenance. On the other hand, they are more resistant against refactoring, while unit tests essentially have to be rewritten when any kind of refactoring happens.

Nowadays, I write both unit tests and integration tests, which is expensive to write and maintain, but in return they provide you with peace of mind and confidence, which is priceless imho.

1 comments

Integration tests catch more bugs.

In fact unit tests are fairly low on the scale, according to this: https://kev.inburke.com/kevin/the-best-ways-to-find-bugs-in-...

Bugs caught is only one axis though, they other is effort. Unit testing is much lower effort, particularly for edge cases (what happens if dependency x throws exception) which may be hard/impossible with integration tests.