Mockito verify(...) fails - "Actually, there were zero interactions with this mock." in more than one test run sequentially

Viewed 4774

I have a Wrapper class that causes that instead of equals method, the method equalsWithoutId is called on wrapped object. Implementation here:

import org.apache.commons.lang3.Validate;

public class IdAgnosticWrapper {

    private final IdAgnostic wrapped;

    public IdAgnosticWrapper(IdAgnostic wrapped) {
        Validate.notNull(wrapped, "wrapped must not be null");
        this.wrapped = wrapped;
    }

    @Override
    public int hashCode() {
        return wrapped.hashCodeWithoutId();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof IdAgnosticWrapper)) {
            return false;
        }
        return wrapped.equalsWithoutId(((IdAgnosticWrapper) obj).getWrapped());
    }

    public IdAgnostic getWrapped() {
        return wrapped;
    }
}

IdAgnostic is a simple interface, that ensures that required methods are present

public interface IdAgnostic {
    int hashCodeWithoutId();
    boolean equalsWithoutId(Object o);
}

Then I have some Unit tests that should test, if equals() delegates to wrapped#equalsWithoutId() method and hashCode() delegates to wrapped#hashCodeWithoutId.

Now I try to test it by these tests

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.mockito.Mockito.verify;

public class IdAgnosticWrapperTest {

    @Mock
    private IdAgnostic wrappedMock;

    @InjectMocks
    private IdAgnosticWrapper tested;


    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testEquals_EqualsWithoutIdIsCalledOnWrapped() throws Exception {
        tested.equals(tested);
        verify(wrappedMock).equalsWithoutId(tested.getWrapped());
    }

    @Test
    public void testHashCode_HashCodeWithoutIdIsCalledOnWrapped() throws Exception {
        tested.hashCode();
        verify(wrappedMock).hashCodeWithoutId(); //line 34
    }
}

As you can see, I just create wrapped mock and I test, whether equals and hashcode delegate the functionality.

If I run tests separately, everything works fine, but if I run both tests sequentially, the second one fails with this message

Wanted but not invoked:
wrappedMock.hashCodeWithoutId();
-> at com.my.app.utils.IdAgnosticWrapperTest.testHashCode_HashCodeWithoutIdIsCalledOnWrapped(IdAgnosticWrapperTest.java:34)
Actually, there were zero interactions with this mock.

Why does this happen?

1 Answers
Related