JUnit 5 and Mockito Unit Testing
Harry
· 21 Sep 2026
· 1 views
Log in to track your progress and mark lessons complete.
Sponsored
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 // cleanupAssertions 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 testMockito: 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.
- Mock dependencies, test logic.
- when() stubs, verify() proves interaction.
- Unit suites must run in seconds on every commit.