• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.configuration.injection.filter;
6 
7 import org.mockito.internal.util.reflection.BeanPropertySetter;
8 
9 import java.lang.reflect.Field;
10 import java.util.Collection;
11 import java.util.List;
12 
13 import static org.mockito.internal.exceptions.Reporter.cannotInjectDependency;
14 import static org.mockito.internal.util.reflection.FieldSetter.setField;
15 
16 /**
17  * This node returns an actual injecter which will be either :
18  *
19  * <ul>
20  * <li>an {@link OngoingInjector} that do nothing if a candidate couldn't be found</li>
21  * <li>an {@link OngoingInjector} that will try to inject the candidate trying first the property setter then if not possible try the field access</li>
22  * </ul>
23  */
24 public class TerminalMockCandidateFilter implements MockCandidateFilter {
filterCandidate(final Collection<Object> mocks, final Field candidateFieldToBeInjected, final List<Field> allRemainingCandidateFields, final Object injectee)25     public OngoingInjector filterCandidate(final Collection<Object> mocks,
26                                            final Field candidateFieldToBeInjected,
27                                            final List<Field> allRemainingCandidateFields,
28                                            final Object injectee) {
29         if(mocks.size() == 1) {
30             final Object matchingMock = mocks.iterator().next();
31 
32             return new OngoingInjector() {
33                 public Object thenInject() {
34                     try {
35                         if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected).set(matchingMock)) {
36                             setField(injectee, candidateFieldToBeInjected,matchingMock);
37                         }
38                     } catch (RuntimeException e) {
39                         throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e);
40                     }
41                     return matchingMock;
42                 }
43             };
44         }
45 
46         return OngoingInjector.nop;
47 
48     }
49 }
50