DEV Community

Discussion on: ELI5: Useful Unit Testing

Collapse
tchaffee profile image
Todd Chaffee

A lot depends on why you write tests. My top reason is that I know when to stop writing code. When the tests pass, I'm done writing code.

Other reasons: documenting the code behavior so I can quickly get up to speed without reading code. And finally I want to be able to change code without breaking existing behavior.

If you write tests first and make sure they fail before writing any code, then you can stop writing tests when your tests fully document the behavior required. Hopefully the first few tests you write inspire all sorts of other behavior questions.

But ultimately I think of tests as a contract between me and the user of my code. I will guarantee what's in the tests and nothing else. It is an excellent way of getting everyone on the team to dig into all the edge cases and detailed behavior.

My tests say that my function can add positive integers and give only examples of adding positive integers? I know to not assume the function can handle negative numbers and that it may even throw unexpected errors with negative numbers or non-integers. My tests don't give the largest integers that it can safely add? I don't make assumptions about what that limit is. If you think of tests as documentation about behavior, it's a lot easier to focus on and decide which tests are important.

Collapse
deciduously profile image
Ben Lovy Author

This makes a lot of sense!

When the tests pass, I'm done writing code.

Framing tests as documentation makes it a lot clearer, thank you.