org.mockito.internal.util.collections.HashCodeAndEqualsMockWrapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mockito-core Show documentation
Show all versions of mockito-core Show documentation
Mockito mock objects library core API and implementation
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util.collections;
import org.mockito.internal.util.MockUtil;
/**
* hashCode and equals safe mock wrapper.
*
*
* It doesn't use the actual mock {@link Object#hashCode} and {@link Object#equals} method as they might
* throw an NPE if those method cannot be stubbed even internally.
*
*
*
* Instead the strategy is :
*
* - For hashCode : use {@link System#identityHashCode}
* - For equals : use the object reference equality
*
*
*
* @see HashCodeAndEqualsSafeSet
*/
public class HashCodeAndEqualsMockWrapper {
private final Object mockInstance;
public HashCodeAndEqualsMockWrapper(Object mockInstance) {
this.mockInstance = mockInstance;
}
public Object get() {
return mockInstance;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HashCodeAndEqualsMockWrapper)) {
return false;
}
HashCodeAndEqualsMockWrapper that = (HashCodeAndEqualsMockWrapper) o;
return mockInstance == that.mockInstance;
}
@Override
public int hashCode() {
return System.identityHashCode(mockInstance);
}
public static HashCodeAndEqualsMockWrapper of(Object mock) {
return new HashCodeAndEqualsMockWrapper(mock);
}
@Override
public String toString() {
return "HashCodeAndEqualsMockWrapper{"
+ "mockInstance="
+ (MockUtil.isMock(mockInstance)
? MockUtil.getMockName(mockInstance)
: typeInstanceString())
+ '}';
}
private String typeInstanceString() {
return mockInstance.getClass().getSimpleName()
+ "("
+ System.identityHashCode(mockInstance)
+ ")";
}
}