惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
Google DeepMind News
Google DeepMind News
H
Help Net Security
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
T
Troy Hunt's Blog
Recent Announcements
Recent Announcements
GbyAI
GbyAI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security @ Cisco Blogs
S
Secure Thoughts
Y
Y Combinator Blog
D
Docker
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
N
News and Events Feed by Topic
aimingoo的专栏
aimingoo的专栏
I
InfoQ
P
Palo Alto Networks Blog
F
Full Disclosure
C
Cyber Attacks, Cyber Crime and Cyber Security
The Register - Security
The Register - Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Heimdal Security Blog
G
Google Developers Blog
Webroot Blog
Webroot Blog
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
W
WeLiveSecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
Help Net Security
Help Net Security
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
TaoSecurity Blog
TaoSecurity Blog
博客园 - 三生石上(FineUI控件)
T
Threatpost
V
V2EX
AWS News Blog
AWS News Blog
O
OpenAI News
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
TDD with AI: Claude Writes Tests First, Then the Implementation
Roman Belov · 2026-05-12 · via DEV Community

Most teams know TDD works. Few actually practice it. The friction is real: writing a test before the implementation means thinking through the API, edge cases, and module contract before a single line of logic exists. That's cognitively expensive.

An AI assistant removes this barrier. Claude Code turns test-first from a discipline exercise into a natural development workflow. Tests become the specification, and the implementation is generated against them.

Why TDD Stalls Without AI

The classic TDD cycle: Red → Green → Refactor. Write a failing test, make it pass with minimal code, then refactor. In practice, the cycle breaks at the first step.

A developer sits down to write a test for a new module. But writing the test requires defining the interface, which requires understanding the architecture, which requires at least mentally sketching the implementation. The circle closes on itself.

Three concrete problems:

Designing an API from scratch. A test requires calling a function that doesn't exist yet. What arguments does it take? What does it return? What errors does it throw? Without a prototype implementation, these questions hang in the air.

Edge cases in the dark. Good tests cover boundary conditions. But boundary conditions only become visible once you understand the implementation. Empty arrays, null, timeouts, concurrent access — these are all much easier to spot when looking at code rather than a blank test file.

Motivation. A test that fails with "function not found" gives no sense of progress. The developer switches to the implementation "just to quickly verify the idea" — and never returns to test-first.

AI removes all three barriers. Claude generates a test specification from a description of the task, suggests edge cases based on data types and patterns, and creates an implementation strictly against the test contract.

Workflow: Test-First with Claude Code

The workflow has four steps. Each step has a concrete prompt and expected outcome.

Step 1. Specification via Tests

Claude Code prompt:

Write tests for the parseSchedule module.
Input: a free-form schedule string ("every Monday at 10:00", "daily at 9am").
Output: an object { dayOfWeek?: number, hour: number, minute: number, recurring: boolean }.
Cover: valid strings in EN/RU, invalid input, empty string, null.
Use vitest. Do not write the implementation.

Enter fullscreen mode Exit fullscreen mode

Claude generates the test file:

import { describe, it, expect } from 'vitest';
import { parseSchedule } from './parseSchedule';

describe('parseSchedule', () => {
  describe('english input', () => {
    it('parses "every Monday at 10:00"', () => {
      const result = parseSchedule('every Monday at 10:00');
      expect(result).toEqual({
        dayOfWeek: 1,
        hour: 10,
        minute: 0,
        recurring: true,
      });
    });

    it('parses "daily at 9am"', () => {
      const result = parseSchedule('daily at 9am');
      expect(result).toEqual({
        hour: 9,
        minute: 0,
        recurring: true,
      });
    });

    it('parses "Friday 14:30"', () => {
      const result = parseSchedule('Friday 14:30');
      expect(result).toEqual({
        dayOfWeek: 5,
        hour: 14,
        minute: 30,
        recurring: false,
      });
    });
  });

  describe('russian input', () => {
    it('parses "каждый понедельник в 10:00"', () => {
      const result = parseSchedule('каждый понедельник в 10:00');
      expect(result).toEqual({
        dayOfWeek: 1,
        hour: 10,
        minute: 0,
        recurring: true,
      });
    });

    it('parses "ежедневно в 9:00"', () => {
      const result = parseSchedule('ежедневно в 9:00');
      expect(result).toEqual({
        hour: 9,
        minute: 0,
        recurring: true,
      });
    });
  });

  describe('edge cases', () => {
    it('throws on empty string', () => {
      expect(() => parseSchedule('')).toThrow('Invalid schedule format');
    });

    it('throws on null', () => {
      expect(() => parseSchedule(null as any)).toThrow();
    });

    it('throws on unrecognized format', () => {
      expect(() => parseSchedule('maybe sometime')).toThrow(
        'Invalid schedule format'
      );
    });

    it('handles extra whitespace', () => {
      const result = parseSchedule('  daily   at   9am  ');
      expect(result).toEqual({
        hour: 9,
        minute: 0,
        recurring: true,
      });
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

All tests fail — parseSchedule doesn't exist. That's expected: the Red phase is complete.

What just happened: the tests locked in the contract. Input type, output structure, behavior on edge cases, supported formats. This file is already a full specification for the module.

Step 2. Minimal Implementation

Prompt:

Write an implementation of parseSchedule that passes all tests in parseSchedule.test.ts.
Minimal code. No extra features. Only what the tests require.

Enter fullscreen mode Exit fullscreen mode

Claude reads the test file, extracts the expectations, and generates the implementation:

const EN_DAYS: Record<string, number> = {
  sunday: 0, monday: 1, tuesday: 2, wednesday: 3,
  thursday: 4, friday: 5, saturday: 6,
};

const RU_DAYS: Record<string, number> = {
  воскресенье: 0, понедельник: 1, вторник: 2, среда: 3,
  четверг: 4, пятница: 5, суббота: 6,
};

interface Schedule {
  dayOfWeek?: number;
  hour: number;
  minute: number;
  recurring: boolean;
}

export function parseSchedule(input: string): Schedule {
  if (!input || typeof input !== 'string') {
    throw new Error('Invalid schedule format');
  }

  const normalized = input.trim().replace(/\s+/g, ' ').toLowerCase();
  if (!normalized) throw new Error('Invalid schedule format');

  const recurring =
    normalized.startsWith('every') ||
    normalized.startsWith('каждый') ||
    normalized.startsWith('каждая') ||
    normalized.startsWith('каждое') ||
    normalized.includes('daily') ||
    normalized.includes('ежедневно');

  const timeMatch = normalized.match(/(\d{1,2}):(\d{2})/);
  const amPmMatch = normalized.match(/(\d{1,2})(am|pm)/);

  let hour: number;
  let minute: number;

  if (timeMatch) {
    hour = parseInt(timeMatch[1], 10);
    minute = parseInt(timeMatch[2], 10);
  } else if (amPmMatch) {
    hour = parseInt(amPmMatch[1], 10);
    minute = 0;
    if (amPmMatch[2] === 'pm' && hour !== 12) hour += 12;
    if (amPmMatch[2] === 'am' && hour === 12) hour = 0;
  } else {
    throw new Error('Invalid schedule format');
  }

  const allDays = { ...EN_DAYS, ...RU_DAYS };
  let dayOfWeek: number | undefined;

  for (const [name, num] of Object.entries(allDays)) {
    if (normalized.includes(name)) {
      dayOfWeek = num;
      break;
    }
  }

  const result: Schedule = { hour, minute, recurring };
  if (dayOfWeek !== undefined) result.dayOfWeek = dayOfWeek;

  return result;
}

Enter fullscreen mode Exit fullscreen mode

Run the tests: all green. Green phase complete.

Step 3. Refactoring Under Test Coverage

Prompt:

Refactor parseSchedule. Extract time and day parsing into separate functions.
Tests must not change. All must remain green.

Enter fullscreen mode Exit fullscreen mode

Claude performs the refactoring and runs tests after each change. The tests are the safety net: if the refactoring breaks something, it's immediately visible.

Step 4. Extending Through New Tests

Need to add support for the "every 2 hours" format? Write the test first:

it('parses interval "every 2 hours"', () => {
  const result = parseSchedule('every 2 hours');
  expect(result).toEqual({
    intervalHours: 2,
    recurring: true,
  });
});

Enter fullscreen mode Exit fullscreen mode

Test fails. Claude prompt: "Make this test pass without breaking the existing ones." The cycle repeats.

Claude Code Prompt Templates for Test-First

Generating Tests for a New Module

Write tests for [module/function].
Context: [what the module does, what data it processes].
Input: [types, examples].
Expected output: [structure, types].
Edge cases: [specific cases or "suggest them yourself"].
Framework: [vitest/jest/pytest].
DO NOT write the implementation.

Enter fullscreen mode Exit fullscreen mode

Generating Implementation from Tests

Write an implementation of [module] that passes all tests in [file.test.ts].
Minimal code. No unnecessary abstractions. Only what the tests require.

Enter fullscreen mode Exit fullscreen mode

Expanding Coverage

Analyze [module] and its tests.
What scenarios are not covered? Add tests for missing edge cases.
Do not modify existing tests.

Enter fullscreen mode Exit fullscreen mode

Refactoring

Refactor [module]. Tests must not change.
Goal: [readability / performance / extensibility].
Run tests after changes.

Enter fullscreen mode Exit fullscreen mode

Comparison: Test-First vs Code-First with AI

In practice, developers use AI in two ways: ask it to generate code first, then tests (code-first), or the other way around (test-first). The difference in outcomes is significant.

Criterion Code-first + AI Test-first + AI
Test quality Tests are retrofitted to the implementation and miss bugs Tests reflect requirements and catch real problems
Edge case coverage AI tests what it wrote, not what was needed Edge cases are defined from the specification
Refactoring Risky to change: tests may break Safe: tests are bound to the contract, not the implementation
Speed Faster at the start Faster in the long run
API quality API forms organically API is designed through tests

The key difference: with code-first, AI generates tests that check what the code does. With test-first, AI generates tests that check what the code should do. The difference becomes critical during refactoring and feature expansion.

Real Example: A Validator with LLM-as-Judge

A practical task: an AI response validation module using LLM-as-Judge. The goal is to check that an LLM's response meets quality criteria.

Tests are written first:

describe('ResponseValidator', () => {
  it('accepts response meeting all criteria', async () => {
    const result = await validator.validate({
      response: 'Paris is the capital of France.',
      criteria: {
        factual: true,
        maxLength: 100,
        language: 'en',
      },
    });
    expect(result.passed).toBe(true);
    expect(result.scores.factual).toBeGreaterThan(0.8);
  });

  it('rejects response failing factual check', async () => {
    const result = await validator.validate({
      response: 'Berlin is the capital of France.',
      criteria: { factual: true },
    });
    expect(result.passed).toBe(false);
    expect(result.failures).toContain('factual');
  });

  it('handles LLM provider timeout', async () => {
    const result = await validator.validate({
      response: 'test',
      criteria: { factual: true },
      timeout: 100,
    });
    expect(result.passed).toBe(false);
    expect(result.error).toBe('timeout');
  });
});

Enter fullscreen mode Exit fullscreen mode

The tests defined: the validate() interface, the criteria structure, the result format, and behavior on timeout. This is a complete specification. Claude implements the module strictly against the contract, including error handling that's easy to forget with a code-first approach.

If your project already has multi-agent code review in place, tests go through review alongside the code. The agents verify that tests cover all declared scenarios and that the implementation doesn't go beyond the contract.

Patterns and Anti-Patterns

What Works Well

One test, one behavior. Claude generates a precise implementation when each test checks exactly one aspect. "Parses a date in ISO format" — good. "Parses a date and validates and formats" — bad.

Typed expectations. Instead of expect(result).toBeTruthy()expect(result).toEqual({ ... }). The more precise the expectation, the more precise the implementation.

Tests as documentation. The test name describes behavior: it('returns empty array when no items match filter'). Claude uses it to understand intent.

What Doesn't Work

Tests on internal implementation. expect(cache.store).toHaveBeenCalledWith('key', 'value') — binding to the implementation. The test will break on refactoring even though behavior didn't change.

Too many mocks. If a test needs five dependencies mocked, the problem is in the architecture, not the tests. Claude will create a working mock, but the implementation will be brittle.

Generating tests and code in one prompt. "Write a function and tests for it" — that's code-first with the illusion of test-first. The tests will be retrofitted to the implementation. Always split into two steps.

TDD for Infrastructure Code

Test-first works not just for business logic. For infrastructure modules, like a circuit breaker for edge functions, tests are especially valuable.

describe('CircuitBreaker', () => {
  it('stays closed after successful calls', async () => {
    const breaker = new CircuitBreaker({ failureThreshold: 3 });
    await breaker.call(() => Promise.resolve('ok'));
    await breaker.call(() => Promise.resolve('ok'));
    expect(breaker.state).toBe('closed');
  });

  it('opens after reaching failure threshold', async () => {
    const breaker = new CircuitBreaker({ failureThreshold: 2 });
    await ignoreError(() => breaker.call(() => Promise.reject('fail')));
    await ignoreError(() => breaker.call(() => Promise.reject('fail')));
    expect(breaker.state).toBe('open');
  });

  it('rejects calls immediately when open', async () => {
    const breaker = openCircuitBreaker();
    await expect(breaker.call(() => Promise.resolve('ok')))
      .rejects.toThrow('Circuit is open');
  });

  it('transitions to half-open after cooldown', async () => {
    vi.useFakeTimers();
    const breaker = openCircuitBreaker({ cooldownMs: 5000 });
    vi.advanceTimersByTime(5000);
    expect(breaker.state).toBe('half-open');
    vi.useRealTimers();
  });
});

Enter fullscreen mode Exit fullscreen mode

A state machine circuit breaker is fully described through tests: state transitions, thresholds, timers. Claude generates an implementation that correctly handles all transitions because every transition is pinned in a test.

Metrics: What to Measure

Defect escape rate. How many bugs slip past tests into production. With test-first, this number drops because edge cases are covered before any code is written.

Refactoring time. With tests bound to the contract, refactoring is safe. Without them, every change requires manual verification.

Coverage on the first pass. With a code-first approach, coverage after the first iteration is usually 40–60%. With test-first — 80–90%, because the tests already define all the main scenarios.

Number of iterations to green. With well-written tests, Claude passes all of them on the first generation. If more than two iterations are needed, the tests are too vague or contradictory.

Getting Started

There's no need to convert an entire project to TDD in one day. Starting with a single new module is enough.

1. Pick an isolated module. A utility function, a validator, a parser. A module without heavy dependencies where inputs and outputs are easy to define.

2. Write tests with a prompt. Use the template from the section above. Describe the input, expected output, and edge cases. Let Claude generate the test file.

3. Confirm the tests fail. Run the tests. All should be red. If something is green without an implementation — the test is incorrect.

4. Generate the implementation. In a separate prompt, ask Claude to write code that passes all the tests. Don't add "and also do X" — only what's in the tests.

5. Run, refactor, repeat. Green tests — refactor. New requirements — new tests. The Red → Green → Refactor cycle runs without friction when AI handles the generation.

AI doesn't replace TDD. AI makes TDD practical. The cognitive load of designing APIs through tests drops, the speed of the cycle increases, and the quality of the contract stays on par with manual design.


More articles on AI-assisted development workflows at futurecraft.pro. Need help building AI products? — belov.works.