待测试方法:
public boolean isValidStudent(String fName, String lName){
Student student = new Student(fName, lName);//-----------this creates problem
return (studentDao.get(student).isEmpty())?false : true;
}
下面的测试失败,因为当我专门指定它返回我创建的列表时,方法 stub 总是返回一个空列表。 看来考试的学生对象和方法不一样。我该怎么做才能让它发挥作用?我通过更改下面第二种方法中的方法签名来修复此问题。但我想在不改变方法的情况下做到这一点。
@Mock
Service service;
@Test
public void isValidStudent(){
studentList = new ArrayList<Student>();
studentList.add(new Student());
studentList.add(new Student());
Student student = new Student("Tom", "Clancy");//---this creates problem.
when(studentDao.get(student)).thenReturn(studentList);
assertTrue(service.isValidStudent("Tom", "Clancy"));
}
第二种有效方法:
在这种方法中,我更改了方法签名以接受学生对象,并且效果很好。我在测试中仅实例化一次学生对象,并将其用于方法 stub 以及将其传递给被测方法。
public boolean isValidStudent(Student student){
return (studentDao.get(student).isEmpty())?false : true;
}
@Mock
Service service;
@Test
public void isValidStudent(){
studentList = new ArrayList<Student>();
studentList.add(new Student());
studentList.add(new Student());
Student student = new Student("Tom", "Clancy");
when(studentDao.get(student)).thenReturn(studentList);
assertTrue(service.isValidStudent(student));
}
最佳答案
假设:您的 Student
类未实现 .equals()
/.hashCode()
。
默认情况下,when()
你模拟一个方法调用,mockito会检查它的参数.equals()
是否是你传递的参数它作为模拟方法的(一个)参数。
但是,如果您不实现.equals()
,那么您将遇到以下情况:
final Student s1 = new Student("foo", "bar");
final Student s2 = new Student("foo", "bar");
s1.equals(s2); // <--- FALSE!
这就是这里发生的事情。在您的第一个场景中,您创建了一个 Student
,对您来说,它在逻辑上是平等的,但这不是 Mockito 想要的。因此,在第一个场景中,.get()
将返回 null
。
但是,在第二个中,您传递了相同的引用;由于您没有实现 .equals()
,因此 Object
的 .equals()
会发生,并且对于此 .equals ()
实现,obj1.equals(obj2)
当且仅当 obj1 == obj2
—— 就是这种情况。根据您的情况,继续上面的代码:
s1 == s2; // FALSE! (as in first test)
s1 == s1; // true (as in second test)
如果你想对参数更加“宽松”,你必须编写自定义参数匹配器; Mockito 也可以做到这一点(借助其 hamcrest 依赖项)。
所有这些玩笑都是说你应该通过让你的 Student
类实现 .equals()
/.hashCode()
来解决你的问题.
关于java - 在测试和待测方法中使用相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22665919/