Search code examples
mockitojunit4

Mockito change return value of a method


In the test class trying to change the result returned from a method call.

Trying to return true when isExistStudentInList(...) is called from the test class when testing method1.

Tried the below but, it is actually executing the method rather than returning the true value.

Any suggessions on how this can be done?

public class School { 
    public static void main(String[] s) {
        ..........
    }

    public void method1(List<Students> lstStudents) {
        int ilCounter       = 0; 
        .....
        while(rs.next()) { 
            ilCounter++;

            Students voObj = new Students();
            voObj.setName(rs.getString(1));
            voObj.setDepartment(rs.getString(2));
                .....           

            boolean existStu = isExistStudentInList(lstStudents, voObj);
            if(elementId == 0 && existStu) {
                ilCounter--;    
                .....
            } 
        }
    }

    public boolean isExistStudentInList(List<Students> lstJobElements, Students voObj) {
        boolean checkStudent;
        .........
        return checkStudent;
    }
}

public class SchoolTest { 
    @InjectMocks
    School school;

    .....
    @Before
    public void setUp() {
        ........
    }

    @Test
    public void testMethod1() throws SQLException {
        ........    
        when(school.isExistStudentInList(getSampleDataForStudents(), (Students)getSampleDataForStudents().get(0))).thenReturn(true);
        school.method1(getSampleDataForStudents());         
        ....
    }

    private List<Students> getSampleDataForStudents() {
        List<Students> lstStudents = new ArrayList<Students>();

                Students student1 = new Students();
        student1 .setName("aaaa");
        student1 .setDepartment("1222");
        .....       

        Students student2 = new Students();
        student1 .setName("bbbb");
        student1 .setDepartment("1222");
        .....

        lstStudents.add(student1);
        lstStudents.add(student2);

        return lstStudents;
    }
}

Solution

  • You are using @InjectMocks which creates an instance of the class and injects the mocks that are created with @Mock or @Spy. But School is neither a mock nor spy. Therefore, I am surprised your code is not throwing any exceptions when you call when() on it.

    You can accomplish what you are trying to do by making School a spy. This will allow the underlying methods to get called unless they are stubbed.

    School school = Mockito.spy(new School());
    

    However, I think you should really change the way you are testing your code or abstract some of the implementation because you should not have to mock / spy on the class you are testing.