tdd
测试驱动开发 (Test-Driven Development)
哲学 (Philosophy)
核心原则 (Core principle):测试应该通过公共接口验证行为,而不是实现细节。代码可以完全改变;测试不应该。
Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
好测试 (Good tests) 是集成风格的:它们通过公共 API 操作真正的代码路径。它们描述系统做什么,而不是怎么做。一个好测试读起来像一个规格说明——"用户可以用有效的购物车结账"告诉你确切存在什么能力。这些测试在重构中存活,因为它们不关心内部结构。
Good tests are integration-style: they exercise real code paths through public APIs. They describe what the system does, not how it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
坏测试 (Bad tests) 与实现耦合。它们 mock 内部协作者、测试私有方法、或通过外部方式验证(比如直接查询数据库而不是使用接口)。警告信号:你的测试在重构时失败,但行为没有改变。如果你重命名一个内部函数而测试失败,那些测试是在测试实现,而不是行为。
Bad tests are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
见 tests.md 了解示例,mocking.md 了解 mock 指南。
See tests.md for examples and mocking.md for mocking guidelines.