flowchart LR
subgraph ”真实环境”
A[”被测类”] --> B[”真实依赖<br/><small>ExpressService</small>”]
end
subgraph ”测试环境”
C[”被测类”] --> D[”测试替身<br/><small>ExpressServiceDouble</small>”]
end
/** * ExpressService 的测试替身。 * 通过继承原始类,重写需要隔离的方法,返回预设值。 */public class ExpressServiceDouble extends ExpressService { private final int fullFee; private final int halfFee; public ExpressServiceDouble(int fullFee, int halfFee) { this.fullFee = fullFee; this.halfFee = halfFee; } @Override public int fullFee() { return this.fullFee; // 返回预设值,而非真实查询 } @Override public int halfFee() { return this.halfFee; // 返回预设值,而非真实查询 }}
步骤 3:利用多态替换依赖
Java 的多态允许子类对象赋值给父类类型。在测试中,我们用替身替换真实对象:
class PriceCalculatorUnitTest { @Test void should_add_full_express_fee_when_total_less_than_100() { // 创建替身,预设快递费为 20 元 ExpressServiceDouble doubleService = new ExpressServiceDouble(20, 10); // 将替身注入被测对象(利用多态) PriceCalculator calculator = new PriceCalculator(); calculator.setExpressService(doubleService); // 执行测试 int result = calculator.calculate(85); // 验证结果 assertThat(result).isEqualTo(105); // 85 + 20 }}
替身的工作原理
sequenceDiagram
participant Test as 测试方法
participant Double as ExpressServiceDouble
participant Real as ExpressService(真实)
Note over Test,Real: 测试中使用替身
Test->>+Double: fullFee()
Double->>-Test: 返回 20(预设值)
Note over Double,Real: 不会调用真实服务