What is Unit Testing?
Unit testing is the practice of testing a single function, method, or class in isolation from the rest of the system. A unit test calls the target with specific inputs, asserts on the output and side effects, and uses mocks or stubs for any dependencies. The goal is to catch logic bugs — wrong conditionals, off-by-one errors, incorrect return values — without running the full application.
What makes a good unit test
- Fast. Milliseconds per test. A suite of 1,000 tests should finish in under 10 seconds. Slow unit tests are a symptom of mocked dependencies that are not fully mocked.
- Deterministic. The same inputs always produce the same pass or fail. No timestamps, no random numbers, no network calls, no database state.
- Tests one behavior. A failure points to a specific broken thing. A test that checks five unrelated behaviors tells you something is wrong but not what.
- Mocks every dependency. Anything your code calls that crosses a process boundary or touches shared state gets mocked. File system, network, database, timers, random number generators.
- Has a descriptive name.
test_user_creation_rejects_duplicate_emailis useful when it fails at 2am.test_user_creation_2is not.
Unit tests vs integration tests
Unit tests mock every dependency and run in milliseconds. Integration tests exercise real dependencies and catch contract bugs at component boundaries. Both matter — a codebase with only unit tests passes every check and breaks in production; a codebase with only integration tests is slow to iterate on. See What is Integration Testing? for the full comparison.
Frameworks per language
Every language has a dominant choice. Pick one and use it consistently.
Jest or Vitest
Built-in testing package + testify
JUnit 5
pytest
Built-in test harness + proptest
xUnit
Keploy Test Agent for AI-generated unit tests
Keploy Test Agent is a separate Keploy product (from the core eBPF-based API testing) that uses large language models to generate unit tests from source code and pull request diffs. On every PR, the Test Agent identifies changed functions, proposes unit tests that cover the new behavior, and posts them as a suggested commit on the PR. The developer reviews, edits, and commits — no hand-writing boilerplate. See Keploy Unit Test Generator for details and the VS Code extension with 1M+ installs.