In 30 seconds
- Test one small unit, like a function or class, on its own.
- Run in milliseconds; run constantly.
- Form the wide base of the test pyramid.
Good unit tests are FIRST
- Fast: milliseconds each
- Isolated: no shared state, no network
- Repeatable: same result every run
- Self-validating: pass or fail, no reading logs
- Timely: written with or before the code
Arrange, act, assert
Set up the inputs (arrange), call the code (act), check the result (assert). One behaviour per test, with a name that says what it checks. TDD writes these first.
Common mistakes
- Testing implementation details instead of behaviour
- Mocking so much that the test proves nothing
- Slow tests that touch databases (those are integration tests)
Myth vs reality
Myth · Unit tests catch all bugs.
Reality · They miss integration and usability issues.
Myth · More mocks mean better isolation.
Reality · Over-mocking creates brittle, meaningless tests.
Myth · High coverage means good tests.
Reality · Coverage shows code ran, not that it was checked.
The AI angle
AI can generate many unit tests fast. Check that they test behaviour, not implementation, and that they would fail if the code were wrong.
FAQ
What counts as a unit?
Usually a function or class, but focus on a unit of behaviour.
Who writes unit tests?
The developers writing the code.
Should private methods be tested?
Usually test them through the public interface.