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() {...}
}
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?
}
}
How to use Mockito to check/verify countIncludeTeacher()
is invoked once in my test case?
答案 0 :(得分:5)
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();
}
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.
答案 1 :(得分:0)
verify(mSchool, times(1)).countIncludeTeacher();
Edit: As @Tunaki mentioned this won't work. You should use spy.
答案 2 :(得分:0)
If you want exactly one invocation, you can go with
verify(mSchool, times(1)).countIncludeTeacher();
I you want to check for interaction and you don't care how often it happens, do
verify(mSchool).countIncludeTeacher();
答案 3 :(得分:0)
您有两种选择。
答案 4 :(得分:-2)
You need to do by this way
Mockito.doNothing().when(mock).countIncludeTeacher();