A unit test is a small program that runs part of your code and checks the answer. In Java that means JUnit 5, usually with Mockito for test doubles and AssertJ for readable assertions. This guide covers writing tests, testing code that depends on a database or a clock, and deciding what deserves a test at all.
Setting up#
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.25.3</version>
<scope>test</scope>
</dependency>
Spring Boot’s spring-boot-starter-test bundles JUnit, AssertJ, Mockito and more, so a Spring project needs only that one.
A first test#
public class Discount {
public BigDecimal apply(BigDecimal price, int percent) {
if (percent < 0 || percent > 100) {
throw new IllegalArgumentException("percent must be 0-100");
}
return price.multiply(BigDecimal.valueOf(100 - percent))
.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
}
}
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
class DiscountTest {
private final Discount discount = new Discount();
@Test
void reducesPriceByPercentage() {
// given
BigDecimal price = new BigDecimal("100.00");
// when
BigDecimal result = discount.apply(price, 20);
// then
assertThat(result).isEqualByComparingTo("80.00");
}
@Test
void rejectsNegativePercentage() {
assertThatThrownBy(() -> discount.apply(BigDecimal.TEN, -5))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("0-100");
}
}
The given-when-then comments are not decoration. Keeping setup, action and assertion visually separate makes a failing test readable a year later.
Parameterised tests#
@ParameterizedTest
@CsvSource({
"100.00, 0, 100.00",
"100.00, 50, 50.00",
"100.00, 100, 0.00",
"19.99, 10, 17.99",
})
void calculatesCorrectly(BigDecimal price, int percent, BigDecimal expected) {
assertThat(discount.apply(price, percent)).isEqualByComparingTo(expected);
}
@ParameterizedTest
@ValueSource(ints = {-1, 101, 500})
void rejectsOutOfRange(int percent) {
assertThatThrownBy(() -> discount.apply(BigDecimal.TEN, percent))
.isInstanceOf(IllegalArgumentException.class);
}
Each row appears as a separate result, so you see exactly which combination failed rather than just that something did.
Lifecycle#
class OrderServiceTest {
private OrderService service;
@BeforeEach
void setUp() {
service = new OrderService(new InMemoryRepository());
}
@AfterEach
void tearDown() { }
@BeforeAll
static void once() { } // must be static
}
JUnit creates a new instance of the test class for each test method, so fields do not leak between tests. That isolation is deliberate and worth relying on.
Making code testable#
This method cannot be tested reliably:
public boolean isExpired(Order order) {
return order.getCreatedAt().plusDays(30).isBefore(LocalDate.now());
}
Its result depends on when the test runs. Inject the dependency instead:
public class OrderService {
private final Clock clock;
public OrderService(Clock clock) {
this.clock = clock;
}
public boolean isExpired(Order order) {
return order.getCreatedAt().plusDays(30).isBefore(LocalDate.now(clock));
}
}
@Test
void expiresAfterThirtyDays() {
Clock fixed = Clock.fixed(Instant.parse("2026-02-15T00:00:00Z"), ZoneOffset.UTC);
var service = new OrderService(fixed);
var order = new Order(LocalDate.of(2026, 1, 1));
assertThat(service.isExpired(order)).isTrue();
}
The same applies to databases, HTTP clients, file systems and random numbers. Code that is hard to test usually has hidden dependencies, so the difficulty is telling you something about the design.
Mockito#
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock private OrderRepository repository;
@Mock private EmailSender email;
@InjectMocks private OrderService service;
@Test
void savesAndNotifies() {
var order = new Order("ana@example.com");
when(repository.save(any(Order.class))).thenReturn(42L);
service.place(order);
verify(repository).save(order);
verify(email).send(eq("ana@example.com"), anyString());
verifyNoMoreInteractions(email);
}
@Test
void propagatesRepositoryFailure() {
when(repository.save(any())).thenThrow(new DataAccessException("down") { });
assertThatThrownBy(() -> service.place(new Order("a@b.com")))
.isInstanceOf(DataAccessException.class);
}
}
Spring Boot tests#
// Slow - starts the entire application context
@SpringBootTest
class FullTest { }
// Fast - only the web layer, with the service mocked
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired private MockMvc mvc;
@MockBean private ProductService service;
@Test
void returnsProduct() throws Exception {
when(service.find(1L)).thenReturn(Optional.of(new Product("Pen")));
mvc.perform(get("/api/products/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Pen"));
}
@Test
void returnsNotFoundWhenMissing() throws Exception {
when(service.find(99L)).thenReturn(Optional.empty());
mvc.perform(get("/api/products/99"))
.andExpect(status().isNotFound());
}
}
// Only the persistence layer, against an in-memory database
@DataJpaTest
class ProductRepositoryTest {
@Autowired private ProductRepository repository;
@Test
void findsByPrice() {
repository.save(new Product("Pen", new BigDecimal("1.50")));
assertThat(repository.findByPriceLessThan(new BigDecimal("2.00")))
.hasSize(1);
}
}
Slice tests start a fraction of the context and run in a fraction of the time. Reserve full @SpringBootTest for a handful of end-to-end checks.
Testing against a real database#
@Testcontainers
@SpringBootTest
class OrderIntegrationTest {
@Container
static PostgreSQLContainer<?> db =
new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", db::getJdbcUrl);
registry.add("spring.datasource.username", db::getUsername);
registry.add("spring.datasource.password", db::getPassword);
}
}
Testcontainers starts a real database in Docker for the test run. It is slower than H2 but catches the dialect differences that make an H2-passing test fail in production.
What to test#
Worth testing: business rules, calculations, validation, boundaries and edge cases, anything you have already had to fix once, and every bug you fix — write the failing test first, then make it pass.
Not worth testing: getters and setters, framework behaviour, third-party libraries, and code that only wires other code together.
mvn test
mvn test -Dtest=DiscountTest
gradle test --tests "*Discount*"
Questions people ask#
JUnit 4 or 5?
JUnit 5 for new work. The annotations differ — @BeforeEach rather than @Before, and no @RunWith — which is worth knowing when reading older tutorials.
Should I use AssertJ or the built-in assertions?
AssertJ reads better and gives more informative failure messages, particularly on collections. The built-in ones are perfectly serviceable for simple checks.
How do I test private methods?
Through the public method that calls them. If a private method is complex enough to need its own tests, that is a hint it wants to be its own class.
What is a flaky test?
One that passes and fails without the code changing — usually a dependency on timing, ordering, the clock or a shared resource. Fix it or delete it; a test nobody trusts is worse than none.
Where to go next#
- Java and the Spring framework — the injection that makes this possible.
- Java web development — what the controller tests exercise.
- Java performance optimization — tests as a safety net for it.