【问题标题】:How to use mockito when a funtion is using the other function's return data?当一个函数使用另一个函数的返回数据时如何使用mockito?
【发布时间】:2021-08-02 13:33:25
【问题描述】:

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

我在 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 方法的情况下将值传递给 count 变量? mockito 可以吗?我尝试了以下代码:

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

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

【问题讨论】:

    标签: java mockito junit5


    【解决方案1】:

    你需要为被测类创建一个模拟实例:-

    final StudentHelper mockHelper = mock(StudentHelper.class);
    

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

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

    上面的例子只有在使用你的期望值调用方法时才会执行。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-13
      • 2015-07-16
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多