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

推荐订阅源

博客园_首页
H
Help Net Security
量子位
The Cloudflare Blog
博客园 - Franky
博客园 - 聂微东
博客园 - 司徒正美
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
罗磊的独立博客
GbyAI
GbyAI
雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
美团技术团队
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
MongoDB | Blog
MongoDB | 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
Dr. Strangelove or How I Learned to Stop Worrying and Lov...
lmilz · 2026-05-14 · via DEV Community

lmilz

When I was still programming at university, my “testing” looked roughly like this:

std::cout << "Value: " << value << std::endl;

Enter fullscreen mode Exit fullscreen mode

along with some classic debugging: setting breakpoints, inspecting variables, stepping through the code. Looking back, this was clearly not an effective approach. I don’t even want to know how many bugs went unnoticed back then. Over several professional roles, I gradually improved my testing skills. In my first job, I initially continued exactly as I had done at university. Later, I had the chance to dive deeper into testing. At that time, my workflow looked like this: implement changes, document them, integrate, deploy, and only then start testing. This naturally led to discovering bugs late, being unable to fix them right away, and shipping bugfixes only with the next release.

This became increasingly frustrating for me. At the same time, I noticed that many developers “automate” their manual debugging process by reproducing the implementation inside their tests. This is a classic anti-pattern: you end up testing the implementation instead of the behavior. If you simply reproduce the production code in your tests, you're effectively writing the same code twice and that adds no value.

I started with small steps: whenever I worked on a new feature, I wrote tests immediately. In parallel, I began adding tests to our legacy codebase to gain experience building a meaningful and maintainable test suite.

Early on, I fell into the usual traps myself: I recreated the implementation in the test or wrote tests that were so granular that the suite became hard to maintain.

Along the way, I realized that testing is not just testing. In particular, we distinguish between:

  • Verification: Are we building the product right?
  • Validation: Are we building the right product?

Consider a simple example: a football field has exact specifications. If those are implemented correctly, verification is satisfied. But whether you can play well on that field is a matter of validation. A field can meet all technical requirements and still be unplayable if the ground is uneven or sloped.

Eventually, I had a kind of Eureka moment: proper testing is a learning process. In a way, it felt like my own little Dr. Strangelove moment. I stopped worrying about breaking things and started to love testing. Because once your tests define the expected behavior, fear turns into confidence.
Tests help me understand how the code is meant to behave and provide immediate feedback. The only problem was that my feedback always came too late. So I looked for ways to move it earlier in the process.

After many iterations, I finally found the answer to my problem: I must not test the implementation, I must test the behavior. The method that enforces exactly this is called Test-Driven Development (TDD).

TDD is often misunderstood. It’s not a testing technique but a design method. Tests are the tool we use to shape the design. TDD can be used for both verification and validation.

To demonstrate my approach, I’ll use the calculation of the inverse square root. This function is used to normalize vectors. From this, we can derive verifiable mathematical properties as well as validation tests based on intended behavior. These properties must hold regardless of the internal implementation of inverse_sqrt. Below is an example of the tests (with the input data inputs and vectors omitted for readability):

// ------------------------------------------------------------
// 1. Positivity Test
//    f(x) > 0 for all x > 0
// ------------------------------------------------------------
#[test]
fn always_positive() {
    for &x in &inputs {
        assert!(inverse_sqrt(x) > 0.0);
    }
}

// ------------------------------------------------------------
// 2. Monotonicity Test
//    f(x) decreases as x increases
// ------------------------------------------------------------
#[test]
fn monotony() {
    for i in 0..inputs.len() - 1 {
        assert!(inverse_sqrt(inputs[i]) > inverse_sqrt(inputs[i + 1]));
    }
}

// ------------------------------------------------------------
// 3. Product Rule Test
//    f(a·b) ≈ f(a)·f(b)
// ------------------------------------------------------------
#[test]
fn product_rule() {
    for i in 0..inputs.len() - 1 {
        let a = inputs[i];
        let b = inputs[i + 1];
        let x1 = inverse_sqrt(a * b);
        let x2 = inverse_sqrt(a) * inverse_sqrt(b);
        assert!((x1 - x2).abs() < 0.25);
    }
}

// ------------------------------------------------------------
// 4. Division Rule Test
//    f(a/b) ≈ f(a)/f(b)
// ------------------------------------------------------------
#[test]
fn division_rule() {
    for i in 0..inputs.len() - 1 {
        let a = inputs[i];
        let b = inputs[i + 1];
        let x1 = inverse_sqrt(a / b);
        let x2 = inverse_sqrt(a) / inverse_sqrt(b);
        assert!((x1 - x2).abs() < 2.5);
    }
}

// ------------------------------------------------------------
// 5. Validation: Normalization Length
//    A vector normalized with this function should have length ≈ 1
// ------------------------------------------------------------
#[test]
fn normalization_length_is_one() {
    for &(x, y, z) in &vectors {
        let n = normalize(x, y, z);
        let len = (n.0 * n.0 + n.1 * n.1 + n.2 * n.2).sqrt();
        assert!((len - 1.0).abs() < 1e-6);
    }
}

Enter fullscreen mode Exit fullscreen mode

Now it gets practical: you write the implementation and the tests immediately verify whether it behaves as expected. This instant feedback is one of the greatest strengths of TDD. The test run produces results like these:

running 5 tests
test tests::monotony ... ok
test tests::division_rule ... ok
test tests::always_positive ... ok
test tests::normalization_length_is_one ... ok
test tests::product_rule ... ok

test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Enter fullscreen mode Exit fullscreen mode

This illustrates the essence of TDD: define the behavior first, then write the implementation that fulfills it.

Another essential benefit: once tests clearly define the expected behavior, you can refactor the implementation without fear. The tests act as a safety net. They ensure that the visible behavior remains unchanged, even if the internals change dramatically.

To make this even more concrete, here’s a small example that shows the real power of testing for behavior: you can completely change the implementation, yet the tests and therefore the behavior remain unchanged.

Consider a simple function that filters out negative numbers. The tests describe what the function must do, not how it must do it:

#[test] 
fn filters_out_negative_numbers() {     
    let input = vec![3, -1, 0, -5, 9];     
    let result = filter_positive(&input);     
    assert_eq!(result, vec![3, 0, 9]); 
}  

#[test] 
fn keeps_order() {     
    let input = vec![5, 2, 8];     
    let result = filter_positive(&input);     
    assert_eq!(result, input); 
}

Enter fullscreen mode Exit fullscreen mode

These tests specify two behaviors:

  1. Negative numbers must be removed.
  2. The order of the remaining elements must be preserved.

Now here is the first, simple implementation, fully correct but not particularly elegant:

fn filter_positive(values: &[i32]) -> Vec<i32> {     
    let mut result = Vec::new();     
    for v in values {         
        if *v >= 0 {             
            result.push(*v);         
        }     
    }     
    result 
}

Enter fullscreen mode Exit fullscreen mode

Later, you might want to refactor it into a more idiomatic and functional style:

fn filter_positive(values: &[i32]) -> Vec<i32> {    
    values.iter().copied().filter(|v| *v >= 0).collect() 
}

Enter fullscreen mode Exit fullscreen mode

The internal implementation is now completely different, yet the behavior remains exactly the same.

And that's the crucial point: the tests still pass without changing a single line of them. They don't care how the behavior is achieved. They only care that it is achieved. This is exactly the kind of freedom and safety TDD provides: the ability to evolve and improve internal code confidently, without risking regressions.

This is how software is created that not only works but also remains maintainable and evolvable over time, a core principle of good software design.

Looking back, I don’t write tests today because I’m “supposed to”. I write them because they make me faster, calmer, and better at my craft.