01: package net.sf.mockcreator.expectable;
02:
03: import java.lang.reflect.Method;
04: import java.lang.reflect.Modifier;
05:
06: import net.sf.mockcreator.utils.CompareByValue;
07:
08: /**
09: * Compares two Java Beans by iterating properties and comparing their values.
10: */
11: public class ExpectJavaBean implements ExpectableParameter {
12:
13: Object expected;
14:
15: public ExpectJavaBean(Object expected) {
16: this .expected = expected;
17: }
18:
19: public boolean isExpected(Object actual) {
20: if (expected == actual)
21: return true;
22: if (expected == null && actual != null)
23: return false;
24: if (expected != null && actual == null)
25: return false;
26:
27: // iterate public get/is fields
28: Method[] methods = expected.getClass().getMethods();
29: for (int i = 0; i < methods.length; i++) {
30: Method method = methods[i];
31: if ((method.getModifiers() & Modifier.PUBLIC) == 0)
32: continue;
33: if ((method.getModifiers() & Modifier.STATIC) != 0)
34: continue;
35: if ((method.getModifiers() & Modifier.ABSTRACT) != 0)
36: continue;
37: if ((method.getModifiers() & Modifier.NATIVE) != 0)
38: continue;
39:
40: if (method.getParameterTypes().length != 0)
41: continue;
42: if (method.getReturnType().equals(void.class))
43: continue;
44:
45: if (!method.getName().startsWith("get")
46: && !method.getName().startsWith("is"))
47: continue;
48:
49: try {
50: Method method2 = actual.getClass().getMethod(
51: method.getName(), (Class[]) null);
52:
53: Object expectedPropertyValue = method.invoke(expected,
54: (Object[]) null);
55: Object actualPropertyValue = method2.invoke(actual,
56: (Object[]) null);
57: if (!CompareByValue.equals(expectedPropertyValue,
58: actualPropertyValue))
59: return false;
60: } catch (Exception ex) {
61: return false;
62: }
63: }
64:
65: return true;
66: }
67: }
|