今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

The One TDD Habit That Saved My Sanity (and My Codebase)

Timevolt 2026年06月05日 23:36 4 次阅读 来源:Dev.to

The One TDD Habit That Saved My Sanity (and My Codebase) Quick context (why you're writing this) Here's the thing: I used to think I was doing TDD right. I’d write a test, watch it fail, then write just enough code to make it green. Rinse and repeat. Sounds textbook, right? But a few months ago I spent an entire afternoon chasing a bug that only showed up after I refactored a service class. The tests were all passing, yet the app was throwing NullReferenceExceptions in production. I was shocked. How could everything be green and still be broken? Turns out I was testing the inside of my code instead of what it actually did for the outside world. That realization hit me like a truck, and it completely changed how I approach TDD. The Insight Test behavior, not implementation. If your test is coupled to private fields, internal data structures, or the exact way a method accomplishes its goal, you’re not testing what matters—you’re testing how you happen to do it today. When you later refactor to improve performance, swap out a dependency, or even just rename a variable, those tests start failing for no good reason. You end up spending more time fixing tests than delivering value, and you lose confidence in the suite because it feels fragile. The payoff? A test suite that gives you confidence when you change code, not anxiety. You can refactor fearlessly because the tests only care about the contract: given these inputs, the system should produce these outputs or side‑effects . How (with code) Let’s look at a tiny but realistic example: a PasswordValidator service that checks whether a user‑chosen password meets our policy. ❌ The mistake: testing implementation details // PasswordValidator.cs public class PasswordValidator { private readonly IRegexProvider _regex ; // injected for testability public PasswordValidator ( IRegexProvider regex ) { _regex = regex ; } public bool IsValid ( string password ) { // implementation we might want to change later return _regex . IsMa

本文内容来源于互联网,版权归原作者所有
查看原文