可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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.
回答2:
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:
verify(mSchool, times(1)).countIncludeTeacher();
Edit: As @Tunaki mentioned this won't work. You should use spy.
回答4:
You have two options.
- Set up the School such that is has X teachers and Y students and verify that either X+Y or just X is returned. This would be my preference as mocking the class your are testing feels icky to me. The two methods should be well tested, so any errors will be caught in the tests for them.
- Use Spy as suggested by Tunaki.
回答5:
You need to do by this way
Mockito.doNothing().when(mock).countIncludeTeacher();