更新时间:2023-11-20 22:35:04
你必须使用 间谍.这里的问题是您想验证一个方法是在 real 对象上调用的,而不是在模拟对象上调用的.你不能在这里使用模拟,因为它会存根类中的所有方法,因此也存根 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.