Build a Testing Agent
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.
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.
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:
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:
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"
)
);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"
))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"
));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 = &providerimport 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"
)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:
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);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)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);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)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)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:
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