测试隔离与组合的本质区别
推荐指数 48.0 NO. 016 · 2026.08.19
发布2026/08/18Score55Comments48
为什么值得看
Kent Beck 澄清测试的两个易混淆属性:隔离(isolation)指单个测试自包含、无副作用;组合(composition)指多个测试共享 fixture 仍能正确协同运行。后者是集成测试和性能优化的关键,但常被忽视。
编辑判断
很多团队把「每个测试独立建 fixture」当作铁律,导致测试套件跑半小时以上。Beck 点出的组合性其实是给性能优化开了一道门:共享 fixture 不必然破坏正确性,关键是测试之间保持引用透明。
实际工程中,Spring 的 @DirtiesContext 和 pytest 的 scope 参数都是在这两个属性间做权衡。如果你正在头疼 CI 流水线太慢,值得重新审视哪些测试真的需要完全隔离,哪些可以安全组合。
社区反馈
意见分歧 43 条评论
核心争论:测试组合是效率优化还是隐式耦合陷阱
相关内容
I'm done listening to smart people proposing fixes for my dumb code. Either I'm not smart or disciplined enough to make it work, or my colleagues are not. Mostly both.
What he wrote is basically "don't repeat in test X what you already tested in test X-1". It's not as much composition as compounding, and can work quite well. Let's say something takes 20 steps, and you want to test all 20. Instead of this: test 1: do step 1, assert step 1 test 2:
I wonder if it would work do design something that was able to say test 1: do step 1, assert step 1 test 2: requires: test 1 do step 2, assert step 2 test 3: requires: test 2 do step 3, assert step 3 test 4: requires: test 2 do ste