0

I am trying to mock the new instance of CourseLoader in the method I'm testing so when I call loadAll() it returns my mock.

I have setup a mock() in the unit test but it seems to be ignoring what I'm doing, is some of the setup wrong?

Method I'm testing

public ArrayList<Module> getAssignedModulesWithDetails() {
        CourseLoader courseLoader = new CourseLoader();
        ArrayList<Module> assignedModules = new ArrayList<>();
        
        for (Course course : courseLoader.loadAll()) {
            ArrayList<Module> courseModules = course.getModules();
            for (Module module : courseModules) {
                if (module.getInstructor() != null && module.getInstructor().equals(this.getId())) {
                    assignedModules.add(module);
                }
            }
        }

        return assignedModules;
    }

Unit test

@Test
    public void testYouCanGetAssignedModulesWithDetails() {
        CourseLoader courseLoaderMock = mock(CourseLoader.class);
        ArrayList<Course> mockedCourses = new ArrayList<>();

        ArrayList<Module> mockedModules = new ArrayList<>();
        Module module1 = new Module(this.module1, "Module1", true, 4, false, this.id);
        Module module2 = new Module(this.module2, "Module2", true, 4, false, this.id);
        Module module3 = new Module(this.module3, "Module3", true, 4, false, this.id);
        mockedModules.add(module1);
        mockedModules.add(module2);
        mockedModules.add(module3);
        Course mockedCourse = new Course(UUID.randomUUID(), "Mocked Course", true, mockedModules);

        mockedCourses.add(mockedCourse);
        when(courseLoaderMock.loadAll()).thenReturn(mockedCourses);

        ArrayList<Module> assignedModulesWithDetails = this.instructor.getAssignedModulesWithDetails();

        assertEquals(0, assignedModulesWithDetails.size());
    }
John_Mason27
  • 227
  • 4
  • 17
  • As far as I know, you can not mock `new` instance in JUnit 5 + Mockito. – matoni May 21 '22 at 09:49
  • do you know how I'd go about doing it? – John_Mason27 May 21 '22 at 09:52
  • If you had something like this: `getAssignedModulesWithDetails(CourseLoader courseLoader)` you will be able to pass mock and verify interactions. Or alternativelly, `getAssignedModulesWithDetails() { CourseLoader courseLoader = createCourseLoader(); }` in such case, you will be able to mock createCourseLoader() method to return mock and verify interactions. – matoni May 21 '22 at 09:55
  • Hmm okay I'll have a think about refactoring thanks! – John_Mason27 May 21 '22 at 10:01
  • Since Mockito 3.5 version you can mock object construction. Example: https://stackoverflow.com/questions/72337164/powermock-whennew-alternative/72338212#72338212 – Eugene May 23 '22 at 21:40

0 Answers0