-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
TerminalMockCandidateFilter.java
52 lines (46 loc) · 1.92 KB
/
TerminalMockCandidateFilter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.configuration.injection.filter;
import static org.mockito.internal.exceptions.Reporter.cannotInjectDependency;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.util.reflection.BeanPropertySetter;
import org.mockito.plugins.MemberAccessor;
/**
* This node returns an actual injecter which will be either :
*
* <ul>
* <li>an {@link OngoingInjector} that do nothing if a candidate couldn't be found</li>
* <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>
* </ul>
*/
public class TerminalMockCandidateFilter implements MockCandidateFilter {
@Override
public OngoingInjector filterCandidate(
final Collection<Object> mocks,
final Field candidateFieldToBeInjected,
final List<Field> allRemainingCandidateFields,
final Object injectee,
final Field injectMocksField) {
if (mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
MemberAccessor accessor = Plugins.getMemberAccessor();
return () -> {
try {
if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected)
.set(matchingMock)) {
accessor.set(candidateFieldToBeInjected, injectee, matchingMock);
}
} catch (RuntimeException | IllegalAccessException e) {
throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e);
}
return matchingMock;
};
}
return OngoingInjector.nop;
}
}