---
title: "Build a Testing Agent"
description: "Learn how to create a coding assistant that automatically generates unit tests and integration tests with the Autohand Code Agent SDK. Available in TypeScript, Python, Java, Go, Swift, and Rust."
slug: "agent-sdk/tutorials/600-testing-agent"
sidebar:
  label: "Testing agent"
seo:
  title: "Testing Agent | Autohand Code"
  description: "Build a testing coding assistant with the Autohand Code Agent SDK. Learn how to create agents that automatically generate unit tests and integration tests."
---

In this tutorial, you'll build a testing coding assistant that reads source code, understands its functionality, and automatically generates comprehensive unit tests. This demonstrates how to use the Agent SDK for automated testing.

:::note
**Prerequisites:**

- Completed [Code Reviewer Agent](/agent-sdk/tutorials/100-code-reviewer-agent)
- Node.js 16+ (for TypeScript), Python 3.10+ (for Python), Java 11+ (for Java), Go 1.16+ (for Go), Swift 5.5+ (for Swift), or Rust 1.60+ (for Rust)
- SDK installed for your chosen language
- API key from your LLM provider (set as `AUTOHAND_API_KEY`)
:::

## What You'll Build

A testing coding assistant that:

- Reads source code files
- Understands function behavior and edge cases
- Generates unit tests with assertions
- Covers edge cases and error conditions
- Runs tests and reports results
- Supports multiple testing frameworks

## Step 1: Create Sample Code

Create a sample code file to test in your chosen language:

```ts
import * as fs from "fs";
import * as path from "path";

function createSampleCode(tmpdir: string): void {
  const code = "export const divide = (a: number, b: number) => { if (b === 0) throw new Error('Division by zero'); return a / b; };\n";
  fs.writeFileSync(path.join(tmpdir, "calculator.ts"), code);
}
```

## Step 2: Create Testing Agent

Create an agent with test generation capabilities in your chosen language:

```ts title="TypeScript"
import { Agent, Runner } from "@autohandai/agent-sdk";
import { OpenRouterProvider } from "@autohandai/agent-sdk";

const testGenerator = new Agent(
  "Test Generator",
  "You are a testing expert. Read source code files, understand their functionality, and generate comprehensive unit tests. Cover normal cases, edge cases, and error conditions. Use Jest or Mocha syntax for TypeScript. Include assertions and test descriptions.",
  ["read_file", "write_file", "bash"],
  15
);

testGenerator.setProvider(
  new OpenRouterProvider(
    process.env.AUTOHAND_API_KEY!,
    "z-ai/glm-5.2"
  )
);
```

```python title="Python"
from autohand_agent_sdk import Agent, Runner, OpenRouterProvider

test_generator = Agent(
    name="Test Generator",
    instructions="You are a testing expert. Read source code files, understand their functionality, and generate comprehensive unit tests. Cover normal cases, edge cases, and error conditions. Use pytest syntax for Python. Include assertions and test descriptions.",
    tools=["read_file", "write_file", "bash"],
    max_turns=15
)

test_generator.set_provider(OpenRouterProvider(
    api_key=os.getenv("AUTOHAND_API_KEY"),
    model="z-ai/glm-5.2"
))
```

```java title="Java"
import ai.autohand.agent.sdk.*;
import ai.autohand.agent.sdk.providers.*;

Agent testGenerator = new Agent(
    "Test Generator",
    "You are a testing expert. Read source code files, understand their functionality, and generate comprehensive unit tests. Cover normal cases, edge cases, and error conditions. Use JUnit syntax for Java. Include assertions and test descriptions.",
    DefaultToolRegistry.getTools("read_file", "write_file", "bash"),
    15
);

testGenerator.setProvider(new OpenRouterProvider(
    System.getenv("AUTOHAND_API_KEY"),
    "z-ai/glm-5.2"
));
```

```go title="Go"
package main

import (
    "os"
    "github.com/autohandai/agentsdk-go/pkg/autohand"
)

testGenerator := autohand.Agent{
    Name:         "Test Generator",
    Instructions: "You are a testing expert. Read source code files, understand their functionality, and generate comprehensive unit tests. Cover normal cases, edge cases, and error conditions. Use Go testing syntax. Include assertions and test descriptions.",
    Tools:        []autohand.Tool{autohand.ReadFile, autohand.WriteFile, autohand.Bash},
    MaxTurns:     15,
}

provider := autohand.NewOpenRouterProvider(
    os.Getenv("AUTOHAND_API_KEY"),
    "z-ai/glm-5.2",
)
testGenerator.Provider = &provider
```

```swift title="Swift"
import AutohandAgentSDK

let testGenerator = Agent(
    name: "Test Generator",
    instructions: "You are a testing expert. Read source code files, understand their functionality, and generate comprehensive unit tests. Cover normal cases, edge cases, and error conditions. Use XCTest syntax for Swift. Include assertions and test descriptions.",
    tools: [.readFile, .writeFile, .bash],
    maxTurns: 15
)

testGenerator.provider = try OpenRouterProvider(
    apiKey: ProcessInfo.processInfo.environment["AUTOHAND_API_KEY"] ?? "your-api-key",
    model: "z-ai/glm-5.2"
)
```

```rust title="Rust"
use autohand_agents::{AgentBuilder, Runner};
use autohand_agents::providers::ProviderFactory;
use autohand_agents::config::ConfigLoader;

let mut test_generator = AgentBuilder::new()
    .name("Test Generator")
    .instructions("You are a testing expert. Read source code files, understand their functionality, and generate comprehensive unit tests. Cover normal cases, edge cases, and error conditions. Use Rust testing syntax. Include assertions and test descriptions.")
    .tools(vec![Tool::ReadFile, Tool::WriteFile, Tool::Bash])
    .max_turns(15)
    .build()?;

let config = ConfigLoader::from_env()?;
let provider = ProviderFactory::from_env(&config.provider)?;
test_generator.set_provider(provider);
```

## Step 3: Generate Tests

Run the test generator agent on your sample code in your chosen language:

```ts title="TypeScript"
const result = await Runner.run(
  testGenerator,
  "Read all source files in this directory. Generate comprehensive unit tests for each function. Cover normal cases, edge cases (division by zero, empty arrays), and error conditions. Create a test file with proper Jest syntax."
);

console.log(result.finalOutput);
```

```python title="Python"
result = Runner.run(
    test_generator,
    "Read all source files in this directory. Generate comprehensive unit tests for each function. Cover normal cases, edge cases (division by zero, empty arrays), and error conditions. Create a test file with proper pytest syntax."
)

print(result.final_output)
```

```java title="Java"
String result = Runner.run(
    testGenerator,
    "Read all source files in this directory. Generate comprehensive unit tests for each function. Cover normal cases, edge cases (division by zero, empty arrays), and error conditions. Create a test file with proper JUnit syntax."
);

System.out.println(result);
```

```go title="Go"
result, err := autohand.Runner.Run(&testGenerator, "Read all source files in this directory. Generate comprehensive unit tests for each function. Cover normal cases, edge cases (division by zero, empty arrays), and error conditions. Create a test file with proper Go testing syntax.")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result)
```

```swift title="Swift"
let result = try Runner.run(
    testGenerator,
    "Read all source files in this directory. Generate comprehensive unit tests for each function. Cover normal cases, edge cases (division by zero, empty arrays), and error conditions. Create a test file with proper XCTest syntax."
)

print(result)
```

```rust title="Rust"
let result = Runner::run(&test_generator, "Read all source files in this directory. Generate comprehensive unit tests for each function. Cover normal cases, edge cases (division by zero, empty arrays), and error conditions. Create a test file with proper Rust testing syntax.").await?;
println!("{}", result.final_output);
```

## Key Concepts

**Code Analysis**

The agent reads and analyzes source code to understand function behavior.

**Edge Case Coverage**

Tests cover normal cases, edge cases, and error conditions.

**Test Generation**

Using WRITE\_FILE to create comprehensive test files.

**Test Execution**

Using BASH to run tests and report results.

## Complete Example

Here's the complete example with cleanup:

```ts
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { Agent, Runner } from "@autohandai/agent-sdk";

async function main() {
  const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "testing-agent-example-"));
  const oldCwd = process.cwd();
  try {
    fs.writeFileSync(path.join(tmpdir, "calculator.ts"), "export const divide = (a: number, b: number) => { if (b === 0) throw new Error('Division by zero'); return a / b; };\n");
    const agent = new Agent("Test Generator", "Read source files and write focused unit tests.", ["read_file", "write_file", "bash"], 15);
    process.chdir(tmpdir);
    const result = await Runner.run(agent, "Create unit tests for calculator.ts, including division by zero.");
    console.log(result.finalOutput);
  } finally {
    process.chdir(oldCwd);
    fs.rmSync(tmpdir, { recursive: true, force: true });
  }
}

main();
```

## Real-World Applications

This pattern can be applied to:

- **Test automation:** Auto-generate tests for new code
- **Regression testing:** Ensure code changes don't break existing functionality
- **Code review:** Generate tests alongside code reviews
- **CI/CD integration:** Automatically test code before deployment
- **Legacy code testing:** Add tests to untested legacy codebases

## Next Steps

**[📁 View the Example](https://github.com/autohandai/agent-sdk-typescript/tree/main/examples)**

See the complete example in the SDK repositories.

**[📚 Explore More](/agent-sdk/overview)**

Check out all examples in the SDK repositories.
