Image Credit: Mockito
dependencies {
// Use JUnit Jupiter API for testing.
testImplementation ..., 'org.mockito:mockito-inline:3.8.0',
'org.mockito:mockito-junit-jupiter:3.8.0'
...
}
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
}
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
}
@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);
}
}
@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"));
}
}
@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));
}
}