Unit testing
A unit test is an automated test that verifies the correctness of the smallest separable part of a program — usually a single function, method or class — examined in complete isolation from the rest of the system. Its purpose is to prove that a given piece of logic returns the expected result for specific inputs, before the code is combined into a larger whole.
How unit testing works
A single test typically follows the AAA pattern: Arrange (set up the data and the object under test), Act (call the method being tested) and Assert (check that the result matches expectations). Isolation is the key idea — every external dependency, such as a database, an API or the system clock, is replaced with a test double (a mock, stub or fake). This keeps the test fast, deterministic and pointed only at the code under scrutiny, not its surroundings. Tests are written in dedicated frameworks — PHPUnit or Pest in PHP, Jest in JavaScript, pytest in Python — and their aggregate code coverage reports what share of lines the suite actually executed.
Practical application
Unit tests are the base of the so-called testing pyramid: there should be the most of them, because they are cheap and fast. They run automatically in a CI/CD pipeline on every commit — if one fails, the change does not move forward. They guard against regression: after a refactor you immediately see whether the old behaviour still holds. In TDD the test is written before the production code and defines its contract. In practice a well-crafted unit suite shortens debugging — instead of clicking through the application by hand, a developer sees within seconds which edge case stopped holding. It pays to focus on calculation logic, validation and boundary cases (empty data, negative values, range overflows), since that is where bugs are born most often.
Powiązane pojęcia
Najczęstsze pytania
How do unit tests differ from integration tests?
A unit test checks one piece of code in full isolation, replacing every dependency with a test double. An integration test verifies that several components — for example, code plus a real database — work correctly together. Unit tests are faster and more numerous; integration tests are slower but closer to reality.
Does 100% code coverage mean the code is bug-free?
No. Coverage only tells you which lines ran during the tests, not whether the assertions check the right things. You can reach full coverage and still miss a logic error. Treat coverage as a helper metric, never as a guarantee of quality.
