当一个函数正在使用另一个函数的 return 数据时如何使用 mockito?

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

我正在使用 mockito 学习 Junit。我有一个场景,我需要为一个函数编写测试用例,该函数调用其他函数并使用该函数 return 数据。

我在 class StudentHelper

中有两个函数 courseCompletecourseCount

课程完成:

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

课程数:

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

现在我需要为 courseComplete 函数编写单元测试用例。如何在不调用 courseComplete 函数中的 courseCount 方法的情况下将值传递给计数变量? mockito 有可能吗?我尝试了以下代码:

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

但这不起作用。请任何人帮助我。谢谢。

您需要为被测 class 创建一个模拟实例:-

final StudentHelper mockHelper = mock(StudentHelper.class);

然后你可以继续使用ArgumentMatchers来模拟你的行为:-

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

以上示例只会在使用您的预期值调用方法时执行。

请注意,您可以使用 any(Student.class) 等匹配器来提供更大的灵活性。