flowchart TD
subgraph ”测试替身(对象级)”
A[”ExpressServiceDouble<br/><small>替身对象</small>”]
end
subgraph ”桩方法(行为级)”
B[”fullFee() → 返回 20”]
C[”halfFee() → 返回 10”]
end
A --> B
A --> C
public class PriceCalculator { private ExpressService expressService; public void setExpressService(ExpressService expressService) { this.expressService = expressService; } public int calculate(int total) { if (total < 30) { // 足额快递费 + 手续费 return total + expressService.fullFee() + 5; } if (total < 100) { // 足额快递费 return total + expressService.fullFee(); } if (total > 100 && total < 150) { // 一半快递费 return total + expressService.halfFee(); } return total; }}
替身类(含桩方法)
public class ExpressServiceDouble extends ExpressService { private int fullFee; private 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; }}
单元测试(使用替身+桩)
class PriceCalculatorUnitTest { @Test void should_add_full_express_fee_when_total_less_than_100() { // Arrange - 创建替身并打桩 ExpressServiceDouble stub = new ExpressServiceDouble(20, 10); PriceCalculator calculator = new PriceCalculator(); calculator.setExpressService(stub); // 注入替身 // Act - 执行被测方法 int result = calculator.calculate(85); // Assert - 验证结果 assertThat(result).isEqualTo(105); // 85 + 20(桩返回的值) } @Test void should_add_half_express_fee_when_total_between_100_and_150() { // Arrange ExpressServiceDouble stub = new ExpressServiceDouble(20, 10); PriceCalculator calculator = new PriceCalculator(); calculator.setExpressService(stub); // Act int result = calculator.calculate(110); // Assert assertThat(result).isEqualTo(120); // 110 + 10(桩返回的值) }}