AI Hints
Home›Spring Boot Tutorial›Why Test, JUnit Basics and Testing a Service
Spring Boot · Lesson 102 of 120

Testing a Service

Plain Java, no Spring.

⏱ 2 min read▶ Video at 2:15:22🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

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.

  • Services are plain classes
  • Create them with new
  • No Spring needed

CheckoutService.java

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
@Service
public 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;
    }
}

Testing it with new

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.

test/CheckoutServiceTest.javajava
class CheckoutServiceTest {

    CheckoutService checkout = new CheckoutService(new PriceCalculator());

    @Test
    void addsDeliveryUnder25() {
        assertEquals(12.98, checkout.total(List.of(9.99), 0), 0.001);
    }

    @Test
    void freeDeliveryFrom25() {
        assertEquals(27.0, checkout.total(List.of(10.0, 20.0), 10), 0.001);
    }
}
Output
[INFO] Running CheckoutServiceTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Also uses PriceCalculator.java
@Service
public 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
@Service
public 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;
    }
}
Also uses _mvn
test

Why this is fast

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.

keyvalue
No Springno context to start
No databasenothing to set up
Speedmilliseconds
Thanks toconstructor injection

Summary

Services with constructor injection are easy to test with new, without Spring. Next, Mockito, for dependencies we don't want to use for real.

Key takeaways
  • new CheckoutService(...)
  • No Spring
  • Very fast
Next up: Mockito — fake dependencies