Try free

Last updated 13 October 2026

Generate unit tests using Claude Code

Project instructions guide the agent

Claude Code needs to understand your coding style and testing framework before it writes a single line. The agent looks for a file named CLAUDE.md in the root of your repository to understand project standards. You should define your preferred testing library, such as Jest, Vitest, or Pytest, inside this file. Explicitly state where test files should live, whether they are co-located with source code or kept in a separate directory. Describe the naming convention for test files so the agent follows your existing patterns without guessing.

If you have specific requirements for mocking or dependency injection, document these in CLAUDE.md as well. The agent reads this file at the start of a session to set its internal state. Without these instructions, the agent might use a different testing framework than the one your project uses. You can also create a CLAUDE.md file in a subdirectory if a specific part of your tree requires different testing rules. This ensures that the generated code fits into your architecture immediately. Providing clear examples of existing tests in this file will significantly improve the accuracy of the new suites the agent generates.

Initiating the test generation session

Run the command claude in your terminal to start an interactive session. Once the agent is active, you can provide a direct prompt to analyze a specific file and generate tests for it. For example, you might ask the agent to read a file and write a test suite that covers all exported functions. The agent will use the Read tool to examine your source code and the Glob tool to find related files or existing test patterns. It will then use the Write tool to create the new test file or the Edit tool to append to an existing one.

You can control the level of autonomy the agent has by switching permission modes. Pressing Shift+Tab cycles through default, acceptEdits, plan, and bypassPermissions modes. If you want to see exactly what tests the agent proposes before it writes them to disk, use the plan mode. This allows you to review the logic and ensure the test cases align with your expectations. If you are confident in the project instructions you provided in CLAUDE.md, the default mode or acceptEdits mode will speed up the process by allowing the agent to apply changes after your approval.

Expanding coverage for edge cases and errors

Standard unit tests often miss complex edge cases like null inputs, network timeouts, or boundary conditions in mathematical logic. You can prompt the agent to specifically look for these vulnerabilities after the initial test suite is written. Ask the agent to identify potential failure points in the logic and write additional test cases to handle them. The agent uses its reasoning capabilities to trace execution paths and suggest inputs that might trigger unhandled exceptions or logic errors. This proactive approach helps you find bugs before they reach production.

As the conversation grows longer, the context window fills up with the code it has read and the tests it has written. You can use the /compact command to summarize the session so far and free up space for more complex analysis. This is particularly useful when you are working on a large module with dozens of functions. If the agent starts to lose track of the original requirements because of a long history, /compact helps it maintain focus on the current task of improving test coverage. You can also use the /clear command if you want to start over with a fresh context in the same folder.

Running and verifying tests within the session

Writing the tests is only half the job; they must actually pass in your environment. You can ask the agent to run your test runner using the Bash tool directly from the interface. For instance, tell the agent to run the command for your test suite and report any failures. If a test fails, the agent can read the error output from the terminal and use the Edit tool to fix either the test or the source code, depending on where the bug lies. This creates a tight feedback loop that ensures the generated tests are functional and accurate.

The agent can also use the Grep tool to find existing tests that might be relevant or might conflict with the new ones. By searching for specific function names across the repository, the agent ensures that it does not duplicate effort or create redundant test suites. If you need to see the current state of the project or verify the files created, you can use the /status command. This shows you which files have been modified during the session and provides a summary of the work completed. Using the /review command allows you to get a summary of the changes before you commit them to your repository.

Using adhdTerminal for concurrent test generation

When you have a large project with many components, generating tests one file at a time in a single terminal can feel slow. This is where adhdTerminal becomes a useful part of your workflow. It allows you to run many Claude Code sessions side by side, with each session appearing as a tile on a wall. You can dedicate one tile to testing your API layer, another to your utility functions, and a third to your UI components. Each tile has a color, a number, and a name, making it easy to track the progress of multiple test generation tasks at once.

The interface of adhdTerminal shows whether a session is working, waiting for your input, or finished. This visibility is helpful when you are asking the agent to perform deep analysis on several different modules. You can glance at the wall to see which sessions are done and which ones need you to approve a permission request. Because tiles reopen in the same place after a restart and resume the same session, you can break a large testing overhaul into smaller pieces and pick up exactly where you left off. This approach reduces the cognitive load of switching between terminal tabs and keeps your focus on the broader testing strategy.

Managing global and local testing preferences

You can influence how the agent writes tests across all your projects by using the global configuration file. A CLAUDE.md file located at ~/.claude/CLAUDE.md applies to every session you run on your machine. This is the ideal place to put general preferences, such as a preference for descriptive test names or a specific style of assertions. If you always use a certain library for mocking time or filesystem access, putting that instruction in the global file saves you from repeating it in every new repository.

For settings that should not be shared with your team or tracked in version control, use the .claude/settings.local.json file. This file allows you to override project-wide settings for your own environment. You might use this to configure specific permissions or to point the agent toward local tools that are not part of the standard CI/CD pipeline. To see your current configuration or verify which settings are active, use the /config command inside a session. This helps you understand why the agent is making certain decisions or using specific tools during the test generation process.

Leveraging hooks and subagents for complex suites

Claude Code supports hook events that trigger at specific points in its workflow. You can use events like PostToolUse or UserPromptSubmit to automate certain parts of the testing process. For example, you could set up a hook that automatically runs a linter after the agent uses the Write tool to create a new test file. This ensures that all generated code adheres to your formatting rules before you even look at it. You can define these behaviors in the settings.json file under the hooks section to create a customized testing pipeline.

If a testing task is particularly large, you can use subagents to handle specific parts of the work. Subagents are defined as markdown files in the .claude/agents directory. You might create a subagent specifically designed to generate mock data or to write integration tests for database interactions. By calling these subagents using the /agents command, you can delegate specialized tasks to a focused context. This keeps the main session clean and prevents the context window from becoming overwhelmed with unnecessary details from secondary tasks, making the overall test generation process more efficient.

Closing the session and exporting results

Once you are satisfied with the generated tests, you can wrap up the session and move the code into your main branch. Use the /cost or /usage commands to see the financial impact of the session and ensure you are staying within your budget. If you need to share the reasoning behind the generated tests with your team, use the /export command to save the conversation history. This can be valuable for documentation or for explaining why certain edge cases were prioritized during the test generation process. The exported logs can also help you refine your CLAUDE.md instructions for future sessions.

To end the session, use Ctrl+C or simply type a request for the agent to stop. If you want to clear the conversation but stay in the same directory to start a new task, use the /clear command. If you realize later that you need to add more tests to the same module, you can return to the folder and run claude --continue to pick up the most recent session. This persistence allows you to build a comprehensive test suite over several days without losing the context of your previous work. The agent remembers the files it read and the tests it wrote, ensuring continuity in your development workflow.

Questions people ask

How do I make the agent use my specific test library?

You should define your testing framework in the CLAUDE.md file at the root of your project. Specify the library name and the preferred syntax for assertions and mocks. The agent reads this file at the start of every session to ensure its output matches your project standards.

What should I do if the agent generates a test that fails?

If a generated test fails, you can use the Bash tool to run the test and share the output with the agent. Ask the agent to analyze the error and determine if the test logic or the source code needs a fix. The agent can then use the Edit tool to apply the necessary corrections.

Can I use Claude Code to update existing tests when code changes?

Yes, you can provide the agent with the updated source code and the existing test file. Ask it to identify which tests are now broken or obsolete and request that it updates them to reflect the new behavior. The agent will use the Read and Edit tools to synchronize your test suite with your implementation.

Read next

More on claude code basics·All posts