Stop 11 · Git, Build Tools & TestingTopics · 6/10

Unit Testing with JUnit 5

Part of the Java Roadmap

In short

Every time you change code, you risk breaking something that used to work. Unit tests check it for you in seconds, and companies expect every Java developer to write them.

JUnit 5 is the standard Java testing framework. You write test methods with @Test and check results with assertions like assertEquals and assertThrows.

The jaadu in an inspector's cap holds a clipboard and ticks a box as a small car parks perfectly between two cones.

Think of it like this

The driving test checklist

An RTO inspector doesn't just feel that you drive well. They run fixed checks: start on a slope, reverse park, stop at the line. Each check passes or fails. A JUnit test is one of those checks for a method: set things up, do one action, assert the result.

The big ideas

What you need to know

@Test methods

A test is a void method annotated with @Test. It needn't be public in JUnit 5, and its name should describe the behaviour.

Fresh setup

@BeforeEach runs before every test, so tests don't share state and can run in any order.

Assertions

assertEquals(expected, actual), assertTrue, assertNull, assertAll to check several things, and assertThrows for errors.

Parameterised tests

@ParameterizedTest with @ValueSource or @CsvSource runs the same test for many inputs.

How it works

Arrange, Act, Assert

  1. 1

    Arrange

    Create the objects you need, often in a @BeforeEach method so every test starts fresh.

  2. 2

    Act

    Call the one method you are testing, like account.deposit(500).

  3. 3

    Assert

    Check the outcome with assertEquals, assertTrue or assertThrows.

  4. 4

    Run

    Run from IntelliJ's green arrow, mvn test or ./gradlew test. Green means pass, red shows what was expected and what came back.

See it in code

Walk through the code

java
1import org.junit.jupiter.api.BeforeEach;2import org.junit.jupiter.api.DisplayName;3import org.junit.jupiter.api.Test;4import org.junit.jupiter.params.ParameterizedTest;5import org.junit.jupiter.params.provider.ValueSource;6 7import static org.junit.jupiter.api.Assertions.*;8 9class BankAccountTest {10    private BankAccount account;11 12    @BeforeEach13    void setUp() {14        account = new BankAccount("ACC-101", 1000);15    }16 17    @Test18    @DisplayName("deposit adds money to the balance")19    void depositIncreasesBalance() {20        account.deposit(500);21        assertEquals(1500, account.getBalance());22    }23 24    @Test25    void withdrawMoreThanBalanceThrows() {26        IllegalStateException ex = assertThrows(IllegalStateException.class,27                () -> account.withdraw(5000));28        assertEquals("Insufficient balance", ex.getMessage());29    }30 31    @ParameterizedTest32    @ValueSource(ints = {0, -100})33    void depositRejectsNonPositiveAmounts(int amount) {34        assertThrows(IllegalArgumentException.class, () -> account.deposit(amount));35    }36}

1/4Arrange: every test gets a brand-new account with ₹1,000.

Tests for a BankAccount class with a long balance. The file lives in src/test/java, mirroring the class's package.

Save yourself the pain

Common mistakes

Oops

assertEquals(account.getBalance(), 1500)

Do this instead

Put the expected value first: assertEquals(1500, account.getBalance()). Otherwise failure messages read backwards.

Oops

Using try/catch with fail() to test exceptions.

Do this instead

assertThrows is shorter and clearer, and it hands you the exception to inspect.

Oops

One giant test that checks deposit, withdraw and transfer together.

Do this instead

Test one behaviour per method. When it fails, the name tells you exactly what broke.

Your mission

Test a GST calculator

~40 min

Quick check

Why does JUnit 5 run @BeforeEach before every test instead of once?

Go deeper

  1. 1Write tests for the methods in your bank or contact book project.
  2. 2Use @BeforeEach for shared setup and @ParameterizedTest for many inputs.
  3. 3Run tests from IntelliJ and from Maven or Gradle.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge