649 B
649 B
面向可测试性的接口设计
好的接口能让测试变得自然:
-
接收依赖,而非创建依赖
// 可测试 function processOrder(order, paymentGateway) {} // 难测试 function processOrder(order) { const gateway = new StripeGateway(); } -
返回结果,而非产生副作用
// 可测试 function calculateDiscount(cart): Discount {} // 难测试 function applyDiscount(cart): void { cart.total -= discount; } -
缩小接触面
- 方法越少 = 需要编写的测试越少
- 参数越少 = 测试设置越简单