• 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 static org.mockito.internal.exceptions.Reporter.cannotInjectDependency;
8 
9 import java.lang.reflect.Field;
10 import java.util.Collection;
11 import java.util.List;
12 
13 import org.mockito.internal.configuration.plugins.Plugins;
14 import org.mockito.internal.util.reflection.BeanPropertySetter;
15 import org.mockito.plugins.MemberAccessor;
16 
17 /**
18  * This node returns an actual injecter which will be either :
19  *
20  * <ul>
21  * <li>an {@link OngoingInjector} that do nothing if a candidate couldn't be found</li>
22  * <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>
23  * </ul>
24  */
25 public class TerminalMockCandidateFilter implements MockCandidateFilter {
26     @Override
filterCandidate( final Collection<Object> mocks, final Field candidateFieldToBeInjected, final List<Field> allRemainingCandidateFields, final Object injectee)27     public OngoingInjector filterCandidate(
28             final Collection<Object> mocks,
29             final Field candidateFieldToBeInjected,
30             final List<Field> allRemainingCandidateFields,
31             final Object injectee) {
32         if (mocks.size() == 1) {
33             final Object matchingMock = mocks.iterator().next();
34 
35             MemberAccessor accessor = Plugins.getMemberAccessor();
36             return () -> {
37                 try {
38                     if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected)
39                             .set(matchingMock)) {
40                         accessor.set(candidateFieldToBeInjected, injectee, matchingMock);
41                     }
42                 } catch (RuntimeException | IllegalAccessException e) {
43                     throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e);
44                 }
45                 return matchingMock;
46             };
47         }
48 
49         return OngoingInjector.nop;
50     }
51 }
52