Home | History | Annotate | Download | only in collections
      1 /*
      2  * Copyright (c) 2007 Mockito contributors
      3  * This program is made available under the terms of the MIT License.
      4  */
      5 package org.mockito.internal.util.collections;
      6 
      7 import org.mockito.internal.util.MockUtil;
      8 
      9 /**
     10  * hashCode and equals safe mock wrapper.
     11  *
     12  * <p>
     13  *     It doesn't use the actual mock {@link Object#hashCode} and {@link Object#equals} method as they might
     14  *     throw an NPE if those method cannot be stubbed <em>even internally</em>.
     15  * </p>
     16  *
     17  * <p>
     18  *     Instead the strategy is :
     19  *     <ul>
     20  *         <li>For hashCode : <strong>use {@link System#identityHashCode}</strong></li>
     21  *         <li>For equals : <strong>use the object reference equality</strong></li>
     22  *     </ul>
     23  * </p>
     24  *
     25  * @see HashCodeAndEqualsSafeSet
     26  */
     27 public class HashCodeAndEqualsMockWrapper {
     28 
     29     private Object mockInstance;
     30 
     31     public HashCodeAndEqualsMockWrapper(Object mockInstance) {
     32         this.mockInstance = mockInstance;
     33     }
     34 
     35     public Object get() {
     36         return mockInstance;
     37     }
     38 
     39     @Override
     40     public boolean equals(Object o) {
     41         if (this == o) return true;
     42         if (!(o instanceof HashCodeAndEqualsMockWrapper)) return false;
     43 
     44         HashCodeAndEqualsMockWrapper that = (HashCodeAndEqualsMockWrapper) o;
     45 
     46         return mockInstance == that.mockInstance;
     47     }
     48 
     49     @Override
     50     public int hashCode() {
     51         return System.identityHashCode(mockInstance);
     52     }
     53 
     54     public static HashCodeAndEqualsMockWrapper of(Object mock) {
     55         return new HashCodeAndEqualsMockWrapper(mock);
     56     }
     57 
     58     @Override public String toString() {
     59         MockUtil mockUtil = new MockUtil();
     60         return "HashCodeAndEqualsMockWrapper{" +
     61                 "mockInstance=" + (mockUtil.isMock(mockInstance) ? mockUtil.getMockName(mockInstance) : typeInstanceString()) +
     62                 '}';
     63     }
     64 
     65     private String typeInstanceString() {
     66         return mockInstance.getClass().getSimpleName() + "(" + System.identityHashCode(mockInstance) + ")";
     67     }
     68 }
     69