…lines 1–6 unchanged (6 lines)
7import org.mockito.exceptions.Reporter;
8import org.mockito.internal.util.reflection.BeanPropertySetter;
9import org.mockito.internal.util.reflection.FieldSetter;
10
11import java.lang.reflect.Field;
12import java.util.Collection;
13import java.util.List;
14
15/**
16 * This node returns an actual injecter which will be either :
17 *
18 * <ul>
19 * <li>an {@link OngoingInjecter} that do nothing if a candidate couldn't be found</li>
20 * <li>an {@link OngoingInjecter} that will try to inject the candidate trying first the property setter then if not possible try the field access</li>
21 * </ul>
22 */
23public class FinalMockCandidateFilter implements MockCandidateFilter {
24 public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, List<Field> fields, final Object fieldInstance) {
25 if(mocks.size() == 1) {
26 final Object matchingMock = mocks.iterator().next();
27
28 return new OngoingInjecter() {
29 public Object thenInject() {
30 try {
31 if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
32 new FieldSetter(fieldInstance, field).set(matchingMock);
33 }
34 } catch (RuntimeException e) {
35 new Reporter().cannotInjectDependency(field, matchingMock, e);
36 }
37 return matchingMock;
38 }
39 };
40 }
41
42 return new OngoingInjecter() {
43 public Object thenInject() {
44 return null;
45 }
46 };
47
48 }
49}
50