Spy doesn't forward hashcode/equals to actual object
Author: cdalexndrCreated Jun 16, 2021Updated Mar 7, 2026
Mockito 3.11.1
public class MockitoTest {
private static class ValueHolder {
private final String value;
public ValueHolder( String value ) {
this.value = value;
}
public String getValue() {
return value;
}
@Override public boolean equals( Object o ) {
if (this == o) return true;
if (!(o instanceof ValueHolder)) return false;
ValueHolder that = (ValueHolder) o;
return getValue().equals( that.getValue() );
}
@Override
public int hashCode() {
return Objects.hash( getValue() );
}
}
@Test
public void test() {
ValueHolder value = new ValueHolder( "test" );
ValueHolder spy = Mockito.spy( value );
assert value.equals( spy );
assert spy.equals( value ); //fails
assert value.hashCode() == spy.hashCode(); //fails
}
}- The mockito message in the stacktrace have useful information, but it didn't help
- The problematic code (if that's possible) is copied here; Note that some configuration are impossible to mock via Mockito
- Provide versions (mockito / jdk / os / any other relevant information)
- Provide a Short, Self Contained, Correct (Compilable), Example of the issue (same as any question on stackoverflow.com)
- Read the contributing guide
Source: mockito/mockito