Image Credit: Mockito

Install in Gradle

dependencies {
    // Use JUnit Jupiter API for testing.
    testImplementation ..., 'org.mockito:mockito-inline:3.8.0',
    'org.mockito:mockito-junit-jupiter:3.8.0'
... }

Add Mockito to Test Class

import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class) public class UnitTestClass { // tests here }

Use Strict Stubs

import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness;
@MockitoSettings(strictness = Strictness.STRICT_STUBS) public class UnitTestClass { // tests here }

Creating Fake Objects

@MockitoSettings(strictness = Strictness.STRICT_STUBS)
public class UnitTestClass {
@Mock Person mockPerson; @Mock Teacher mockTeacher;
public void testClassroomHasTeacher() { Classroom classroom = new Classroom() assertTrue(classroom.hasTeacher() == false);
classroom.addTeacher(mockTeacher); assertTrue(classroom.hasTeacher() == true); } }

Adding a Stub

@MockitoSettings(strictness = Strictness.STRICT_STUBS)
public class ClassroomTest {
@Mock Person mockPerson; @Mock Teacher mockTeacher;
@Test public void testClassroomGetTeacherName() { // create a method stub for `getName` when(mockTeacher.getName()).thenReturn("Teacher Person");
Classroom classroom = new Classroom(); classroom.addTeacher(mockTeacher);
// assert that the classroom returns the teacher's name assertTrue(classroom.getTeacherName().equals("Teacher Person")); } }

Static Classes

@Test
public void testTeacherFailsMinimumAgeRequirement() {
    // Create mock static class
    try (MockedStatic mockTeacherRules = Mockito.mockStatic(TeacherRules.class)) {
// Create method stub for static class mockTeacherRules.when(() -> TeacherRules.getMinAge()).thenReturn(16);
// Create method stub for fake Teacher when(mockTeacher.getAge()).thenReturn(15);
// Test functionality Classroom classroom = new Classroom(); assertThrows(IllegalArgumentException.class, () -> classroom.addTeacher(mockTeacher)); } }