Mockito
interface CourseChat {
void send(String message);
}
class Course {
private final CourseChat courseChat;
public Course(CourseChat courseChat) {
this.courseChat = courseChat;
}
public void start() {
courseChat.send("Welcome to this marvellous course!!");
}
}
class CourseTest {
@Test
public void sends_a_welcome_message_in_the_chat() {
CourseChat courseChat = mock(CourseChat.class);
Course course = new Course(courseChat);
course.start();
verify(courseChat).send("Welcome to this marvellous course!!"); // <- spying
}
}
interface StudentsRepository {
List<Student> getAll();
}
class CourseReport {
private final StudentsRepository studentsRepository;
public CourseReport(StudentsRepository studentsRepository) {
this.studentsRepository = studentsRepository;
}
public double calculateAgeAverage() {
List<Student> students = studentsRepository.getAll();
int studentsNumber = students.size();
if (studentsNumber == 0) {
return 0.0;
}
int agesSum = students.stream().mapToInt(Student::age).sum();
return (double) agesSum / studentsNumber;
}
}
class CourseReportTest {
@Test
public void calculates_age_average() {
StudentsRepository repository = mock(StudentsRepository.class);
List<Student> students = Arrays.asList(new Student(20), new Student(25), new Student(30));
when(repository.getAll()).thenReturn(students); // <- stubbing
CourseReport courseReport = new CourseReport(repository);
double ageAverage = courseReport.calculateAgeAverage();
assertThat(ageAverage, is(25.0));
}
}