Mockito, check that the function is called 0 times

I use Mockito to write my test case. I have a simple class that contains a function countPerson(boolean)that I am interested in checking:

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 a method countPerson(boolean):

@Test 
public void testCountPerson() {    
    School mSchool = School.getInstance();
    School spySchool = Mockito.spy(mSchool);
    spySchool.countPerson(true);

    //Verify the function countIncludeTeacher is invoked once
    verify(spySchool).countIncludeTeacher();
    //Until here things are working well.

    spySchool.countPerson(false);
    //ERROR HERE when I try to verify the function has 0 times invoke
    verify(spySchool, times(0)).countIncludeTeacher();      
}

I have the following error:

org.mockito.exceptions.verification.NeverWantedButInvoked: school.countIncludeTeacher (); Never wanted here: (SchoolTest.java 20)

Why does checking 0 times not work?

+4
source share
2 answers

, verify spySchool. :

@Test 
public void testCountPerson() {    
    School mSchool = School.getInstance();
    School spySchool = Mockito.spy(mSchool); // a spy is created here, Mockito is listening in.
    spySchool.countPerson(true); // real method is invoked
    verify(spySchool).countIncludeTeacher(); // our spy identified that countIncludeTeacher was called

    spySchool.countPerson(false); // real method is invoked
    verify(spySchool, times(0)).countIncludeTeacher(); // our spy still identified that countIncludeTeacher was called, before it was called before
}

, verify , countIncludeTeacher , .

, verifyNoMoreInteractions, , . reset .

, , Mockito Javadoc:

. , , , verifyNoMoreInteractions() . verifyNoMoreInteractions() . verifyNoMoreInteractions() - . , . , . .

Mockito , , . reset , .

reset(), , , , , . reset() . , , . : ", ".

: true false.

+5

, DO countIncludeTeacher() spySchool.countPerson(true) . , -.

, , reset .

+1

Source: https://habr.com/ru/post/1615575/