Files
skillhub-009-tdd/interface-design.md
2026-07-13 21:35:35 +08:00

649 B

面向可测试性的接口设计

好的接口能让测试变得自然:

  1. 接收依赖,而非创建依赖

    // 可测试
    function processOrder(order, paymentGateway) {}
    
    // 难测试
    function processOrder(order) {
      const gateway = new StripeGateway();
    }
    
  2. 返回结果,而非产生副作用

    // 可测试
    function calculateDiscount(cart): Discount {}
    
    // 难测试
    function applyDiscount(cart): void {
      cart.total -= discount;
    }
    
  3. 缩小接触面

    • 方法越少 = 需要编写的测试越少
    • 参数越少 = 测试设置越简单