JUnit 5 and Mockito Unit Testing

Harry · 21 Sep 2026 · 1 views
Log in to track your progress and mark lessons complete.

Introduction to JUnit 5

JUnit 5 (Jupiter) is the standard for Java unit tests: @Test, lifecycle hooks and expressive assertions, running under Maven Surefire.

Annotations and Lifecycle

@BeforeEach // fresh fixture per test
@Test
@ParameterizedTest @ValueSource(strings = {"", " ", "ab"})
@AfterEach // cleanup

Assertions and Exception Testing

assertEquals(4, calc.add(2, 2));
assertThrows(IllegalArgumentException.class,
  () -> calc.divide(1, 0));

JUnit with Maven and Spring Boot

mvn test // runs *Test classes
@SpringBootTest // full context
@WebMvcTest(BookController.class) // slice test

Mockito: Mocking Dependencies

Unit tests must not hit databases. Mockito fakes collaborators:

@ExtendWith(MockitoExtension.class)
@Mock BookRepository repo;
@InjectMocks BookService service;

when(repo.findBySlug("x")).thenReturn(Optional.of(book));
assertEquals(1, service.count());
verify(repo).findBySlug("x");

Service and Repository Testing

  • Service layer - mock the repository, verify business logic.
  • Repository layer - use @DataJpaTest with an in-memory DB for real queries.

Unit Testing Best Practices

  • Fast, isolated, repeatable; one behaviour per test.
  • Name tests as sentences: rejectsExpiredCoupon().
  • Cover branches, not just lines.

Mockito mocking - unit test uses mock repository instead of real database

Key Points

  • Mock dependencies, test logic.
  • when() stubs, verify() proves interaction.
  • Unit suites must run in seconds on every commit.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in