Here's a secret of constructor injection. A service is just a Java class. In a unit test, we can create it ourselves, with new, without starting Spring at all.
Checkout service needs a price calculator, through its constructor. Total adds the prices, and applies the discount. Orders under twenty five pay two ninety nine for delivery.
CheckoutService.javajava
@Servicepublic class CheckoutService { private final PriceCalculator calc; public CheckoutService(PriceCalculator calc) { this.calc = calc; } public double total(List<Double> prices, int percent) { double sum = prices.stream().mapToDouble(Double::doubleValue).sum(); double total = calc.discounted(sum, percent); return total >= 25 ? total : total + 2.99; }}
We build the service ourselves, passing a real calculator. The first test checks the delivery charge. The second checks free delivery, from twenty five. The last argument, nought point nought nought one, allows for tiny rounding differences in doubles. Run it. Both pass, in a fraction of a second.
@Servicepublic class PriceCalculator { public double discounted(double price, int percent) { if (percent < 0 || percent > 100) { throw new IllegalArgumentException("Bad percent: " + percent); } return Math.round(price * (100 - percent)) / 100.0; }}
Also uses CheckoutService.java
@Servicepublic class CheckoutService { private final PriceCalculator calc; public CheckoutService(PriceCalculator calc) { this.calc = calc; } public double total(List<Double> prices, int percent) { double sum = prices.stream().mapToDouble(Double::doubleValue).sum(); double total = calc.discounted(sum, percent); return total >= 25 ? total : total + 2.99; }}
No Spring context starts, and no database, or web server. The test only runs our Java code. That's why unit tests take milliseconds. And it works because of constructor injection.