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