1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package com.stephenduncanjr.easymock.matcher;
16
17 import java.lang.reflect.InvocationTargetException;
18 import java.util.HashMap;
19 import java.util.Map;
20 import java.util.Map.Entry;
21
22 import org.apache.commons.beanutils.PropertyUtils;
23 import org.easymock.IArgumentMatcher;
24
25 /***
26 * Matches based on a bean property.
27 *
28 * @author stephen.duncan (Stephen C. Duncan Jr.
29 * <stephen.duncan@gmail.com>)
30 * @since 1.0
31 */
32 public class BeanProperty implements IArgumentMatcher
33 {
34 /*** Map of property names to values to match against. */
35 private final Map<String, ?> expectedProperties;
36
37 /***
38 * Creates a new match for the given map of property names to values.
39 *
40 * @param expectedProperties
41 * @since 1.1
42 */
43 public BeanProperty(final Map<String, ?> expectedProperties)
44 {
45 super();
46 this.expectedProperties = expectedProperties;
47 }
48
49 /***
50 * Creates a new matcher for the given property name and value.
51 *
52 * @param expectedPropertyValue
53 * @param propertyName
54 */
55 public BeanProperty(final String propertyName, final Object expectedPropertyValue)
56 {
57 super();
58 final Map<String, Object> properties = new HashMap<String, Object>();
59 properties.put(propertyName, expectedPropertyValue);
60 this.expectedProperties = properties;
61 }
62
63 /***
64 * @see org.easymock.IArgumentMatcher#appendTo(java.lang.StringBuffer)
65 */
66 public void appendTo(final StringBuffer buffer)
67 {
68 buffer.append("propertyEq(");
69
70 for(final Entry<String, ?> entry : this.expectedProperties.entrySet())
71 {
72 buffer.append(entry.getKey());
73 buffer.append("=");
74 buffer.append(entry.getValue());
75 buffer.append(", ");
76 }
77
78 buffer.replace(buffer.length() - 2, buffer.length(), ")");
79 }
80
81 /***
82 * @see org.easymock.IArgumentMatcher#matches(java.lang.Object)
83 */
84 public boolean matches(final Object actual)
85 {
86 for(final Entry<String, ?> entry : this.expectedProperties.entrySet())
87 {
88 try
89 {
90 final Object actualValue = PropertyUtils.getProperty(actual, entry.getKey());
91 if(!(entry.getValue() == actualValue || entry.getValue().equals(actualValue)))
92 {
93 return false;
94 }
95 }
96 catch(IllegalAccessException e)
97 {
98 return false;
99 }
100 catch(InvocationTargetException e)
101 {
102 return false;
103 }
104 catch(NoSuchMethodException e)
105 {
106 return false;
107 }
108 catch(RuntimeException e)
109 {
110 return false;
111 }
112 }
113
114 return true;
115 }
116 }