Mocking external dependencies for unit tests
Unit tests are meant to execute without any external dependencies. We can certainly write methods at a granular level, such that the core business logic methods are totally separate from methods that have external dependencies. However, sometimes this is not practical, and we may have to write unit tests for code that are closely dependent on methods that access external systems.
For example, let's assume that we have to add a method in our Course
bean to add students to the course. We will also mandate that the course has an upper limit on the number of students that it can enroll, and once this limit is reached, no more students can be enrolled. Let's add the following method to our Course
bean:
public void addStudent (Student student) throws EnrolmentFullException, SQLException { //get current enrolement first int currentEnrolment = courseDAO.getNumStudentsInCourse(id); if (currentEnrolment >= getMaxStudents()) throw new...