Mockito verify a function is invoked once in my case

时间:2015-11-12 11:25:40

标签: java unit-testing mockito

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?

5 个答案:

答案 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)

您有两种选择。

  • 设置学校,让X老师和Y学生同时确认返回X + Y或X.这将是我的偏好,因为嘲笑你正在测试的课程对我来说很蠢。这两种方法应该经过充分测试,因此任何错误都会在测试中被捕获。
  • 按照Tunaki的建议使用间谍。

答案 4 :(得分:-2)

You need to do by this way

Mockito.doNothing().when(mock).countIncludeTeacher();