Lesson 1 of 5 · 11 min · Unit testing in Java
Writing unit tests with JUnit and AssertJ
What you will learn
- What a unit test is and what makes a good one
- Write tests with JUnit Jupiter:
@Test, assertions and the test lifecycle - Use AssertJ for readable assertions
- Structure tests with arrange, act, assert and good names
- Run the tests with Maven and read the result
In simple words
A unit test is a tiny program that checks that one small piece of your code does what you expect, such as "a discount of 10 percent on 1,000 gives 900". You write it once and run it in a second, every time you change the code. When a test fails, it tells you straight away that something you changed broke something that worked, long before a customer finds it.
Words to know
- Unit test: an automated check of one small piece of code in isolation.
- Assertion: a statement in a test that must be true, or the test fails.
- Test fixture: the objects and data a test needs to run.
- Regression: something that used to work and breaks after a change.
Why unit tests
- They catch bugs early, when they are cheap to fix.
- They let you change code with confidence (refactor) because failures show up immediately.
- They are living documentation: a test shows how a class is meant to be used.
- They push you toward small, testable design (the SOLID lesson: classes with injected dependencies are easy to test).
In the "test pyramid", most tests should be fast unit tests, fewer integration tests (several components together, a real database), and very few slow end-to-end tests. A good unit test is fast (milliseconds), isolated (no network, database or clock), repeatable (same result every time) and self-checking (pass or fail, no manual reading).
JUnit Jupiter
JUnit is the standard Java test framework. JUnit 6 (current at the time of writing; it requires Java 17 or newer) consists of the JUnit Platform (runs tests), JUnit Jupiter (the programming model you write tests with) and the Vintage engine for old JUnit 4 tests (deprecated). Spring Boot's spring-boot-starter-test brings JUnit Jupiter, AssertJ and Mockito. Without Spring Boot, add:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>6.1.3</version> <!-- check the current version in the user guide -->
<scope>test</scope>
</dependency>
Your first test
Class under test:
public class PriceCalculator {
public double discounted(double price, int percent) {
if (price < 0) throw new IllegalArgumentException("price must be >= 0");
if (percent < 0 || percent > 100) throw new IllegalArgumentException("percent must be 0..100");
return price - price * percent / 100.0;
}
}
Test, in src/test/java/.../PriceCalculatorTest.java (the same package, a Test suffix):
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PriceCalculatorTest {
private final PriceCalculator calculator = new PriceCalculator();
@Test
void tenPercentOffThousandIsNineHundred() {
double result = calculator.discounted(1000, 10);
assertEquals(900.0, result, 0.001); // the third argument is the allowed delta for doubles
}
@Test
void zeroPercentLeavesPriceUnchanged() {
assertEquals(500.0, calculator.discounted(500, 0), 0.001);
}
@Test
void negativePriceIsRejected() {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
() -> calculator.discounted(-1, 10));
assertEquals("price must be >= 0", e.getMessage());
}
}
Test classes and methods can be package-private in Jupiter (no public needed). Each test method runs on a new instance of the class, so tests do not share state accidentally.
Arrange, act, assert
Give every test the same shape:
@Test
void totalOfTwoItemsIsTheirSum() {
// arrange: build what you need
Cart cart = new Cart();
cart.add(new Item("pen", 40));
cart.add(new Item("book", 120));
// act: do the one thing under test
double total = cart.total();
// assert: check the outcome
assertEquals(160.0, total, 0.001);
}
Test one behaviour per test; a failure should tell you exactly what broke. Avoid logic (loops, if) inside tests, and do not test the framework or simple getters. Test behaviour (what the code does for the caller), not implementation (how it does it), so that refactoring does not break tests.
Naming
A test name should read like a sentence describing the behaviour: negativePriceIsRejected, shouldReturnEmptyListWhenNoOrdersExist, givenExpiredCoupon_whenApply_thenThrows. Choose one convention for the team. Add a display name for reports:
@Test
@DisplayName("A 100% discount makes the price zero")
void fullDiscount() { ... }
Lifecycle
class OrderServiceTest {
@BeforeAll static void startOnce() { } // once before all tests (must be static)
@BeforeEach void setUp() { } // before every test: build fresh objects
@AfterEach void tearDown() { } // after every test: clean up
@AfterAll static void stopOnce() { }
}
Prefer creating objects in @BeforeEach (or as fields) so tests stay independent. Tests must not depend on each other or on order; JUnit does not guarantee an order.
Other useful annotations: @Disabled("reason") to skip a test (and fix it soon), @Tag("slow") to group tests, @Timeout(2) to fail a test that hangs, @TempDir Path dir for a temporary folder, @Nested for grouping related tests in inner classes (the next lesson).
Assertions
JUnit's Assertions class: assertEquals(expected, actual) (note the order: expected first), assertNotEquals, assertTrue, assertFalse, assertNull, assertNotNull, assertSame, assertThrows, assertDoesNotThrow, assertTimeout, assertArrayEquals, and assertAll which runs several checks and reports all failures:
assertAll("customer",
() -> assertEquals("Asha", customer.name()),
() -> assertEquals("asha@example.com", customer.email()),
() -> assertTrue(customer.isActive()));
Add a message as the last argument (assertEquals(900, result, "price after 10% off")) when the failure would otherwise be unclear. For floating-point numbers, always give a delta; for money prefer BigDecimal and assertEquals on compareTo or AssertJ's isEqualByComparingTo.
AssertJ: fluent, readable assertions
AssertJ (included with Spring Boot's test starter) reads like English, gives precise failure messages and has helpers for collections, strings, dates and exceptions:
import static org.assertj.core.api.Assertions.*;
assertThat(result).isEqualTo(900.0);
assertThat(name).isNotBlank().startsWith("A").hasSize(4);
assertThat(orders).hasSize(3).extracting(Order::status).containsExactly("PAID", "PAID", "PENDING");
assertThat(order.amount()).isEqualByComparingTo("1200.00"); // BigDecimal ignoring scale
assertThat(map).containsEntry("pen", 100).doesNotContainKey("bag");
assertThat(list).containsExactlyInAnyOrder("a", "b", "c");
assertThatThrownBy(() -> calculator.discounted(-1, 10))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("price");
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> service.run());
The chained style gives messages such as Expecting actual: ["PAID", "PENDING"] to contain exactly: ["PAID", "PAID"], much clearer than expected: <true> but was: <false>. Both JUnit and AssertJ assertions are fine; choose AssertJ for collections and richer checks.
Running tests
Maven runs tests during mvn test or mvn verify through the Surefire plugin (it finds *Test, Test*, *Tests and *TestCase classes):
./mvnw test # all unit tests
./mvnw test -Dtest=PriceCalculatorTest # one class
./mvnw test -Dtest=PriceCalculatorTest#negativePriceIsRejected # one method
Output ends with Tests run: 3, Failures: 0, Errors: 0, Skipped: 0. A failure is an assertion that did not hold; an error is an unexpected exception. IDEs (IntelliJ IDEA, VS Code, Eclipse) run tests with a click and show a green or red bar; use them for fast feedback. Run the full suite in CI (GitHub Actions, Jenkins) on every push, so a broken test blocks the merge.
Test-driven development in brief
TDD is a rhythm: red (write a failing test for the next small behaviour), green (write the least code to pass), refactor (tidy with the tests protecting you). Even if you do not use it all the time, writing the test first for a bug is excellent practice: reproduce the bug in a failing test, fix it, and keep the test forever as a regression guard.
Common mistakes
- Tests that depend on order or share mutable state.
- Testing implementation details, so every refactor breaks tests.
- Many assertions about different behaviours in one test.
- Calling real services, databases or the system clock in a unit test.
- Swapping
expectedandactual, producing confusing messages. - Commenting out or
@Disabled-ing failing tests and forgetting them. - Asserting nothing, a test that cannot fail.
Try it yourself
- Write
PriceCalculatorand the three tests above; run them with Maven. - Break the code on purpose (change
/ 100.0to/ 10.0) and read the failure message. - Rewrite the assertions on a list of orders using AssertJ's
extractingandcontainsExactly. - Reproduce a bug you remember with a failing test before fixing it.
- Add
@BeforeEachto build a freshCartand write four tests for it.
Check yourself
What makes a good unit test?
It is fast, isolated from slow external systems, repeatable, self-checking, tests one behaviour and has a name that describes it.
What does arrange, act, assert mean?
Set up the objects and data, perform the single action under test, then check the outcome.
Why is a new test class instance created for each test method in JUnit Jupiter?
So tests cannot share state accidentally and remain independent of each other and of their order.
Why give a delta to assertEquals for doubles?
Floating-point arithmetic is approximate, so comparing with a small tolerance avoids false failures.
Interview questions
What is the difference between a unit test and an integration test?
A unit test checks one small piece in isolation, with dependencies replaced by fakes, and runs in milliseconds. An integration test checks several parts working together, such as a service with a real database, and is slower.
What are @BeforeEach and @BeforeAll?
@BeforeEach runs before every test method (fresh setup); @BeforeAll runs once before all tests in the class and must be static (unless the lifecycle is per class).
How do you test that a method throws an exception?
assertThrows(Type.class, () -> call()) in JUnit, or assertThatThrownBy(() -> call()).isInstanceOf(Type.class).hasMessageContaining(...) in AssertJ.
Summary
- Unit tests are fast, isolated, repeatable checks of one behaviour, the base of the test pyramid.
- JUnit Jupiter gives
@Test, the lifecycle annotations,assertEquals,assertThrowsandassertAll; AssertJ makes assertions fluent. - Use arrange-act-assert, descriptive names and fresh objects per test.
- Run tests with Maven and in CI; reproduce bugs with a failing test first.
Going deeper
- JUnit User Guide: the official documentation for JUnit 6.
- AssertJ documentation: the fluent assertion library, with guides for each type.
- Maven Surefire plugin: how Maven runs tests.
- Spring Boot: Testing: the test starters and modules.
See how much of this you can explain
A free mock interview asks you new questions on Unit testing in Java with JUnit and Mockito for Java Full Stack Developer and scores every answer, with what to fix.