Unit Testing
Definition
Unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures—are tested to determine whether they are fit for use.
Why It Matters
Unit tests provide a safety net for developers. They verify that the smallest, individual pieces of the code work as expected. This allows developers to make changes and refactor code with confidence, knowing that if they break something, the tests will fail.
Contextual Example
A developer writes a function `add(a, b)` that is supposed to return the sum of two numbers. They would write a unit test that calls `add(2, 3)` and asserts that the result is 5. If someone later accidentally changes the function to do subtraction, this test will fail, immediately alerting them to the error.
Common Misunderstandings
- Unit tests should be fast and test only one thing in isolation.
- They are the foundation of the "testing pyramid," complemented by integration tests and end-to-end tests.