3 ms·
Unit tests serve a number of different purposes (for me, YMMV): 1. When writing tests before the code, the tests can help you wrap your head around what the co
by RHSeeger 13y ago
Unit tests serve a number of different purposes (for me, YMMV):
1. When writing tests before the code, the tests can help you wrap your head around what the code should and should not do.
2. Forces distinct functionality/algorithms to be broken out into their own functions for easier testing.
3. Forces algorithms to be broken away from other, less testable, code (ie, read from data base, algorithm, write to database... the piece in the middle there should be in it's own function for testing)
4. When refactoring, gives (more) confidence that the changes being made aren't breaking anything. The corollary to this is it makes refactoring more common because you can feel braver about doing so.
5. Proves the code is doing what you say it's doing (with the tests). Note that this doesn't mean the code is right, just that it isn't wrong in the ways you're testing. Learning to write tests with good coverage and how to partition input data for that is a skill learned by experience.
6. Documents exactly what the code does for someone that comes along later. For much code, this can be determined by looking at the code... but in many cases the tests can say it cleaner.
7. Documents what the code DOESN'T do, and this is an important one that can't really be understood by just looking at the code. If the tests don't say the code does something, it could change later. If the tests only exercise negative number inputs but the code happens to do something useful with positive numbers... user's shouldn't rely on the positive number behavior.
8. Confirm that, when a bug is found, the fix actually fixes it. When finding a bug... a) find a way to reproduce is, b) write a test that does so and fails, c) fix the code and see the test pass... d) the bug never returns without being caught by the test.
- DanWaterworth 13y agoThis is a great answer, but perhaps you could clarify some points for me: * I'm of a functional persuasion, I like to think about types before code, I already tend break things up into testable components (also known as pure functions). What benefits might I find by adopting TDD? * I understand the there are different benefits to be had from the act of writing tests and the artefact that is produced (ie the test suite). Do you the expect the tests that you write find bugs immediately? Or does the artefact only help to document code/detect regressions?