Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active September 7, 2024 13:42
Show Gist options
  • Save trikitrok/1573df976f090f46f3b188646de8b3be to your computer and use it in GitHub Desktop.
Save trikitrok/1573df976f090f46f3b188646de8b3be to your computer and use it in GitHub Desktop.
Use of test doubles with Mockito

Tools

Mockito

Example of spy

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
    }
}

Example of stub

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));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment