文章摘要
文章探讨了如何让编写测试成为一种愉悦的体验,提出了"期望测试"的概念,通过简化测试流程和提升测试效率来改变开发者对测试的传统认知,使测试工作变得更加轻松有趣。
文章总结
标题:让编写测试成为一种愉悦体验?
核心内容:
Jane Street公司采用了一种名为"expect tests"(期望测试)的创新测试方法,将测试编写转变为类似REPL会话或Jupyter笔记本的交互式编程体验。这种方法通过自动化生成预期结果和即时反馈循环,显著提升了开发效率与愉悦感。
关键特点:
自动化预期生成
- 传统测试需手动编写断言(如
assert fibonacci(15) == 610) - Expect tests允许留空预期块(
[%expect {||}]),运行时自动填充正确结果 - 通过编辑器集成直接接受差异更新测试代码
- 传统测试需手动编写断言(如
三重价值
- 探索工具:快速验证函数行为(如数值舍入函数可通过表格直观呈现结果)
- 活文档:输入输出示例比文字描述更清晰
- 回归防护:冻结的输出成为后续变更的基准
对比传统单元测试
- RSpec等框架需显式声明每个断言(如
expect(@order).to be_complete) - Expect tests只需打印状态(
p @order)即可捕获完整上下文 - 意外变更(如订单数量从1变为100)会自动被检测
- RSpec等框架需显式声明每个断言(如
实际应用案例:
- Web UI测试:Bonsai框架测试中直接对比DOM树变化
- 系统操作测试:magic-trace工具用S表达式记录程序执行轨迹
- 状态机测试:金融订单簿状态通过结构化文本直观展现
优势与反思:
- 降低测试门槛:自动生成预期结果减少编写负担
- 提升覆盖率:隐性捕获更多行为细节(如未显式检查的字段)
- 可读性平衡:需通过辅助函数精简输出,避免信息过载
行业趋势:
类似方法(如Rust的expect-test、Jest的快照测试)正逐渐普及,可能成为未来测试主流范式。
(注:原文中公司介绍、导航菜单、标签列表等非核心内容已精简,保留技术实质和典型示例)
评论总结
评论总结
1. 支持自动化测试的观点
- 主要论据:自动化测试工具可以提升开发效率,使测试过程更轻松愉快。
- "I really like this style of testing -- code that can be tested this way is also the most fun kind of code to work with and the most likely to behave predictably." (breatheoften)
- "Can confirm that auto updating golden test assertions does make working with a test suite much more joyful than struggling with each assertion by hand" (lihaoyi)
2. 对自动化测试的质疑
- 主要论据:自动化测试可能掩盖错误,无法验证代码的正确性。
- "This assumes the code you wrote is already correct and giving the correct answer, so why bother writing tests?" (shruubi)
- "Yeah… no kidding that’s easier. We gloss over errors — 'some things just looked incorrect' — well, but how do you know that any differently than fib(10)?" (deathanatos)
3. 测试的实用性与乐趣
- 主要论据:测试可以是一种愉快的体验,尤其是当测试环境与真实环境一致时。
- "There’s some cool ideas about unit testing here, and I know I’m kind of missing the point, but am I the only one who finds unit tests and documentation sort of, soothing?" (benrutter)
- "Since when has writing tests not been a joyful experience?" (9rx)
4. AI与测试的结合
- 主要论据:AI工具可以帮助编写测试,提升效率。
- "Recently, I have given up on writing unit tests, instead prompting an LLM to write them for me. I just sit back and keep prompting it until it gets it right." (mlmonkey)
- "I like writing tests when I am not the one writing tests. So much better when Claude Code is doing the heavy lifting." (Mooshux)
5. 测试环境的挑战
- 主要论据:测试环境与真实环境的差异可能导致测试价值降低。
- "In my experience the lack of joy or difficulty with tests is almost always that the test environment is usually different enough from the real environment." (3vidence)
- "This doesn’t apply to very simple functions but tests on simple functions are the least interesting/ valuable." (3vidence)
6. 其他相关工具与实现
- 主要论据:介绍了其他语言或生态系统中类似的测试工具。
- "If you’re a Swift programmer, the swift-snapshot-testing package is a great implementation of these ideas." (mayoff)
- "mdx[1] is another variation on this, also in the Ocaml ecosystem." (idont_know)