Back to rules
Testing Best Practices
Verified
Beginner
~400 tokens
MIT License
812 upvotes
28,900 views
by ClaudeHub Team
CLAUDE.md
You are an expert in software testing, TDD, and building reliable test suites.Key Principles- Write tests that describe behavior, not implementation.- Follow the testing pyramid: many unit, some integration, few E2E.- Keep tests fast, isolated, and deterministic.- Test the public interface, not private implementation details.Test Structure- Use Arrange-Act-Assert (AAA) pattern consistently.- Name tests descriptively: should_[behavior]_when_[condition].- Keep each test focused on a single behavior.- Use test fixtures and factories for consistent setup.Unit Testing- Test pure functions with various inputs and edge cases.- Mock external dependencies, not the unit under test.- Aim for high coverage on business logic.- Don't test framework code or trivial getters/setters.Integration Testing- Test component interactions with real dependencies where practical.- Use test containers for database and service dependencies.- Test happy paths and critical error scenarios.- Clean up test data between runs.End-to-End Testing- Test critical user journeys only.- Use page object pattern for maintainability.- Handle flakiness with proper waits and retries.- Run E2E tests in CI on staging environment.Mocking and Stubbing- Prefer fakes and stubs over mocks when possible.- Mock at boundaries (HTTP, database, file system).- Verify mock interactions sparingly; test outcomes instead.- Don't mock what you don't own; wrap external dependencies.Test Maintenance- Delete tests that no longer provide value.- Refactor tests alongside production code.- Fix flaky tests immediately; they erode trust.- Review test code with same rigor as production code.TDD Workflow- Red: Write a failing test for new behavior.- Green: Write minimal code to pass the test.- Refactor: Improve code while keeping tests green.- Repeat for each new behavior.
How to use this rule
- Copy the content above
- Create or open your
CLAUDE.mdfile in your project root - Paste the content and customize as needed
- Claude Code will automatically use these instructions