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

JUnit Basics

Tests that check themselves.

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

JUnit is the standard testing library for Java. Spring Boot includes it, ready to use. Let's learn its most useful pieces.

  • The standard library
  • Included in Spring Boot
  • The useful pieces

Assertions

Assert equals compares expected, and actual. Assert true, and assert false, check a condition. Assert not null checks for a value. And assert throws checks that code throws a certain exception.

AssertionChecks
assertEquals(expected, actual)equal values
assertTrue / assertFalsea condition
assertNotNullnot null
assertThrows(Type.class, () -> ...)an exception

More assertions

The first test checks the rounding, and that the result is cheaper. The second uses assert throws, with a lambda, that should fail. It returns the exception, so we can check its message too. Run it. Both tests pass.

test/PriceCalculatorTest.javajava
class PriceCalculatorTest {

    PriceCalculator calc = new PriceCalculator();

    @Test
    void roundsToPennies() {
        double result = calc.discounted(9.99, 15);
        assertEquals(8.49, result);
        assertTrue(result < 9.99);
    }

    @Test
    void rejectsBadPercent() {
        var ex = assertThrows(IllegalArgumentException.class,
                              () -> calc.discounted(10, 150));
        assertEquals("Bad percent: 150", ex.getMessage());
    }
}
Output
[INFO] Running PriceCalculatorTest
[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 _mvn
test

A failing test

Here, we expect four, but half of ten is five. Run it. Maven shows the failing test, and its line number. It says, expected four, but was five. And the build fails. That's exactly what we want, when something is wrong.

test/PriceCalculatorTest.javajava
class PriceCalculatorTest {

    PriceCalculator calc = new PriceCalculator();

    @Test
    void halfPrice() {
        assertEquals(4.0, calc.discounted(10.0, 50));
    }
}
Output
[INFO] Running PriceCalculatorTest
[ERROR] Failures:
[ERROR]   PriceCalculatorTest.halfPrice:7 expected: <4.0> but was: <5.0>
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[ERROR] BUILD FAILURE
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 _mvn
test

Good test habits

Give tests clear names, that say what they check. Test one behaviour per test. Arrange the data, act, then assert. And make sure each test can fail. A test that can never fail is useless.

keyvalue
Namessay what is checked
One thingper test
Shapearrange, act, assert
Can it fail?it must be able to

Summary

JUnit tests use at Test, and assertions like assert equals, and assert throws. A failing test shows expected, and actual values. Next, testing a service.

Key takeaways
  • assertEquals
  • assertThrows
  • Failures show the line
Next up: Testing a Service — plain Java, no Spring