Mockito验证在我的情况下调用一次函数 [英] Mockito verify a function is invoked once in my case
问题描述
我正在使用 Mockito 来编写我的测试用例。我有一个简单的类,其中包含一个函数 countPerson(boolean)
我有兴趣测试它:
I am using Mockito to write my test case. I have a simple class which contains a function countPerson(boolean)
which I am interested to test:
public class School {
//School is a singleton class.
public void countPerson(boolean includeTeacher) {
if (includeTeacher) {
countIncludeTeacher();
return;
}
countOnlyStudents();
}
public void countIncludeTeacher() {...}
public void countOnlyStudents() {...}
}
在我的单元测试中,我想测试 countPerson(boolean)
函数:
In my unit test, I want to test the countPerson(boolean)
function:
public class SchoolTest{
private School mSchool;
@Before
public void setUp(){
mSchool = School.getInstance();
}
@Test
public void testCountPerson() {
mSchool.countPerson(true);
//How to test/verify countIncludeTeacher() is invoked once?
}
}
如何使用Mockito检查/验证 countIncludeTeacher()
在我的测试用例中被调用一次?
How to use Mockito to check/verify countIncludeTeacher()
is invoked once in my test case?
推荐答案
你将不得不使用间谍。这里的问题是你要验证是否在真实的对象上调用了一个方法,而不是在模拟上。你不能在这里使用mock,因为它会存在类中的所有方法,因此默认情况下也会将 countPerson
除去。
You will have to use a spy. The problem here is that you want to verify that a method was called on a real object, not on a mock. You can't use a mock here, since it will stub all the methods in the class, thereby stubbing also countPerson
to do nothing by default.
@Test
public void testCountPerson() {
School school = School.getInstance();
School spySchool = Mockito.spy(school);
spySchool.countPerson(true);
verify(spySchool).countIncludeTeacher();
}
但是,请注意在使用间谍时应该非常小心,因为除非存在,真正的方法被称为。引用Mockito Javadoc:
However, note that you should be very careful when using spies because, unless stubbed, the real methods are gettings called. Quoting Mockito Javadoc:
真正的间谍应该小心使用<偶尔,例如在处理遗留代码时。
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
这篇关于Mockito验证在我的情况下调用一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!