Skip to content
Advertisement

How to use mockito when a funtion is using the other function’s return data?

I am learning Junit with mockito. I got a scenario where I need to write the testcase for a function which calling other function and using that function return data.

I have a two functions called courseComplete and courseCount in the class StudentHelper

courseComplete :

public String courseComplete(Student std) {
    int count = courseCount(std); //Calling another function
    if(count >= 2) {
        return "Courses Registered";
    } else {
        return "Courses Not Registered";
    }
}

courseCount :

public int courseCount(Student std) {
    return std.getCourses.size(); // Student class contains a courses list.
}

Now I need to write unit testcases for the courseComplete function. How can I pass the value to the count variable without calling the courseCount method in courseComplete Function? Is it possible with mockito? I tried by the following code :

when(StudentHelper.courseCount(std)).thenReturn(2); // std is the object which I created in the testclass.

But this is not working. Please anyone help me. Thanks.

Advertisement

Answer

You need to create a mock instance for the class under test:-

final StudentHelper mockHelper = mock(StudentHelper.class);

Then you can go ahead and use ArgumentMatchers to mock your behaviour:-

final Student expected = new Student("Dave"); 
when(mockHelper.courseCount(eq(expected)).thenReturn(2);

The above example will only execute when the method is called with your expected value.

Note that you can use matchers such as any(Student.class) to provide more flexibility.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement