1 3 package org.jmock.core.constraint; 4 5 import java.lang.reflect.Array ; 6 import org.jmock.core.Constraint; 7 8 9 13 public class IsEqual implements Constraint 14 { 15 private Object object; 16 17 public IsEqual( Object equalArg ) { 18 object = equalArg; 19 } 20 21 public boolean eval( Object arg ) { 22 return areEqual(object, arg); 23 } 24 25 public StringBuffer describeTo( StringBuffer buffer ) { 26 buffer.append("eq("); 27 if (object == null) { 28 buffer.append("null"); 29 } else { 30 buffer.append("<"); 31 buffer.append(object); 32 buffer.append(">"); 33 } 34 buffer.append(")"); 35 36 return buffer; 37 } 38 39 private static boolean areEqual( Object o1, Object o2 ) { 40 if (o1 == null || o2 == null) { 41 return o1 == null && o2 == null; 42 } else if (isArray(o1)) { 43 return isArray(o2) && areArraysEqual(o1, o2); 44 } else { 45 return o1.equals(o2); 46 } 47 } 48 49 private static boolean areArraysEqual( Object o1, Object o2 ) { 50 return areArrayLengthsEqual(o1, o2) 51 && areArrayElementsEqual(o1, o2); 52 } 53 54 private static boolean areArrayLengthsEqual( Object o1, Object o2 ) { 55 return Array.getLength(o1) == Array.getLength(o2); 56 } 57 58 private static boolean areArrayElementsEqual( Object o1, Object o2 ) { 59 for (int i = 0; i < Array.getLength(o1); i++) { 60 if (!areEqual(Array.get(o1, i), Array.get(o2, i))) return false; 61 } 62 return true; 63 } 64 65 private static boolean isArray( Object o ) { 66 return o.getClass().isArray(); 67 } 68 } 69 | Popular Tags |