mocks) {}
}
diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
index 60882f95fc..2994f1c84e 100644
--- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
+++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
@@ -29,13 +29,13 @@ public static Object processAnnotationForMock(Mock annotation, Class> type, St
} else {
mockSettings.name(annotation.name());
}
- if(annotation.serializable()){
+ if (annotation.serializable()) {
mockSettings.serializable();
}
- if(annotation.stubOnly()){
+ if (annotation.stubOnly()) {
mockSettings.stubOnly();
}
- if(annotation.lenient()){
+ if (annotation.lenient()) {
mockSettings.lenient();
}
diff --git a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java
index 1a9ce04155..27ebc4a04d 100644
--- a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java
+++ b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java
@@ -44,13 +44,15 @@
* This engine will fail, if the field is also annotated with incompatible Mockito annotations.
*/
@SuppressWarnings({"unchecked"})
-public class SpyAnnotationEngine implements AnnotationEngine, org.mockito.configuration.AnnotationEngine {
+public class SpyAnnotationEngine
+ implements AnnotationEngine, org.mockito.configuration.AnnotationEngine {
@Override
public void process(Class> context, Object testInstance) {
Field[] fields = context.getDeclaredFields();
for (Field field : fields) {
- if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) {
+ if (field.isAnnotationPresent(Spy.class)
+ && !field.isAnnotationPresent(InjectMocks.class)) {
assertNoIncompatibleAnnotations(Spy.class, field, Mock.class, Captor.class);
field.setAccessible(true);
Object instance;
@@ -58,7 +60,8 @@ public void process(Class> context, Object testInstance) {
instance = field.get(testInstance);
if (MockUtil.isMock(instance)) {
// instance has been spied earlier
- // for example happens when MockitoAnnotations.initMocks is called two times.
+ // for example happens when MockitoAnnotations.initMocks is called two
+ // times.
Mockito.reset(instance);
} else if (instance != null) {
field.set(testInstance, spyInstance(field, instance));
@@ -66,45 +69,55 @@ public void process(Class> context, Object testInstance) {
field.set(testInstance, spyNewInstance(testInstance, field));
}
} catch (Exception e) {
- throw new MockitoException("Unable to initialize @Spy annotated field '" + field.getName() + "'.\n" + e.getMessage(), e);
+ throw new MockitoException(
+ "Unable to initialize @Spy annotated field '"
+ + field.getName()
+ + "'.\n"
+ + e.getMessage(),
+ e);
}
}
}
}
private static Object spyInstance(Field field, Object instance) {
- return Mockito.mock(instance.getClass(),
- withSettings().spiedInstance(instance)
- .defaultAnswer(CALLS_REAL_METHODS)
- .name(field.getName()));
+ return Mockito.mock(
+ instance.getClass(),
+ withSettings()
+ .spiedInstance(instance)
+ .defaultAnswer(CALLS_REAL_METHODS)
+ .name(field.getName()));
}
private static Object spyNewInstance(Object testInstance, Field field)
throws InstantiationException, IllegalAccessException, InvocationTargetException {
- MockSettings settings = withSettings().defaultAnswer(CALLS_REAL_METHODS)
- .name(field.getName());
+ MockSettings settings =
+ withSettings().defaultAnswer(CALLS_REAL_METHODS).name(field.getName());
Class> type = field.getType();
if (type.isInterface()) {
return Mockito.mock(type, settings.useConstructor());
}
int modifiers = type.getModifiers();
if (typeIsPrivateAbstractInnerClass(type, modifiers)) {
- throw new MockitoException(join("@Spy annotation can't initialize private abstract inner classes.",
- " inner class: '" + type.getSimpleName() + "'",
- " outer class: '" + type.getEnclosingClass().getSimpleName() + "'",
- "",
- "You should augment the visibility of this inner class"));
+ throw new MockitoException(
+ join(
+ "@Spy annotation can't initialize private abstract inner classes.",
+ " inner class: '" + type.getSimpleName() + "'",
+ " outer class: '" + type.getEnclosingClass().getSimpleName() + "'",
+ "",
+ "You should augment the visibility of this inner class"));
}
if (typeIsNonStaticInnerClass(type, modifiers)) {
Class> enclosing = type.getEnclosingClass();
if (!enclosing.isInstance(testInstance)) {
- throw new MockitoException(join("@Spy annotation can only initialize inner classes declared in the test.",
- " inner class: '" + type.getSimpleName() + "'",
- " outer class: '" + enclosing.getSimpleName() + "'",
- ""));
+ throw new MockitoException(
+ join(
+ "@Spy annotation can only initialize inner classes declared in the test.",
+ " inner class: '" + type.getSimpleName() + "'",
+ " outer class: '" + enclosing.getSimpleName() + "'",
+ ""));
}
- return Mockito.mock(type, settings.useConstructor()
- .outerInstance(testInstance));
+ return Mockito.mock(type, settings.useConstructor().outerInstance(testInstance));
}
Constructor> constructor = noArgConstructorOf(type);
@@ -121,7 +134,10 @@ private static Constructor> noArgConstructorOf(Class> type) {
try {
constructor = type.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
- throw new MockitoException("Please ensure that the type '" + type.getSimpleName() + "' has a no-arg constructor.");
+ throw new MockitoException(
+ "Please ensure that the type '"
+ + type.getSimpleName()
+ + "' has a no-arg constructor.");
}
return constructor;
}
@@ -131,17 +147,20 @@ private static boolean typeIsNonStaticInnerClass(Class> type, int modifiers) {
}
private static boolean typeIsPrivateAbstractInnerClass(Class> type, int modifiers) {
- return Modifier.isPrivate(modifiers) && Modifier.isAbstract(modifiers) && type.getEnclosingClass() != null;
+ return Modifier.isPrivate(modifiers)
+ && Modifier.isAbstract(modifiers)
+ && type.getEnclosingClass() != null;
}
- //TODO duplicated elsewhere
- private static void assertNoIncompatibleAnnotations(Class extends Annotation> annotation,
- Field field,
- Class extends Annotation>... undesiredAnnotations) {
+ // TODO duplicated elsewhere
+ private static void assertNoIncompatibleAnnotations(
+ Class extends Annotation> annotation,
+ Field field,
+ Class extends Annotation>... undesiredAnnotations) {
for (Class extends Annotation> u : undesiredAnnotations) {
if (field.isAnnotationPresent(u)) {
- throw unsupportedCombinationOfAnnotations(annotation.getSimpleName(),
- u.getSimpleName());
+ throw unsupportedCombinationOfAnnotations(
+ annotation.getSimpleName(), u.getSimpleName());
}
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/ConstructorInjection.java b/src/main/java/org/mockito/internal/configuration/injection/ConstructorInjection.java
index 380fb93da1..9946900878 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/ConstructorInjection.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/ConstructorInjection.java
@@ -37,23 +37,24 @@
*/
public class ConstructorInjection extends MockInjectionStrategy {
- public ConstructorInjection() { }
+ public ConstructorInjection() {}
public boolean processInjection(Field field, Object fieldOwner, Set mockCandidates) {
try {
- SimpleArgumentResolver simpleArgumentResolver = new SimpleArgumentResolver(mockCandidates);
- FieldInitializationReport report = new FieldInitializer(fieldOwner, field, simpleArgumentResolver).initialize();
+ SimpleArgumentResolver simpleArgumentResolver =
+ new SimpleArgumentResolver(mockCandidates);
+ FieldInitializationReport report =
+ new FieldInitializer(fieldOwner, field, simpleArgumentResolver).initialize();
return report.fieldWasInitializedUsingContructorArgs();
} catch (MockitoException e) {
- if(e.getCause() instanceof InvocationTargetException) {
+ if (e.getCause() instanceof InvocationTargetException) {
Throwable realCause = e.getCause().getCause();
throw fieldInitialisationThrewException(field, realCause);
}
// other causes should be fine
return false;
}
-
}
/**
@@ -76,10 +77,9 @@ public Object[] resolveTypeInstances(Class>... argTypes) {
private Object objectThatIsAssignableFrom(Class> argType) {
for (Object object : objects) {
- if(argType.isAssignableFrom(object.getClass())) return object;
+ if (argType.isAssignableFrom(object.getClass())) return object;
}
return null;
}
}
-
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/MockInjectionStrategy.java b/src/main/java/org/mockito/internal/configuration/injection/MockInjectionStrategy.java
index 3b4eed7f97..c4d2cb900d 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/MockInjectionStrategy.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/MockInjectionStrategy.java
@@ -17,13 +17,13 @@ public abstract class MockInjectionStrategy {
*/
public static MockInjectionStrategy nop() {
return new MockInjectionStrategy() {
- protected boolean processInjection(Field field, Object fieldOwner, Set mockCandidates) {
+ protected boolean processInjection(
+ Field field, Object fieldOwner, Set mockCandidates) {
return false;
}
};
}
-
private MockInjectionStrategy nextStrategy;
/**
@@ -37,7 +37,7 @@ protected boolean processInjection(Field field, Object fieldOwner, Set m
* @return The passed strategy instance to allow chaining.
*/
public MockInjectionStrategy thenTry(MockInjectionStrategy strategy) {
- if(nextStrategy != null) {
+ if (nextStrategy != null) {
nextStrategy.thenTry(strategy);
} else {
nextStrategy = strategy;
@@ -64,7 +64,7 @@ public MockInjectionStrategy thenTry(MockInjectionStrategy strategy) {
* @return true
if successful, false
otherwise.
*/
public boolean process(Field onField, Object fieldOwnedBy, Set mockCandidates) {
- if(processInjection(onField, fieldOwnedBy, mockCandidates)) {
+ if (processInjection(onField, fieldOwnedBy, mockCandidates)) {
return true;
}
return relayProcessToNextStrategy(onField, fieldOwnedBy, mockCandidates);
@@ -82,9 +82,11 @@ public boolean process(Field onField, Object fieldOwnedBy, Set mockCandi
* @param mockCandidates Pool of mocks to inject.
* @return true
if injection occurred, false
otherwise
*/
- protected abstract boolean processInjection(Field field, Object fieldOwner, Set mockCandidates);
+ protected abstract boolean processInjection(
+ Field field, Object fieldOwner, Set mockCandidates);
- private boolean relayProcessToNextStrategy(Field field, Object fieldOwner, Set mockCandidates) {
+ private boolean relayProcessToNextStrategy(
+ Field field, Object fieldOwner, Set mockCandidates) {
return nextStrategy != null && nextStrategy.process(field, fieldOwner, mockCandidates);
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java b/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
index 38f5760226..26066298ab 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
@@ -64,25 +64,31 @@ public class PropertyAndSetterInjection extends MockInjectionStrategy {
private final MockCandidateFilter mockCandidateFilter =
new TypeBasedCandidateFilter(
- new NameBasedCandidateFilter(
- new TerminalMockCandidateFilter()));
-
- private final ListUtil.Filter notFinalOrStatic = new ListUtil.Filter() {
- public boolean isOut(Field object) {
- return Modifier.isFinal(object.getModifiers()) || Modifier.isStatic(object.getModifiers());
- }
- };
+ new NameBasedCandidateFilter(new TerminalMockCandidateFilter()));
+ private final ListUtil.Filter notFinalOrStatic =
+ new ListUtil.Filter() {
+ public boolean isOut(Field object) {
+ return Modifier.isFinal(object.getModifiers())
+ || Modifier.isStatic(object.getModifiers());
+ }
+ };
- public boolean processInjection(Field injectMocksField, Object injectMocksFieldOwner, Set mockCandidates) {
- FieldInitializationReport report = initializeInjectMocksField(injectMocksField, injectMocksFieldOwner);
+ public boolean processInjection(
+ Field injectMocksField, Object injectMocksFieldOwner, Set mockCandidates) {
+ FieldInitializationReport report =
+ initializeInjectMocksField(injectMocksField, injectMocksFieldOwner);
// for each field in the class hierarchy
boolean injectionOccurred = false;
Class> fieldClass = report.fieldClass();
Object fieldInstanceNeedingInjection = report.fieldInstance();
while (fieldClass != Object.class) {
- injectionOccurred |= injectMockCandidates(fieldClass, fieldInstanceNeedingInjection, newMockSafeHashSet(mockCandidates));
+ injectionOccurred |=
+ injectMockCandidates(
+ fieldClass,
+ fieldInstanceNeedingInjection,
+ newMockSafeHashSet(mockCandidates));
fieldClass = fieldClass.getSuperclass();
}
return injectionOccurred;
@@ -92,33 +98,42 @@ private FieldInitializationReport initializeInjectMocksField(Field field, Object
try {
return new FieldInitializer(fieldOwner, field).initialize();
} catch (MockitoException e) {
- if(e.getCause() instanceof InvocationTargetException) {
+ if (e.getCause() instanceof InvocationTargetException) {
Throwable realCause = e.getCause().getCause();
throw fieldInitialisationThrewException(field, realCause);
}
- throw cannotInitializeForInjectMocksAnnotation(field.getName(),e.getMessage());
+ throw cannotInitializeForInjectMocksAnnotation(field.getName(), e.getMessage());
}
}
-
- private boolean injectMockCandidates(Class> awaitingInjectionClazz, Object injectee, Set mocks) {
+ private boolean injectMockCandidates(
+ Class> awaitingInjectionClazz, Object injectee, Set mocks) {
boolean injectionOccurred;
- List orderedCandidateInjecteeFields = orderedInstanceFieldsFrom(awaitingInjectionClazz);
+ List orderedCandidateInjecteeFields =
+ orderedInstanceFieldsFrom(awaitingInjectionClazz);
// pass 1
- injectionOccurred = injectMockCandidatesOnFields(mocks, injectee, false, orderedCandidateInjecteeFields);
+ injectionOccurred =
+ injectMockCandidatesOnFields(
+ mocks, injectee, false, orderedCandidateInjecteeFields);
// pass 2
- injectionOccurred |= injectMockCandidatesOnFields(mocks, injectee, injectionOccurred, orderedCandidateInjecteeFields);
+ injectionOccurred |=
+ injectMockCandidatesOnFields(
+ mocks, injectee, injectionOccurred, orderedCandidateInjecteeFields);
return injectionOccurred;
}
- private boolean injectMockCandidatesOnFields(Set mocks,
- Object injectee,
- boolean injectionOccurred,
- List orderedCandidateInjecteeFields) {
+ private boolean injectMockCandidatesOnFields(
+ Set mocks,
+ Object injectee,
+ boolean injectionOccurred,
+ List orderedCandidateInjecteeFields) {
for (Iterator it = orderedCandidateInjecteeFields.iterator(); it.hasNext(); ) {
Field candidateField = it.next();
- Object injected = mockCandidateFilter.filterCandidate(mocks, candidateField, orderedCandidateInjecteeFields, injectee)
- .thenInject();
+ Object injected =
+ mockCandidateFilter
+ .filterCandidate(
+ mocks, candidateField, orderedCandidateInjecteeFields, injectee)
+ .thenInject();
if (injected != null) {
injectionOccurred |= true;
mocks.remove(injected);
diff --git a/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java b/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java
index d44080a341..34b8682a5c 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java
@@ -31,7 +31,7 @@ protected boolean processInjection(Field field, Object fieldOwner, Set m
FieldReader fieldReader = new FieldReader(fieldOwner, field);
// TODO refoctor : code duplicated in SpyAnnotationEngine
- if(!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) {
+ if (!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) {
try {
Object instance = fieldReader.read();
if (MockUtil.isMock(instance)) {
@@ -39,10 +39,13 @@ protected boolean processInjection(Field field, Object fieldOwner, Set m
// B. protect against multiple use of MockitoAnnotations.initMocks()
Mockito.reset(instance);
} else {
- Object mock = Mockito.mock(instance.getClass(), withSettings()
- .spiedInstance(instance)
- .defaultAnswer(Mockito.CALLS_REAL_METHODS)
- .name(field.getName()));
+ Object mock =
+ Mockito.mock(
+ instance.getClass(),
+ withSettings()
+ .spiedInstance(instance)
+ .defaultAnswer(Mockito.CALLS_REAL_METHODS)
+ .name(field.getName()));
setField(fieldOwner, field, mock);
}
} catch (Exception e) {
diff --git a/src/main/java/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java b/src/main/java/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
index 454d3be981..470a42ff17 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
@@ -13,6 +13,5 @@ OngoingInjector filterCandidate(
Collection mocks,
Field candidateFieldToBeInjected,
List allRemainingCandidateFields,
- Object injectee
- );
+ Object injectee);
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java b/src/main/java/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
index dc50e9d8b5..1690440459 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
@@ -18,26 +18,30 @@ public NameBasedCandidateFilter(MockCandidateFilter next) {
this.next = next;
}
- public OngoingInjector filterCandidate(final Collection mocks,
- final Field candidateFieldToBeInjected,
- final List allRemainingCandidateFields,
- final Object injectee) {
+ public OngoingInjector filterCandidate(
+ final Collection mocks,
+ final Field candidateFieldToBeInjected,
+ final List allRemainingCandidateFields,
+ final Object injectee) {
if (mocks.size() == 1
- && anotherCandidateMatchesMockName(mocks, candidateFieldToBeInjected, allRemainingCandidateFields)) {
+ && anotherCandidateMatchesMockName(
+ mocks, candidateFieldToBeInjected, allRemainingCandidateFields)) {
return OngoingInjector.nop;
}
- return next.filterCandidate(tooMany(mocks) ? selectMatchingName(mocks, candidateFieldToBeInjected) : mocks,
- candidateFieldToBeInjected,
- allRemainingCandidateFields,
- injectee);
+ return next.filterCandidate(
+ tooMany(mocks) ? selectMatchingName(mocks, candidateFieldToBeInjected) : mocks,
+ candidateFieldToBeInjected,
+ allRemainingCandidateFields,
+ injectee);
}
private boolean tooMany(Collection mocks) {
return mocks.size() > 1;
}
- private List selectMatchingName(Collection mocks, Field candidateFieldToBeInjected) {
+ private List selectMatchingName(
+ Collection mocks, Field candidateFieldToBeInjected) {
List mockNameMatches = new ArrayList();
for (Object mock : mocks) {
if (candidateFieldToBeInjected.getName().equals(getMockName(mock).toString())) {
@@ -56,9 +60,10 @@ private List selectMatchingName(Collection mocks, Field candidat
* whenever we find a field that does match its name with the mock
* name, we should take that field instead.
*/
- private boolean anotherCandidateMatchesMockName(final Collection mocks,
- final Field candidateFieldToBeInjected,
- final List allRemainingCandidateFields) {
+ private boolean anotherCandidateMatchesMockName(
+ final Collection mocks,
+ final Field candidateFieldToBeInjected,
+ final List allRemainingCandidateFields) {
String mockName = getMockName(mocks.iterator().next()).toString();
for (Field otherCandidateField : allRemainingCandidateFields) {
diff --git a/src/main/java/org/mockito/internal/configuration/injection/filter/OngoingInjector.java b/src/main/java/org/mockito/internal/configuration/injection/filter/OngoingInjector.java
index 4550e1f558..2a56985c79 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/filter/OngoingInjector.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/filter/OngoingInjector.java
@@ -23,9 +23,10 @@ public interface OngoingInjector {
/**
* Injector that will do nothing, and will return null
as no mocks will be injected
*/
- OngoingInjector nop = new OngoingInjector() {
- public Object thenInject() {
- return null;
- }
- };
+ OngoingInjector nop =
+ new OngoingInjector() {
+ public Object thenInject() {
+ return null;
+ }
+ };
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java b/src/main/java/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java
index 4644e218aa..a682d92320 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java
@@ -22,18 +22,20 @@
*
*/
public class TerminalMockCandidateFilter implements MockCandidateFilter {
- public OngoingInjector filterCandidate(final Collection mocks,
- final Field candidateFieldToBeInjected,
- final List allRemainingCandidateFields,
- final Object injectee) {
- if(mocks.size() == 1) {
+ public OngoingInjector filterCandidate(
+ final Collection mocks,
+ final Field candidateFieldToBeInjected,
+ final List allRemainingCandidateFields,
+ final Object injectee) {
+ if (mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
return new OngoingInjector() {
public Object thenInject() {
try {
- if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected).set(matchingMock)) {
- setField(injectee, candidateFieldToBeInjected,matchingMock);
+ if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected)
+ .set(matchingMock)) {
+ setField(injectee, candidateFieldToBeInjected, matchingMock);
}
} catch (RuntimeException e) {
throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e);
@@ -44,6 +46,5 @@ public Object thenInject() {
}
return OngoingInjector.nop;
-
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java b/src/main/java/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
index 7284399258..ad190d0039 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
@@ -17,10 +17,11 @@ public TypeBasedCandidateFilter(MockCandidateFilter next) {
this.next = next;
}
- public OngoingInjector filterCandidate(final Collection mocks,
- final Field candidateFieldToBeInjected,
- final List allRemainingCandidateFields,
- final Object injectee) {
+ public OngoingInjector filterCandidate(
+ final Collection mocks,
+ final Field candidateFieldToBeInjected,
+ final List allRemainingCandidateFields,
+ final Object injectee) {
List mockTypeMatches = new ArrayList();
for (Object mock : mocks) {
if (candidateFieldToBeInjected.getType().isAssignableFrom(mock.getClass())) {
@@ -28,6 +29,7 @@ public OngoingInjector filterCandidate(final Collection mocks,
}
}
- return next.filterCandidate(mockTypeMatches, candidateFieldToBeInjected, allRemainingCandidateFields, injectee);
+ return next.filterCandidate(
+ mockTypeMatches, candidateFieldToBeInjected, allRemainingCandidateFields, injectee);
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java b/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java
index 167196a528..c54f6071a3 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java
@@ -30,7 +30,6 @@ public InjectMocksScanner(Class> clazz) {
this.clazz = clazz;
}
-
/**
* Add the fields annotated by @{@link InjectMocks}
*
@@ -59,10 +58,12 @@ private Set scan() {
return mockDependentFields;
}
- private static void assertNoAnnotations(Field field, Class extends Annotation>... annotations) {
+ private static void assertNoAnnotations(
+ Field field, Class extends Annotation>... annotations) {
for (Class extends Annotation> annotation : annotations) {
if (field.isAnnotationPresent(annotation)) {
- throw unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName());
+ throw unsupportedCombinationOfAnnotations(
+ annotation.getSimpleName(), InjectMocks.class.getSimpleName());
}
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/injection/scanner/MockScanner.java b/src/main/java/org/mockito/internal/configuration/injection/scanner/MockScanner.java
index b7da87246b..97984444c7 100644
--- a/src/main/java/org/mockito/internal/configuration/injection/scanner/MockScanner.java
+++ b/src/main/java/org/mockito/internal/configuration/injection/scanner/MockScanner.java
@@ -80,7 +80,6 @@ private boolean isAnnotatedByMockOrSpy(Field field) {
}
private boolean isMockOrSpy(Object instance) {
- return MockUtil.isMock(instance)
- || MockUtil.isSpy(instance);
+ return MockUtil.isMock(instance) || MockUtil.isSpy(instance);
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java b/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java
index e05fc245b7..46bf3a7c0e 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java
@@ -19,27 +19,40 @@
class DefaultMockitoPlugins implements MockitoPlugins {
- private final static Map DEFAULT_PLUGINS = new HashMap();
+ private static final Map DEFAULT_PLUGINS = new HashMap();
static final String INLINE_ALIAS = "mock-maker-inline";
static {
- //Keep the mapping: plugin interface name -> plugin implementation class name
+ // Keep the mapping: plugin interface name -> plugin implementation class name
DEFAULT_PLUGINS.put(PluginSwitch.class.getName(), DefaultPluginSwitch.class.getName());
- DEFAULT_PLUGINS.put(MockMaker.class.getName(), "org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker");
- DEFAULT_PLUGINS.put(StackTraceCleanerProvider.class.getName(), "org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider");
- DEFAULT_PLUGINS.put(InstantiatorProvider2.class.getName(), "org.mockito.internal.creation.instance.DefaultInstantiatorProvider");
- DEFAULT_PLUGINS.put(AnnotationEngine.class.getName(), "org.mockito.internal.configuration.InjectingAnnotationEngine");
- DEFAULT_PLUGINS.put(INLINE_ALIAS, "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker");
- DEFAULT_PLUGINS.put(MockitoLogger.class.getName(), "org.mockito.internal.util.ConsoleMockitoLogger");
+ DEFAULT_PLUGINS.put(
+ MockMaker.class.getName(),
+ "org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker");
+ DEFAULT_PLUGINS.put(
+ StackTraceCleanerProvider.class.getName(),
+ "org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider");
+ DEFAULT_PLUGINS.put(
+ InstantiatorProvider2.class.getName(),
+ "org.mockito.internal.creation.instance.DefaultInstantiatorProvider");
+ DEFAULT_PLUGINS.put(
+ AnnotationEngine.class.getName(),
+ "org.mockito.internal.configuration.InjectingAnnotationEngine");
+ DEFAULT_PLUGINS.put(
+ INLINE_ALIAS, "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker");
+ DEFAULT_PLUGINS.put(
+ MockitoLogger.class.getName(), "org.mockito.internal.util.ConsoleMockitoLogger");
}
@Override
public T getDefaultPlugin(Class pluginType) {
if (pluginType == InstantiatorProvider.class) {
- //the implementation class is not configured via map so that we can reduce duplication
- //(ensure that we are adapting the currently configured default implementation for InstantiatorProvider2)
+ // the implementation class is not configured via map so that we can reduce duplication
+ // (ensure that we are adapting the currently configured default implementation for
+ // InstantiatorProvider2)
String className = DEFAULT_PLUGINS.get(InstantiatorProvider2.class.getName());
- return pluginType.cast(new InstantiatorProvider2Adapter(create(InstantiatorProvider2.class, className)));
+ return pluginType.cast(
+ new InstantiatorProvider2Adapter(
+ create(InstantiatorProvider2.class, className)));
} else {
String className = DEFAULT_PLUGINS.get(pluginType.getName());
return create(pluginType, className);
@@ -56,10 +69,12 @@ String getDefaultPluginClass(String classOrAlias) {
private T create(Class pluginType, String className) {
if (className == null) {
throw new IllegalStateException(
- "No default implementation for requested Mockito plugin type: " + pluginType.getName() + "\n"
- + "Is this a valid Mockito plugin type? If yes, please report this problem to Mockito team.\n"
- + "Otherwise, please check if you are passing valid plugin type.\n"
- + "Examples of valid plugin types: MockMaker, StackTraceCleanerProvider.");
+ "No default implementation for requested Mockito plugin type: "
+ + pluginType.getName()
+ + "\n"
+ + "Is this a valid Mockito plugin type? If yes, please report this problem to Mockito team.\n"
+ + "Otherwise, please check if you are passing valid plugin type.\n"
+ + "Examples of valid plugin types: MockMaker, StackTraceCleanerProvider.");
}
try {
// Default implementation. Use our own ClassLoader instead of the context
@@ -67,9 +82,12 @@ private T create(Class pluginType, String className) {
// Mockito and may not be available via the context ClassLoader.
return pluginType.cast(Class.forName(className).newInstance());
} catch (Exception e) {
- throw new IllegalStateException("Internal problem occurred, please report it. " +
- "Mockito is unable to load the default implementation of class that is a part of Mockito distribution. " +
- "Failed to load " + pluginType, e);
+ throw new IllegalStateException(
+ "Internal problem occurred, please report it. "
+ + "Mockito is unable to load the default implementation of class that is a part of Mockito distribution. "
+ + "Failed to load "
+ + pluginType,
+ e);
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/PluginFileReader.java b/src/main/java/org/mockito/internal/configuration/plugins/PluginFileReader.java
index 1dc63cabbd..c1e2cbbbe8 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/PluginFileReader.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginFileReader.java
@@ -11,7 +11,7 @@
class PluginFileReader {
String readPluginClass(InputStream input) {
- for(String line: IOUtil.readLines(input)) {
+ for (String line : IOUtil.readLines(input)) {
String stripped = stripCommentAndWhitespace(line);
if (stripped.length() > 0) {
return stripped;
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java b/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java
index 71528c2a08..7385afb184 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java
@@ -26,16 +26,17 @@ String findPluginClass(Iterable resources) {
s = resource.openStream();
String pluginClassName = new PluginFileReader().readPluginClass(s);
if (pluginClassName == null) {
- //For backwards compatibility
- //If the resource does not have plugin class name we're ignoring it
+ // For backwards compatibility
+ // If the resource does not have plugin class name we're ignoring it
continue;
}
if (!pluginSwitch.isEnabled(pluginClassName)) {
continue;
}
return pluginClassName;
- } catch(Exception e) {
- throw new MockitoException("Problems reading plugin implementation from: " + resource, e);
+ } catch (Exception e) {
+ throw new MockitoException(
+ "Problems reading plugin implementation from: " + resource, e);
} finally {
IOUtil.closeQuietly(s);
}
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java b/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java
index 355ffa8a5b..d58ca2cdf3 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java
@@ -40,7 +40,8 @@ public T loadImpl(Class service) {
}
try {
- String classOrAlias = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources));
+ String classOrAlias =
+ new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources));
if (classOrAlias != null) {
if (classOrAlias.equals(alias)) {
classOrAlias = plugins.getDefaultPluginClass(alias);
@@ -52,7 +53,7 @@ public T loadImpl(Class service) {
return null;
} catch (Exception e) {
throw new IllegalStateException(
- "Failed to load " + service + " implementation declared in " + resources, e);
+ "Failed to load " + service + " implementation declared in " + resources, e);
}
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/PluginLoader.java b/src/main/java/org/mockito/internal/configuration/plugins/PluginLoader.java
index 464c7a6cb0..3d724aa49a 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/PluginLoader.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginLoader.java
@@ -21,7 +21,9 @@ class PluginLoader {
}
PluginLoader(PluginSwitch pluginSwitch) {
- this(new DefaultMockitoPlugins(), new PluginInitializer(pluginSwitch, null, new DefaultMockitoPlugins()));
+ this(
+ new DefaultMockitoPlugins(),
+ new PluginInitializer(pluginSwitch, null, new DefaultMockitoPlugins()));
}
/**
@@ -33,7 +35,9 @@ class PluginLoader {
*/
@Deprecated
PluginLoader(PluginSwitch pluginSwitch, String alias) {
- this(new DefaultMockitoPlugins(), new PluginInitializer(pluginSwitch, alias, new DefaultMockitoPlugins()));
+ this(
+ new DefaultMockitoPlugins(),
+ new PluginInitializer(pluginSwitch, alias, new DefaultMockitoPlugins()));
}
/**
@@ -52,7 +56,9 @@ T loadPlugin(final Class pluginType) {
* @return An object of either {@code preferredPluginType} or {@code alternatePluginType}
*/
@SuppressWarnings("unchecked")
- Object loadPlugin(final Class preferredPluginType, final Class alternatePluginType) {
+ Object loadPlugin(
+ final Class preferredPluginType,
+ final Class alternatePluginType) {
try {
PreferredType preferredPlugin = initializer.loadImpl(preferredPluginType);
if (preferredPlugin != null) {
@@ -66,14 +72,22 @@ Object loadPlugin(final Class pref
return plugins.getDefaultPlugin(preferredPluginType);
} catch (final Throwable t) {
- return Proxy.newProxyInstance(preferredPluginType.getClassLoader(),
- new Class>[]{preferredPluginType},
- new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- throw new IllegalStateException("Could not initialize plugin: " + preferredPluginType + " (alternate: " + alternatePluginType + ")", t);
- }
- });
+ return Proxy.newProxyInstance(
+ preferredPluginType.getClassLoader(),
+ new Class>[] {preferredPluginType},
+ new InvocationHandler() {
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ throw new IllegalStateException(
+ "Could not initialize plugin: "
+ + preferredPluginType
+ + " (alternate: "
+ + alternatePluginType
+ + ")",
+ t);
+ }
+ });
}
}
}
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java b/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java
index 2e5f069e62..0419001285 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java
@@ -15,25 +15,28 @@
class PluginRegistry {
- private final PluginSwitch pluginSwitch = new PluginLoader(new DefaultPluginSwitch())
- .loadPlugin(PluginSwitch.class);
+ private final PluginSwitch pluginSwitch =
+ new PluginLoader(new DefaultPluginSwitch()).loadPlugin(PluginSwitch.class);
- private final MockMaker mockMaker = new PluginLoader(pluginSwitch, DefaultMockitoPlugins.INLINE_ALIAS)
- .loadPlugin(MockMaker.class);
+ private final MockMaker mockMaker =
+ new PluginLoader(pluginSwitch, DefaultMockitoPlugins.INLINE_ALIAS)
+ .loadPlugin(MockMaker.class);
- private final StackTraceCleanerProvider stackTraceCleanerProvider = new PluginLoader(pluginSwitch)
- .loadPlugin(StackTraceCleanerProvider.class);
+ private final StackTraceCleanerProvider stackTraceCleanerProvider =
+ new PluginLoader(pluginSwitch).loadPlugin(StackTraceCleanerProvider.class);
private final InstantiatorProvider2 instantiatorProvider;
- private final AnnotationEngine annotationEngine = new PluginLoader(pluginSwitch)
- .loadPlugin(AnnotationEngine.class);
+ private final AnnotationEngine annotationEngine =
+ new PluginLoader(pluginSwitch).loadPlugin(AnnotationEngine.class);
- private final MockitoLogger mockitoLogger = new PluginLoader(pluginSwitch)
- .loadPlugin(MockitoLogger.class);
+ private final MockitoLogger mockitoLogger =
+ new PluginLoader(pluginSwitch).loadPlugin(MockitoLogger.class);
PluginRegistry() {
- Object impl = new PluginLoader(pluginSwitch).loadPlugin(InstantiatorProvider2.class, InstantiatorProvider.class);
+ Object impl =
+ new PluginLoader(pluginSwitch)
+ .loadPlugin(InstantiatorProvider2.class, InstantiatorProvider.class);
if (impl instanceof InstantiatorProvider) {
instantiatorProvider = new InstantiatorProviderAdapter((InstantiatorProvider) impl);
} else {
@@ -45,7 +48,7 @@ class PluginRegistry {
* The implementation of the stack trace cleaner
*/
StackTraceCleanerProvider getStackTraceCleanerProvider() {
- //TODO we should throw some sensible exception if this is null.
+ // TODO we should throw some sensible exception if this is null.
return stackTraceCleanerProvider;
}
diff --git a/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java b/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java
index 0cdc54f78d..8469981202 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java
@@ -43,7 +43,7 @@ public static MockMaker getMockMaker() {
* current classpath.
*/
public static InstantiatorProvider2 getInstantiatorProvider() {
- return registry.getInstantiatorProvider();
+ return registry.getInstantiatorProvider();
}
/**
diff --git a/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java b/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java
index c73fe794cc..dee7f45c06 100644
--- a/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java
+++ b/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java
@@ -35,7 +35,8 @@
import org.mockito.stubbing.Answer;
@SuppressWarnings("unchecked")
-public class MockSettingsImpl extends CreationSettings implements MockSettings, MockCreationSettings {
+public class MockSettingsImpl extends CreationSettings
+ implements MockSettings, MockCreationSettings {
private static final long serialVersionUID = 4475297236197939569L;
private boolean useConstructor;
@@ -119,9 +120,10 @@ public MockSettingsImpl stubOnly() {
@Override
public MockSettings useConstructor(Object... constructorArgs) {
- Checks.checkNotNull(constructorArgs,
- "constructorArgs",
- "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)");
+ Checks.checkNotNull(
+ constructorArgs,
+ "constructorArgs",
+ "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)");
this.useConstructor = true;
this.constructorArgs = constructorArgs;
return this;
@@ -235,20 +237,22 @@ public MockSettings lenient() {
return this;
}
- private static CreationSettings validatedSettings(Class typeToMock, CreationSettings source) {
+ private static CreationSettings validatedSettings(
+ Class typeToMock, CreationSettings source) {
MockCreationValidator validator = new MockCreationValidator();
validator.validateType(typeToMock);
validator.validateExtraInterfaces(typeToMock, source.getExtraInterfaces());
validator.validateMockedType(typeToMock, source.getSpiedInstance());
- //TODO SF - add this validation and also add missing coverage
-// validator.validateDelegatedInstance(classToMock, settings.getDelegatedInstance());
+ // TODO SF - add this validation and also add missing coverage
+ // validator.validateDelegatedInstance(classToMock, settings.getDelegatedInstance());
validator.validateConstructorUse(source.isUsingConstructor(), source.getSerializableMode());
- //TODO SF - I don't think we really need CreationSettings type
- //TODO do we really need to copy the entire settings every time we create mock object? it does not seem necessary.
+ // TODO SF - I don't think we really need CreationSettings type
+ // TODO do we really need to copy the entire settings every time we create mock object? it
+ // does not seem necessary.
CreationSettings settings = new CreationSettings(source);
settings.setMockName(new MockNameImpl(source.getName(), typeToMock));
settings.setTypeToMock(typeToMock);
@@ -258,10 +262,9 @@ private static CreationSettings validatedSettings(Class typeToMock, Cr
private static Set> prepareExtraInterfaces(CreationSettings settings) {
Set> interfaces = new HashSet>(settings.getExtraInterfaces());
- if(settings.isSerializable()) {
+ if (settings.isSerializable()) {
interfaces.add(Serializable.class);
}
return interfaces;
}
-
}
diff --git a/src/main/java/org/mockito/internal/creation/SuspendMethod.java b/src/main/java/org/mockito/internal/creation/SuspendMethod.java
index 42ceac66ee..87b596a206 100644
--- a/src/main/java/org/mockito/internal/creation/SuspendMethod.java
+++ b/src/main/java/org/mockito/internal/creation/SuspendMethod.java
@@ -11,7 +11,8 @@
* See Design docs for details .
*/
public class SuspendMethod {
- private static final String KOTLIN_EXPERIMENTAL_CONTINUATION = "kotlin.coroutines.experimental.Continuation";
+ private static final String KOTLIN_EXPERIMENTAL_CONTINUATION =
+ "kotlin.coroutines.experimental.Continuation";
private static final String KOTLIN_CONTINUATION = "kotlin.coroutines.Continuation";
public static Class>[] trimSuspendParameterTypes(Class>[] parameterTypes) {
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java
index 789072832f..4bb4405e73 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java
@@ -114,12 +114,16 @@ public Object writeReplace(Object mockitoMock) throws ObjectStreamException {
return new CrossClassLoaderSerializationProxy(mockitoMock);
} catch (IOException ioe) {
MockName mockName = MockUtil.getMockName(mockitoMock);
- String mockedType = MockUtil.getMockSettings(mockitoMock).getTypeToMock().getCanonicalName();
- throw new MockitoSerializationIssue(join(
- "The mock '" + mockName + "' of type '" + mockedType + "'",
- "The Java Standard Serialization reported an '" + ioe.getClass().getSimpleName() + "' saying :",
- " " + ioe.getMessage()
- ), ioe);
+ String mockedType =
+ MockUtil.getMockSettings(mockitoMock).getTypeToMock().getCanonicalName();
+ throw new MockitoSerializationIssue(
+ join(
+ "The mock '" + mockName + "' of type '" + mockedType + "'",
+ "The Java Standard Serialization reported an '"
+ + ioe.getClass().getSimpleName()
+ + "' saying :",
+ " " + ioe.getMessage()),
+ ioe);
} finally {
// unmark
mockReplacementCompleted();
@@ -127,17 +131,14 @@ public Object writeReplace(Object mockitoMock) throws ObjectStreamException {
}
}
-
private void mockReplacementCompleted() {
instanceLocalCurrentlySerializingFlag = false;
}
-
private void mockReplacementStarted() {
instanceLocalCurrentlySerializingFlag = true;
}
-
private boolean mockIsCurrentlyBeingReplaced() {
return instanceLocalCurrentlySerializingFlag;
}
@@ -195,7 +196,8 @@ public CrossClassLoaderSerializationProxy(Object mockitoMock) throws IOException
private Object readResolve() throws ObjectStreamException {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(serializedMock);
- ObjectInputStream objectInputStream = new MockitoMockObjectInputStream(bis, typeToMock, extraInterfaces);
+ ObjectInputStream objectInputStream =
+ new MockitoMockObjectInputStream(bis, typeToMock, extraInterfaces);
Object deserializedMock = objectInputStream.readObject();
@@ -204,22 +206,25 @@ private Object readResolve() throws ObjectStreamException {
return deserializedMock;
} catch (IOException ioe) {
- throw new MockitoSerializationIssue(join(
- "Mockito mock cannot be deserialized to a mock of '" + typeToMock.getCanonicalName() + "'. The error was :",
- " " + ioe.getMessage(),
- "If you are unsure what is the reason of this exception, feel free to contact us on the mailing list."
- ), ioe);
+ throw new MockitoSerializationIssue(
+ join(
+ "Mockito mock cannot be deserialized to a mock of '"
+ + typeToMock.getCanonicalName()
+ + "'. The error was :",
+ " " + ioe.getMessage(),
+ "If you are unsure what is the reason of this exception, feel free to contact us on the mailing list."),
+ ioe);
} catch (ClassNotFoundException cce) {
- throw new MockitoSerializationIssue(join(
- "A class couldn't be found while deserializing a Mockito mock, you should check your classpath. The error was :",
- " " + cce.getMessage(),
- "If you are still unsure what is the reason of this exception, feel free to contact us on the mailing list."
- ), cce);
+ throw new MockitoSerializationIssue(
+ join(
+ "A class couldn't be found while deserializing a Mockito mock, you should check your classpath. The error was :",
+ " " + cce.getMessage(),
+ "If you are still unsure what is the reason of this exception, feel free to contact us on the mailing list."),
+ cce);
}
}
}
-
/**
* Special Mockito aware ObjectInputStream
that will resolve the Mockito proxy class.
*
@@ -240,7 +245,9 @@ public static class MockitoMockObjectInputStream extends ObjectInputStream {
private final Class> typeToMock;
private final Set> extraInterfaces;
- public MockitoMockObjectInputStream(InputStream in, Class> typeToMock, Set> extraInterfaces) throws IOException {
+ public MockitoMockObjectInputStream(
+ InputStream in, Class> typeToMock, Set> extraInterfaces)
+ throws IOException {
super(in);
this.typeToMock = typeToMock;
this.extraInterfaces = extraInterfaces;
@@ -260,7 +267,8 @@ public MockitoMockObjectInputStream(InputStream in, Class> typeToMock, Set resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
+ protected Class> resolveClass(ObjectStreamClass desc)
+ throws IOException, ClassNotFoundException {
if (notMarkedAsAMockitoMock(readObject())) {
return super.resolveClass(desc);
}
@@ -268,20 +276,24 @@ protected Class> resolveClass(ObjectStreamClass desc) throws IOException, Clas
// create the Mockito mock class before it can even be deserialized
try {
@SuppressWarnings("unchecked")
- Class> proxyClass = ((ClassCreatingMockMaker) Plugins.getMockMaker()).createMockType(
- new CreationSettings()
- .setTypeToMock(typeToMock)
- .setExtraInterfaces(extraInterfaces)
- .setSerializableMode(SerializableMode.ACROSS_CLASSLOADERS));
+ Class> proxyClass =
+ ((ClassCreatingMockMaker) Plugins.getMockMaker())
+ .createMockType(
+ new CreationSettings()
+ .setTypeToMock(typeToMock)
+ .setExtraInterfaces(extraInterfaces)
+ .setSerializableMode(
+ SerializableMode.ACROSS_CLASSLOADERS));
hackClassNameToMatchNewlyCreatedClass(desc, proxyClass);
return proxyClass;
} catch (ClassCastException cce) {
- throw new MockitoSerializationIssue(join(
- "A Byte Buddy-generated mock cannot be deserialized into a non-Byte Buddy generated mock class",
- "",
- "The mock maker in use was: " + Plugins.getMockMaker().getClass()
- ), cce);
+ throw new MockitoSerializationIssue(
+ join(
+ "A Byte Buddy-generated mock cannot be deserialized into a non-Byte Buddy generated mock class",
+ "",
+ "The mock maker in use was: " + Plugins.getMockMaker().getClass()),
+ cce);
}
}
@@ -303,17 +315,19 @@ protected Class> resolveClass(ObjectStreamClass desc) throws IOException, Clas
* @param proxyClass The proxy class whose name will be applied.
* @throws java.io.InvalidObjectException
*/
- private void hackClassNameToMatchNewlyCreatedClass(ObjectStreamClass descInstance, Class> proxyClass) throws ObjectStreamException {
+ private void hackClassNameToMatchNewlyCreatedClass(
+ ObjectStreamClass descInstance, Class> proxyClass) throws ObjectStreamException {
try {
Field classNameField = descInstance.getClass().getDeclaredField("name");
- setField(descInstance, classNameField,proxyClass.getCanonicalName());
+ setField(descInstance, classNameField, proxyClass.getCanonicalName());
} catch (NoSuchFieldException nsfe) {
- throw new MockitoSerializationIssue(join(
- "Wow, the class 'ObjectStreamClass' in the JDK don't have the field 'name',",
- "this is definitely a bug in our code as it means the JDK team changed a few internal things.",
- "",
- "Please report an issue with the JDK used, a code sample and a link to download the JDK would be welcome."
- ), nsfe);
+ throw new MockitoSerializationIssue(
+ join(
+ "Wow, the class 'ObjectStreamClass' in the JDK don't have the field 'name',",
+ "this is definitely a bug in our code as it means the JDK team changed a few internal things.",
+ "",
+ "Please report an issue with the JDK used, a code sample and a link to download the JDK would be welcome."),
+ nsfe);
}
}
@@ -328,7 +342,6 @@ private boolean notMarkedAsAMockitoMock(Object marker) {
}
}
-
/**
* Special Mockito aware ObjectOutputStream
.
*
@@ -374,7 +387,6 @@ private String mockitoProxyClassMarker(Class> cl) {
}
}
-
/**
* Simple interface that hold a correct writeReplace
signature that can be seen by an
* ObjectOutputStream
.
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
index cd46ac0ae6..d110451e3d 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
@@ -103,23 +103,31 @@ public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineM
try {
instrumentation = ByteBuddyAgent.install();
if (!instrumentation.isRetransformClassesSupported()) {
- throw new IllegalStateException(join(
- "Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.",
- "",
- "You cannot use this mock maker on this VM"));
+ throw new IllegalStateException(
+ join(
+ "Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.",
+ "",
+ "You cannot use this mock maker on this VM"));
}
File boot = File.createTempFile("mockitoboot", ".jar");
boot.deleteOnExit();
JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(boot));
try {
- String source = "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher";
- InputStream inputStream = InlineByteBuddyMockMaker.class.getClassLoader().getResourceAsStream(source + ".raw");
+ String source =
+ "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher";
+ InputStream inputStream =
+ InlineByteBuddyMockMaker.class
+ .getClassLoader()
+ .getResourceAsStream(source + ".raw");
if (inputStream == null) {
- throw new IllegalStateException(join(
- "The MockMethodDispatcher class file is not locatable: " + source + ".raw",
- "",
- "The class loader responsible for looking up the resource: " + InlineByteBuddyMockMaker.class.getClassLoader()
- ));
+ throw new IllegalStateException(
+ join(
+ "The MockMethodDispatcher class file is not locatable: "
+ + source
+ + ".raw",
+ "",
+ "The class loader responsible for looking up the resource: "
+ + InlineByteBuddyMockMaker.class.getClassLoader()));
}
outputStream.putNextEntry(new JarEntry(source + ".class"));
try {
@@ -139,19 +147,27 @@ public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineM
instrumentation.appendToBootstrapClassLoaderSearch(jarfile);
}
try {
- Class.forName("org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher", false, null);
+ Class.forName(
+ "org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher",
+ false,
+ null);
} catch (ClassNotFoundException cnfe) {
- throw new IllegalStateException(join(
- "Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader",
- "",
- "It seems like your current VM does not support the instrumentation API correctly."), cnfe);
+ throw new IllegalStateException(
+ join(
+ "Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader",
+ "",
+ "It seems like your current VM does not support the instrumentation API correctly."),
+ cnfe);
}
} catch (IOException ioe) {
- throw new IllegalStateException(join(
- "Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.",
- "This error occured due to an I/O error during the creation of this agent: " + ioe,
- "",
- "Potentially, the current VM does not support the instrumentation API correctly"), ioe);
+ throw new IllegalStateException(
+ join(
+ "Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.",
+ "This error occured due to an I/O error during the creation of this agent: "
+ + ioe,
+ "",
+ "Potentially, the current VM does not support the instrumentation API correctly"),
+ ioe);
}
} catch (Throwable throwable) {
instrumentation = null;
@@ -163,16 +179,23 @@ public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineM
private final BytecodeGenerator bytecodeGenerator;
- private final WeakConcurrentMap mocks = new WeakConcurrentMap.WithInlinedExpunction();
+ private final WeakConcurrentMap mocks =
+ new WeakConcurrentMap.WithInlinedExpunction();
public InlineByteBuddyMockMaker() {
if (INITIALIZATION_ERROR != null) {
- throw new MockitoInitializationException(join(
- "Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)",
- ToolProvider.getSystemJavaCompiler() == null ? "Are you running a JRE instead of a JDK? The inline mock maker needs to be run on a JDK.\n" : "",
- Platform.describe()), INITIALIZATION_ERROR);
+ throw new MockitoInitializationException(
+ join(
+ "Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)",
+ ToolProvider.getSystemJavaCompiler() == null
+ ? "Are you running a JRE instead of a JDK? The inline mock maker needs to be run on a JDK.\n"
+ : "",
+ Platform.describe()),
+ INITIALIZATION_ERROR);
}
- bytecodeGenerator = new TypeCachingBytecodeGenerator(new InlineBytecodeGenerator(INSTRUMENTATION, mocks), true);
+ bytecodeGenerator =
+ new TypeCachingBytecodeGenerator(
+ new InlineBytecodeGenerator(INSTRUMENTATION, mocks), true);
}
@Override
@@ -182,77 +205,85 @@ public T createMock(MockCreationSettings settings, MockHandler handler) {
Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(settings);
try {
T instance = instantiator.newInstance(type);
- MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(handler, settings);
+ MockMethodInterceptor mockMethodInterceptor =
+ new MockMethodInterceptor(handler, settings);
mocks.put(instance, mockMethodInterceptor);
if (instance instanceof MockAccess) {
((MockAccess) instance).setMockitoInterceptor(mockMethodInterceptor);
}
return instance;
} catch (org.mockito.creation.instance.InstantiationException e) {
- throw new MockitoException("Unable to create mock instance of type '" + type.getSimpleName() + "'", e);
+ throw new MockitoException(
+ "Unable to create mock instance of type '" + type.getSimpleName() + "'", e);
}
}
@Override
public Class extends T> createMockType(MockCreationSettings settings) {
try {
- return bytecodeGenerator.mockClass(MockFeatures.withMockFeatures(
- settings.getTypeToMock(),
- settings.getExtraInterfaces(),
- settings.getSerializableMode(),
- settings.isStripAnnotations()
- ));
+ return bytecodeGenerator.mockClass(
+ MockFeatures.withMockFeatures(
+ settings.getTypeToMock(),
+ settings.getExtraInterfaces(),
+ settings.getSerializableMode(),
+ settings.isStripAnnotations()));
} catch (Exception bytecodeGenerationFailed) {
throw prettifyFailure(settings, bytecodeGenerationFailed);
}
}
- private RuntimeException prettifyFailure(MockCreationSettings mockFeatures, Exception generationFailed) {
+ private RuntimeException prettifyFailure(
+ MockCreationSettings mockFeatures, Exception generationFailed) {
if (mockFeatures.getTypeToMock().isArray()) {
- throw new MockitoException(join(
- "Arrays cannot be mocked: " + mockFeatures.getTypeToMock() + ".",
- ""
- ), generationFailed);
+ throw new MockitoException(
+ join("Arrays cannot be mocked: " + mockFeatures.getTypeToMock() + ".", ""),
+ generationFailed);
}
if (Modifier.isFinal(mockFeatures.getTypeToMock().getModifiers())) {
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
- "Can not mock final classes with the following settings :",
- " - explicit serialization (e.g. withSettings().serializable())",
- " - extra interfaces (e.g. withSettings().extraInterfaces(...))",
- "",
- "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",
- "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",
- "",
- "Underlying exception : " + generationFailed
- ), generationFailed);
+ throw new MockitoException(
+ join(
+ "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
+ "Can not mock final classes with the following settings :",
+ " - explicit serialization (e.g. withSettings().serializable())",
+ " - extra interfaces (e.g. withSettings().extraInterfaces(...))",
+ "",
+ "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",
+ "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",
+ "",
+ "Underlying exception : " + generationFailed),
+ generationFailed);
}
if (Modifier.isPrivate(mockFeatures.getTypeToMock().getModifiers())) {
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
- "Most likely it is a private class that is not visible by Mockito",
- "",
- "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",
- "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",
- ""
- ), generationFailed);
+ throw new MockitoException(
+ join(
+ "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
+ "Most likely it is a private class that is not visible by Mockito",
+ "",
+ "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",
+ "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",
+ ""),
+ generationFailed);
}
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
- "",
- "If you're not sure why you're getting this error, please report to the mailing list.",
- "",
- Platform.warnForVM(
- "IBM J9 VM", "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n",
- "Hotspot", Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : ""
- ),
- Platform.describe(),
- "",
- "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",
- "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",
- "",
- "Underlying exception : " + generationFailed
- ), generationFailed);
+ throw new MockitoException(
+ join(
+ "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
+ "",
+ "If you're not sure why you're getting this error, please report to the mailing list.",
+ "",
+ Platform.warnForVM(
+ "IBM J9 VM",
+ "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n",
+ "Hotspot",
+ Platform.isJava8BelowUpdate45()
+ ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n"
+ : ""),
+ Platform.describe(),
+ "",
+ "You are seeing this disclaimer because Mockito is configured to create inlined mocks.",
+ "You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.",
+ "",
+ "Underlying exception : " + generationFailed),
+ generationFailed);
}
@Override
@@ -267,7 +298,8 @@ public MockHandler getHandler(Object mock) {
@Override
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
- MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(newHandler, settings);
+ MockMethodInterceptor mockMethodInterceptor =
+ new MockMethodInterceptor(newHandler, settings);
mocks.put(mock, mockMethodInterceptor);
if (mock instanceof MockAccess) {
((MockAccess) mock).setMockitoInterceptor(mockMethodInterceptor);
@@ -307,5 +339,4 @@ public String nonMockableReason() {
}
};
}
-
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
index eaa61a3d71..dfca195b4d 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
@@ -47,16 +47,19 @@ public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTran
private static final String PRELOAD = "org.mockito.inline.preload";
@SuppressWarnings("unchecked")
- static final Set> EXCLUDES = new HashSet>(Arrays.asList(Class.class,
- Boolean.class,
- Byte.class,
- Short.class,
- Character.class,
- Integer.class,
- Long.class,
- Float.class,
- Double.class,
- String.class));
+ static final Set> EXCLUDES =
+ new HashSet>(
+ Arrays.asList(
+ Class.class,
+ Boolean.class,
+ Byte.class,
+ Short.class,
+ Character.class,
+ Integer.class,
+ Long.class,
+ Float.class,
+ Double.class,
+ String.class));
private final Instrumentation instrumentation;
private final ByteBuddy byteBuddy;
@@ -68,39 +71,68 @@ public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTran
private volatile Throwable lastException;
- public InlineBytecodeGenerator(Instrumentation instrumentation, WeakConcurrentMap mocks) {
+ public InlineBytecodeGenerator(
+ Instrumentation instrumentation,
+ WeakConcurrentMap mocks) {
preload();
this.instrumentation = instrumentation;
- byteBuddy = new ByteBuddy()
- .with(TypeValidation.DISABLED)
- .with(Implementation.Context.Disabled.Factory.INSTANCE)
- .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE);
+ byteBuddy =
+ new ByteBuddy()
+ .with(TypeValidation.DISABLED)
+ .with(Implementation.Context.Disabled.Factory.INSTANCE)
+ .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE);
mocked = new WeakConcurrentSet>(WeakConcurrentSet.Cleaner.INLINE);
String identifier = RandomString.make();
- subclassEngine = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(withDefaultConfiguration()
- .withBinders(of(MockMethodAdvice.Identifier.class, identifier))
- .to(MockMethodAdvice.ForReadObject.class), isAbstract().or(isNative()).or(isToString())), false);
- mockTransformer = new AsmVisitorWrapper.ForDeclaredMethods()
- .method(isVirtual()
- .and(not(isBridge().or(isHashCode()).or(isEquals()).or(isDefaultFinalizer())))
- .and(not(isDeclaredBy(nameStartsWith("java.")).and(isPackagePrivate()))),
- Advice.withCustomMapping()
- .bind(MockMethodAdvice.Identifier.class, identifier)
- .to(MockMethodAdvice.class))
- .method(isHashCode(),
- Advice.withCustomMapping()
- .bind(MockMethodAdvice.Identifier.class, identifier)
- .to(MockMethodAdvice.ForHashCode.class))
- .method(isEquals(),
- Advice.withCustomMapping()
- .bind(MockMethodAdvice.Identifier.class, identifier)
- .to(MockMethodAdvice.ForEquals.class));
+ subclassEngine =
+ new TypeCachingBytecodeGenerator(
+ new SubclassBytecodeGenerator(
+ withDefaultConfiguration()
+ .withBinders(
+ of(MockMethodAdvice.Identifier.class, identifier))
+ .to(MockMethodAdvice.ForReadObject.class),
+ isAbstract().or(isNative()).or(isToString())),
+ false);
+ mockTransformer =
+ new AsmVisitorWrapper.ForDeclaredMethods()
+ .method(
+ isVirtual()
+ .and(
+ not(
+ isBridge()
+ .or(isHashCode())
+ .or(isEquals())
+ .or(isDefaultFinalizer())))
+ .and(
+ not(
+ isDeclaredBy(nameStartsWith("java."))
+ .and(
+ isPackagePrivate()))),
+ Advice.withCustomMapping()
+ .bind(MockMethodAdvice.Identifier.class, identifier)
+ .to(MockMethodAdvice.class))
+ .method(
+ isHashCode(),
+ Advice.withCustomMapping()
+ .bind(MockMethodAdvice.Identifier.class, identifier)
+ .to(MockMethodAdvice.ForHashCode.class))
+ .method(
+ isEquals(),
+ Advice.withCustomMapping()
+ .bind(MockMethodAdvice.Identifier.class, identifier)
+ .to(MockMethodAdvice.ForEquals.class));
Method getModule, canRead, redefineModule;
try {
getModule = Class.class.getMethod("getModule");
canRead = getModule.getReturnType().getMethod("canRead", getModule.getReturnType());
- redefineModule = Instrumentation.class.getMethod("redefineModule",
- getModule.getReturnType(), Set.class, Map.class, Map.class, Set.class, Map.class);
+ redefineModule =
+ Instrumentation.class.getMethod(
+ "redefineModule",
+ getModule.getReturnType(),
+ Set.class,
+ Map.class,
+ Map.class,
+ Set.class,
+ Map.class);
} catch (Exception ignored) {
getModule = null;
canRead = null;
@@ -130,7 +162,8 @@ public InlineBytecodeGenerator(Instrumentation instrumentation, WeakConcurrentMa
private static void preload() {
String preloads = System.getProperty(PRELOAD);
if (preloads == null) {
- preloads = "java.lang.WeakPairMap,java.lang.WeakPairMap$Pair,java.lang.WeakPairMap$Pair$Weak";
+ preloads =
+ "java.lang.WeakPairMap,java.lang.WeakPairMap$Pair,java.lang.WeakPairMap$Pair$Weak";
}
for (String preload : preloads.split(",")) {
try {
@@ -142,9 +175,10 @@ private static void preload() {
@Override
public Class extends T> mockClass(MockFeatures features) {
- boolean subclassingRequired = !features.interfaces.isEmpty()
- || features.serializableMode != SerializableMode.NONE
- || Modifier.isAbstract(features.mockedType.getModifiers());
+ boolean subclassingRequired =
+ !features.interfaces.isEmpty()
+ || features.serializableMode != SerializableMode.NONE
+ || Modifier.isAbstract(features.mockedType.getModifiers());
checkSupportedCombination(subclassingRequired, features);
@@ -152,9 +186,7 @@ public Class extends T> mockClass(MockFeatures features) {
triggerRetransformation(features);
}
- return subclassingRequired ?
- subclassEngine.mockClass(features) :
- features.mockedType;
+ return subclassingRequired ? subclassEngine.mockClass(features) : features.mockedType;
}
private void triggerRetransformation(MockFeatures features) {
@@ -173,11 +205,14 @@ private void triggerRetransformation(MockFeatures features) {
instrumentation.retransformClasses(types.toArray(new Class>[types.size()]));
Throwable throwable = lastException;
if (throwable != null) {
- throw new IllegalStateException(join("Byte Buddy could not instrument all classes within the mock's type hierarchy",
- "",
- "This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:",
- " - Compiled by older versions of scalac",
- " - Classes that are part of the Android distribution"), throwable);
+ throw new IllegalStateException(
+ join(
+ "Byte Buddy could not instrument all classes within the mock's type hierarchy",
+ "",
+ "This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:",
+ " - Compiled by older versions of scalac",
+ " - Classes that are part of the Android distribution"),
+ throwable);
}
} catch (Exception exception) {
for (Class> failed : types) {
@@ -196,7 +231,12 @@ private void assureCanReadMockito(Set> types) {
}
Set modules = new HashSet();
try {
- Object target = getModule.invoke(Class.forName("org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher", false, null));
+ Object target =
+ getModule.invoke(
+ Class.forName(
+ "org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher",
+ false,
+ null));
for (Class> type : types) {
Object module = getModule.invoke(type);
if (!modules.contains(module) && !(Boolean) canRead.invoke(module, target)) {
@@ -204,24 +244,37 @@ private void assureCanReadMockito(Set> types) {
}
}
for (Object module : modules) {
- redefineModule.invoke(instrumentation, module, Collections.singleton(target),
- Collections.emptyMap(), Collections.emptyMap(), Collections.emptySet(), Collections.emptyMap());
+ redefineModule.invoke(
+ instrumentation,
+ module,
+ Collections.singleton(target),
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptySet(),
+ Collections.emptyMap());
}
} catch (Exception e) {
- throw new IllegalStateException(join("Could not adjust module graph to make the mock instance dispatcher visible to some classes",
- "",
- "At least one of those modules: " + modules + " is not reading the unnamed module of the bootstrap loader",
- "Without such a read edge, the classes that are redefined to become mocks cannot access the mock dispatcher.",
- "To circumvent this, Mockito attempted to add a read edge to this module what failed for an unexpected reason"), e);
+ throw new IllegalStateException(
+ join(
+ "Could not adjust module graph to make the mock instance dispatcher visible to some classes",
+ "",
+ "At least one of those modules: "
+ + modules
+ + " is not reading the unnamed module of the bootstrap loader",
+ "Without such a read edge, the classes that are redefined to become mocks cannot access the mock dispatcher.",
+ "To circumvent this, Mockito attempted to add a read edge to this module what failed for an unexpected reason"),
+ e);
}
}
- private void checkSupportedCombination(boolean subclassingRequired, MockFeatures features) {
+ private void checkSupportedCombination(
+ boolean subclassingRequired, MockFeatures features) {
if (subclassingRequired
&& !features.mockedType.isArray()
&& !features.mockedType.isPrimitive()
&& Modifier.isFinal(features.mockedType.getModifiers())) {
- throw new MockitoException("Unsupported settings with this type '" + features.mockedType.getName() + "'");
+ throw new MockitoException(
+ "Unsupported settings with this type '" + features.mockedType.getName() + "'");
}
}
@@ -235,23 +288,29 @@ private void addInterfaces(Set> types, Class>[] interfaces) {
}
@Override
- public byte[] transform(ClassLoader loader,
- String className,
- Class> classBeingRedefined,
- ProtectionDomain protectionDomain,
- byte[] classfileBuffer) {
+ public byte[] transform(
+ ClassLoader loader,
+ String className,
+ Class> classBeingRedefined,
+ ProtectionDomain protectionDomain,
+ byte[] classfileBuffer) {
if (classBeingRedefined == null
- || !mocked.contains(classBeingRedefined)
- || EXCLUDES.contains(classBeingRedefined)) {
+ || !mocked.contains(classBeingRedefined)
+ || EXCLUDES.contains(classBeingRedefined)) {
return null;
} else {
try {
- return byteBuddy.redefine(classBeingRedefined, ClassFileLocator.Simple.of(classBeingRedefined.getName(), classfileBuffer))
- // Note: The VM erases parameter meta data from the provided class file (bug). We just add this information manually.
- .visit(new ParameterWritingVisitorWrapper(classBeingRedefined))
- .visit(mockTransformer)
- .make()
- .getBytes();
+ return byteBuddy
+ .redefine(
+ classBeingRedefined,
+ ClassFileLocator.Simple.of(
+ classBeingRedefined.getName(), classfileBuffer))
+ // Note: The VM erases parameter meta data from the provided class file
+ // (bug). We just add this information manually.
+ .visit(new ParameterWritingVisitorWrapper(classBeingRedefined))
+ .visit(mockTransformer)
+ .make()
+ .getBytes();
} catch (Throwable throwable) {
lastException = throwable;
return null;
@@ -268,16 +327,18 @@ private ParameterWritingVisitorWrapper(Class> type) {
}
@Override
- public ClassVisitor wrap(TypeDescription instrumentedType,
- ClassVisitor classVisitor,
- Implementation.Context implementationContext,
- TypePool typePool,
- FieldList fields,
- MethodList> methods,
- int writerFlags,
- int readerFlags) {
+ public ClassVisitor wrap(
+ TypeDescription instrumentedType,
+ ClassVisitor classVisitor,
+ Implementation.Context implementationContext,
+ TypePool typePool,
+ FieldList fields,
+ MethodList> methods,
+ int writerFlags,
+ int readerFlags) {
return implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V8)
- ? new ParameterAddingClassVisitor(classVisitor, new TypeDescription.ForLoadedType(type))
+ ? new ParameterAddingClassVisitor(
+ classVisitor, new TypeDescription.ForLoadedType(type))
: classVisitor;
}
@@ -291,14 +352,26 @@ private ParameterAddingClassVisitor(ClassVisitor cv, TypeDescription typeDescrip
}
@Override
- public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
- MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);
- MethodList> methodList = typeDescription.getDeclaredMethods().filter((name.equals(MethodDescription.CONSTRUCTOR_INTERNAL_NAME)
- ? isConstructor()
- : ElementMatchers.named(name)).and(hasDescriptor(desc)));
- if (methodList.size() == 1 && methodList.getOnly().getParameters().hasExplicitMetaData()) {
- for (ParameterDescription parameterDescription : methodList.getOnly().getParameters()) {
- methodVisitor.visitParameter(parameterDescription.getName(), parameterDescription.getModifiers());
+ public MethodVisitor visitMethod(
+ int access, String name, String desc, String signature, String[] exceptions) {
+ MethodVisitor methodVisitor =
+ super.visitMethod(access, name, desc, signature, exceptions);
+ MethodList> methodList =
+ typeDescription
+ .getDeclaredMethods()
+ .filter(
+ (name.equals(MethodDescription.CONSTRUCTOR_INTERNAL_NAME)
+ ? isConstructor()
+ : ElementMatchers.named(
+ name))
+ .and(hasDescriptor(desc)));
+ if (methodList.size() == 1
+ && methodList.getOnly().getParameters().hasExplicitMetaData()) {
+ for (ParameterDescription parameterDescription :
+ methodList.getOnly().getParameters()) {
+ methodVisitor.visitParameter(
+ parameterDescription.getName(),
+ parameterDescription.getModifiers());
}
return new MethodParameterStrippingMethodVisitor(methodVisitor);
} else {
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/MockFeatures.java b/src/main/java/org/mockito/internal/creation/bytebuddy/MockFeatures.java
index 2f0ee4dc4f..1dbfba1334 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockFeatures.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockFeatures.java
@@ -16,17 +16,22 @@ class MockFeatures {
final SerializableMode serializableMode;
final boolean stripAnnotations;
- private MockFeatures(Class mockedType, Set> interfaces, SerializableMode serializableMode, boolean stripAnnotations) {
+ private MockFeatures(
+ Class mockedType,
+ Set> interfaces,
+ SerializableMode serializableMode,
+ boolean stripAnnotations) {
this.mockedType = mockedType;
this.interfaces = Collections.unmodifiableSet(interfaces);
this.serializableMode = serializableMode;
this.stripAnnotations = stripAnnotations;
}
- public static MockFeatures withMockFeatures(Class mockedType,
- Set> interfaces,
- SerializableMode serializableMode,
- boolean stripAnnotations) {
+ public static MockFeatures withMockFeatures(
+ Class mockedType,
+ Set> interfaces,
+ SerializableMode serializableMode,
+ boolean stripAnnotations) {
return new MockFeatures(mockedType, interfaces, serializableMode, stripAnnotations);
}
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
index 4887ee1f10..87640a4441 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
@@ -40,22 +40,27 @@ public class MockMethodAdvice extends MockMethodDispatcher {
private final SelfCallInfo selfCallInfo = new SelfCallInfo();
private final MethodGraph.Compiler compiler = MethodGraph.Compiler.Default.forJavaHierarchy();
- private final WeakConcurrentMap, SoftReference> graphs
- = new WeakConcurrentMap.WithInlinedExpunction, SoftReference>();
+ private final WeakConcurrentMap, SoftReference> graphs =
+ new WeakConcurrentMap.WithInlinedExpunction, SoftReference>();
- public MockMethodAdvice(WeakConcurrentMap interceptors, String identifier) {
+ public MockMethodAdvice(
+ WeakConcurrentMap interceptors, String identifier) {
this.interceptors = interceptors;
this.identifier = identifier;
}
@SuppressWarnings("unused")
@Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)
- private static Callable> enter(@Identifier String identifier,
- @Advice.This Object mock,
- @Advice.Origin Method origin,
- @Advice.AllArguments Object[] arguments) throws Throwable {
+ private static Callable> enter(
+ @Identifier String identifier,
+ @Advice.This Object mock,
+ @Advice.Origin Method origin,
+ @Advice.AllArguments Object[] arguments)
+ throws Throwable {
MockMethodDispatcher dispatcher = MockMethodDispatcher.get(identifier, mock);
- if (dispatcher == null || !dispatcher.isMocked(mock) || dispatcher.isOverridden(mock, origin)) {
+ if (dispatcher == null
+ || !dispatcher.isMocked(mock)
+ || dispatcher.isOverridden(mock, origin)) {
return null;
} else {
return dispatcher.handle(mock, origin, arguments);
@@ -64,8 +69,10 @@ private static Callable> enter(@Identifier String identifier,
@SuppressWarnings({"unused", "UnusedAssignment"})
@Advice.OnMethodExit
- private static void exit(@Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object returned,
- @Advice.Enter Callable> mocked) throws Throwable {
+ private static void exit(
+ @Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object returned,
+ @Advice.Enter Callable> mocked)
+ throws Throwable {
if (mocked != null) {
returned = mocked.call();
}
@@ -86,7 +93,8 @@ static Throwable hideRecursiveCall(Throwable throwable, int current, Class> ta
throwable.setStackTrace(cleared);
return throwable;
} catch (RuntimeException ignored) {
- // This should not happen unless someone instrumented or manipulated exception stack traces.
+ // This should not happen unless someone instrumented or manipulated exception stack
+ // traces.
return throwable;
}
}
@@ -103,11 +111,13 @@ public Callable> handle(Object instance, Method origin, Object[] arguments) th
} else {
realMethod = new RealMethodCall(selfCallInfo, origin, instance, arguments);
}
- return new ReturnValueWrapper(interceptor.doIntercept(instance,
- origin,
- arguments,
- realMethod,
- new LocationImpl(new Throwable(), true)));
+ return new ReturnValueWrapper(
+ interceptor.doIntercept(
+ instance,
+ origin,
+ arguments,
+ realMethod,
+ new LocationImpl(new Throwable(), true)));
}
@Override
@@ -130,8 +140,14 @@ public boolean isOverridden(Object instance, Method origin) {
methodGraph = compiler.compile(new TypeDescription.ForLoadedType(instance.getClass()));
graphs.put(instance.getClass(), new SoftReference(methodGraph));
}
- MethodGraph.Node node = methodGraph.locate(new MethodDescription.ForLoadedMethod(origin).asSignatureToken());
- return !node.getSort().isResolved() || !node.getRepresentative().asDefined().getDeclaringType().represents(origin.getDeclaringClass());
+ MethodGraph.Node node =
+ methodGraph.locate(
+ new MethodDescription.ForLoadedMethod(origin).asSignatureToken());
+ return !node.getSort().isResolved()
+ || !node.getRepresentative()
+ .asDefined()
+ .getDeclaringType()
+ .represents(origin.getDeclaringClass());
}
private static class RealMethodCall implements RealMethod {
@@ -144,7 +160,8 @@ private static class RealMethodCall implements RealMethod {
private final Object[] arguments;
- private RealMethodCall(SelfCallInfo selfCallInfo, Method origin, Object instance, Object[] arguments) {
+ private RealMethodCall(
+ SelfCallInfo selfCallInfo, Method origin, Object instance, Object[] arguments) {
this.selfCallInfo = selfCallInfo;
this.origin = origin;
this.instanceRef = new MockWeakReference(instance);
@@ -158,13 +175,13 @@ public boolean isInvokable() {
@Override
public Object invoke() throws Throwable {
- if (!Modifier.isPublic(origin.getDeclaringClass().getModifiers() & origin.getModifiers())) {
+ if (!Modifier.isPublic(
+ origin.getDeclaringClass().getModifiers() & origin.getModifiers())) {
origin.setAccessible(true);
}
selfCallInfo.set(instanceRef.get());
return tryInvoke(origin, instanceRef.get(), arguments);
}
-
}
private static class SerializableRealMethodCall implements RealMethod {
@@ -177,7 +194,8 @@ private static class SerializableRealMethodCall implements RealMethod {
private final Object[] arguments;
- private SerializableRealMethodCall(String identifier, Method origin, Object instance, Object[] arguments) {
+ private SerializableRealMethodCall(
+ String identifier, Method origin, Object instance, Object[] arguments) {
this.origin = new SerializableMethod(origin);
this.identifier = identifier;
this.instanceRef = new MockWeakReference(instance);
@@ -192,14 +210,18 @@ public boolean isInvokable() {
@Override
public Object invoke() throws Throwable {
Method method = origin.getJavaMethod();
- if (!Modifier.isPublic(method.getDeclaringClass().getModifiers() & method.getModifiers())) {
+ if (!Modifier.isPublic(
+ method.getDeclaringClass().getModifiers() & method.getModifiers())) {
method.setAccessible(true);
}
- MockMethodDispatcher mockMethodDispatcher = MockMethodDispatcher.get(identifier, instanceRef.get());
+ MockMethodDispatcher mockMethodDispatcher =
+ MockMethodDispatcher.get(identifier, instanceRef.get());
if (!(mockMethodDispatcher instanceof MockMethodAdvice)) {
throw new MockitoException("Unexpected dispatcher for advice-based super call");
}
- Object previous = ((MockMethodAdvice) mockMethodDispatcher).selfCallInfo.replace(instanceRef.get());
+ Object previous =
+ ((MockMethodAdvice) mockMethodDispatcher)
+ .selfCallInfo.replace(instanceRef.get());
try {
return tryInvoke(method, instanceRef.get(), arguments);
} finally {
@@ -208,12 +230,18 @@ public Object invoke() throws Throwable {
}
}
- private static Object tryInvoke(Method origin, Object instance, Object[] arguments) throws Throwable {
+ private static Object tryInvoke(Method origin, Object instance, Object[] arguments)
+ throws Throwable {
try {
return origin.invoke(instance, arguments);
} catch (InvocationTargetException exception) {
Throwable cause = exception.getCause();
- new ConditionalStackTraceFilter().filter(hideRecursiveCall(cause, new Throwable().getStackTrace().length, origin.getDeclaringClass()));
+ new ConditionalStackTraceFilter()
+ .filter(
+ hideRecursiveCall(
+ cause,
+ new Throwable().getStackTrace().length,
+ origin.getDeclaringClass()));
throw cause;
}
}
@@ -251,25 +279,23 @@ boolean checkSuperCall(Object value) {
}
@Retention(RetentionPolicy.RUNTIME)
- @interface Identifier {
-
- }
+ @interface Identifier {}
static class ForHashCode {
@SuppressWarnings("unused")
@Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)
- private static boolean enter(@Identifier String id,
- @Advice.This Object self) {
+ private static boolean enter(@Identifier String id, @Advice.This Object self) {
MockMethodDispatcher dispatcher = MockMethodDispatcher.get(id, self);
return dispatcher != null && dispatcher.isMock(self);
}
@SuppressWarnings({"unused", "UnusedAssignment"})
@Advice.OnMethodExit
- private static void enter(@Advice.This Object self,
- @Advice.Return(readOnly = false) int hashCode,
- @Advice.Enter boolean skipped) {
+ private static void enter(
+ @Advice.This Object self,
+ @Advice.Return(readOnly = false) int hashCode,
+ @Advice.Enter boolean skipped) {
if (skipped) {
hashCode = System.identityHashCode(self);
}
@@ -280,18 +306,18 @@ static class ForEquals {
@SuppressWarnings("unused")
@Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)
- private static boolean enter(@Identifier String identifier,
- @Advice.This Object self) {
+ private static boolean enter(@Identifier String identifier, @Advice.This Object self) {
MockMethodDispatcher dispatcher = MockMethodDispatcher.get(identifier, self);
return dispatcher != null && dispatcher.isMock(self);
}
@SuppressWarnings({"unused", "UnusedAssignment"})
@Advice.OnMethodExit
- private static void enter(@Advice.This Object self,
- @Advice.Argument(0) Object other,
- @Advice.Return(readOnly = false) boolean equals,
- @Advice.Enter boolean skipped) {
+ private static void enter(
+ @Advice.This Object self,
+ @Advice.Argument(0) Object other,
+ @Advice.Return(readOnly = false) boolean equals,
+ @Advice.Enter boolean skipped) {
if (skipped) {
equals = self == other;
}
@@ -301,11 +327,14 @@ private static void enter(@Advice.This Object self,
public static class ForReadObject {
@SuppressWarnings("unused")
- public static void doReadObject(@Identifier String identifier,
- @This MockAccess thiz,
- @Argument(0) ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
+ public static void doReadObject(
+ @Identifier String identifier,
+ @This MockAccess thiz,
+ @Argument(0) ObjectInputStream objectInputStream)
+ throws IOException, ClassNotFoundException {
objectInputStream.defaultReadObject();
- MockMethodAdvice mockMethodAdvice = (MockMethodAdvice) MockMethodDispatcher.get(identifier, thiz);
+ MockMethodAdvice mockMethodAdvice =
+ (MockMethodAdvice) MockMethodDispatcher.get(identifier, thiz);
if (mockMethodAdvice != null) {
mockMethodAdvice.interceptors.put(thiz, thiz.getMockitoInterceptor());
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
index fdb706b882..532ecc804d 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
@@ -42,23 +42,26 @@ public MockMethodInterceptor(MockHandler handler, MockCreationSettings mockCreat
serializationSupport = new ByteBuddyCrossClassLoaderSerializationSupport();
}
- Object doIntercept(Object mock,
- Method invokedMethod,
- Object[] arguments,
- RealMethod realMethod) throws Throwable {
- return doIntercept(mock,
- invokedMethod,
- arguments,
- realMethod,
- new LocationImpl());
+ Object doIntercept(Object mock, Method invokedMethod, Object[] arguments, RealMethod realMethod)
+ throws Throwable {
+ return doIntercept(mock, invokedMethod, arguments, realMethod, new LocationImpl());
}
- Object doIntercept(Object mock,
- Method invokedMethod,
- Object[] arguments,
- RealMethod realMethod,
- Location location) throws Throwable {
- return handler.handle(createInvocation(mock, invokedMethod, arguments, realMethod, mockCreationSettings, location));
+ Object doIntercept(
+ Object mock,
+ Method invokedMethod,
+ Object[] arguments,
+ RealMethod realMethod,
+ Location location)
+ throws Throwable {
+ return handler.handle(
+ createInvocation(
+ mock,
+ invokedMethod,
+ arguments,
+ realMethod,
+ mockCreationSettings,
+ location));
}
public MockHandler getMockHandler() {
@@ -97,38 +100,34 @@ public static class DispatcherDefaultingToRealMethod {
@SuppressWarnings("unused")
@RuntimeType
@BindingPriority(BindingPriority.DEFAULT * 2)
- public static Object interceptSuperCallable(@This Object mock,
- @FieldValue("mockitoInterceptor") MockMethodInterceptor interceptor,
- @Origin Method invokedMethod,
- @AllArguments Object[] arguments,
- @SuperCall(serializableProxy = true) Callable> superCall) throws Throwable {
+ public static Object interceptSuperCallable(
+ @This Object mock,
+ @FieldValue("mockitoInterceptor") MockMethodInterceptor interceptor,
+ @Origin Method invokedMethod,
+ @AllArguments Object[] arguments,
+ @SuperCall(serializableProxy = true) Callable> superCall)
+ throws Throwable {
if (interceptor == null) {
return superCall.call();
}
return interceptor.doIntercept(
- mock,
- invokedMethod,
- arguments,
- new RealMethod.FromCallable(superCall)
- );
+ mock, invokedMethod, arguments, new RealMethod.FromCallable(superCall));
}
@SuppressWarnings("unused")
@RuntimeType
- public static Object interceptAbstract(@This Object mock,
- @FieldValue("mockitoInterceptor") MockMethodInterceptor interceptor,
- @StubValue Object stubValue,
- @Origin Method invokedMethod,
- @AllArguments Object[] arguments) throws Throwable {
+ public static Object interceptAbstract(
+ @This Object mock,
+ @FieldValue("mockitoInterceptor") MockMethodInterceptor interceptor,
+ @StubValue Object stubValue,
+ @Origin Method invokedMethod,
+ @AllArguments Object[] arguments)
+ throws Throwable {
if (interceptor == null) {
return stubValue;
}
return interceptor.doIntercept(
- mock,
- invokedMethod,
- arguments,
- RealMethod.IsIllegal.INSTANCE
- );
+ mock, invokedMethod, arguments, RealMethod.IsIllegal.INSTANCE);
}
}
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ModuleHandler.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ModuleHandler.java
index 1aa9cdc07e..38716d0776 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/ModuleHandler.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ModuleHandler.java
@@ -37,9 +37,7 @@ abstract class ModuleHandler {
static ModuleHandler make(ByteBuddy byteBuddy, SubclassLoader loader, Random random) {
try {
- return new ModuleSystemFound(
- byteBuddy, loader, random
- );
+ return new ModuleSystemFound(byteBuddy, loader, random);
} catch (Exception ignored) {
return new NoModuleSystemFound();
}
@@ -53,9 +51,18 @@ private static class ModuleSystemFound extends ModuleHandler {
private final int injectonBaseSuffix;
- private final Method getModule, isOpen, isExported, isExportedUnqualified, canRead, addExports, addReads, addOpens, forName;
+ private final Method getModule,
+ isOpen,
+ isExported,
+ isExportedUnqualified,
+ canRead,
+ addExports,
+ addReads,
+ addOpens,
+ forName;
- private ModuleSystemFound(ByteBuddy byteBuddy, SubclassLoader loader, Random random) throws Exception {
+ private ModuleSystemFound(ByteBuddy byteBuddy, SubclassLoader loader, Random random)
+ throws Exception {
this.byteBuddy = byteBuddy;
this.loader = loader;
this.random = random;
@@ -77,7 +84,12 @@ boolean isOpened(Class> source, Class> target) {
if (source.getPackage() == null) {
return true;
}
- return (Boolean) invoke(isOpen, invoke(getModule, source), source.getPackage().getName(), invoke(getModule, target));
+ return (Boolean)
+ invoke(
+ isOpen,
+ invoke(getModule, source),
+ source.getPackage().getName(),
+ invoke(getModule, target));
}
@Override
@@ -90,7 +102,11 @@ boolean isExported(Class> source) {
if (source.getPackage() == null) {
return true;
}
- return (Boolean) invoke(isExportedUnqualified, invoke(getModule, source), source.getPackage().getName());
+ return (Boolean)
+ invoke(
+ isExportedUnqualified,
+ invoke(getModule, source),
+ source.getPackage().getName());
}
@Override
@@ -98,25 +114,39 @@ boolean isExported(Class> source, Class> target) {
if (source.getPackage() == null) {
return true;
}
- return (Boolean) invoke(isExported, invoke(getModule, source), source.getPackage().getName(), invoke(getModule, target));
+ return (Boolean)
+ invoke(
+ isExported,
+ invoke(getModule, source),
+ source.getPackage().getName(),
+ invoke(getModule, target));
}
@Override
Class> injectionBase(ClassLoader classLoader, String typeName) {
String packageName = typeName.substring(0, typeName.lastIndexOf('.'));
- if (classLoader == InjectionBase.class.getClassLoader() && InjectionBase.class.getPackage().getName().equals(packageName)) {
+ if (classLoader == InjectionBase.class.getClassLoader()
+ && InjectionBase.class.getPackage().getName().equals(packageName)) {
return InjectionBase.class;
} else {
synchronized (this) {
String name;
int suffix = injectonBaseSuffix;
do {
- name = packageName + "." + InjectionBase.class.getSimpleName() + "$" + suffix++;
+ name =
+ packageName
+ + "."
+ + InjectionBase.class.getSimpleName()
+ + "$"
+ + suffix++;
try {
Class> type = Class.forName(name, false, classLoader);
- // The injected type must be defined in the class loader that is target of the injection. Otherwise,
- // the class's unnamed module would differ from the intended module. To avoid conflicts, we increment
- // the suffix until we hit a class with a known name and generate one if it does not exist.
+ // The injected type must be defined in the class loader that is target
+ // of the injection. Otherwise,
+ // the class's unnamed module would differ from the intended module. To
+ // avoid conflicts, we increment
+ // the suffix until we hit a class with a known name and generate one if
+ // it does not exist.
if (type.getClassLoader() == classLoader) {
return type;
}
@@ -124,11 +154,14 @@ Class> injectionBase(ClassLoader classLoader, String typeName) {
break;
}
} while (true);
- return byteBuddy.subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
- .name(name)
- .make()
- .load(classLoader, loader.resolveStrategy(InjectionBase.class, classLoader, false))
- .getLoaded();
+ return byteBuddy
+ .subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
+ .name(name)
+ .make()
+ .load(
+ classLoader,
+ loader.resolveStrategy(InjectionBase.class, classLoader, false))
+ .getLoaded();
}
}
}
@@ -142,11 +175,14 @@ void adjustModuleGraph(Class> source, Class> target, boolean export, boolean
}
ClassLoader classLoader = source.getClassLoader();
if (classLoader == null) {
- throw new MockitoException(join("Cannot adjust module graph for modules in the bootstrap loader",
- "",
- source + " is declared by the bootstrap loader and cannot be adjusted",
- "Requires package export to " + target + ": " + needsExport,
- "Requires adjusted reading of " + target + ": " + needsRead));
+ throw new MockitoException(
+ join(
+ "Cannot adjust module graph for modules in the bootstrap loader",
+ "",
+ source
+ + " is declared by the bootstrap loader and cannot be adjusted",
+ "Requires package export to " + target + ": " + needsExport,
+ "Requires adjusted reading of " + target + ": " + needsRead));
}
boolean targetVisible = classLoader == target.getClassLoader();
while (!targetVisible && classLoader != null) {
@@ -156,52 +192,98 @@ void adjustModuleGraph(Class> source, Class> target, boolean export, boolean
MethodCall targetLookup;
Implementation.Composable implementation;
if (targetVisible) {
- targetLookup = MethodCall.invoke(getModule).onMethodCall(MethodCall.invoke(forName).with(target.getName()));
+ targetLookup =
+ MethodCall.invoke(getModule)
+ .onMethodCall(MethodCall.invoke(forName).with(target.getName()));
implementation = StubMethod.INSTANCE;
} else {
Class> intermediate;
Field field;
try {
- intermediate = byteBuddy.subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
- .name(String.format("%s$%d", "org.mockito.codegen.MockitoTypeCarrier", Math.abs(random.nextInt())))
- .defineField("mockitoType", Class.class, Visibility.PUBLIC, Ownership.STATIC)
- .make()
- .load(source.getClassLoader(), loader.resolveStrategy(source, source.getClassLoader(), false))
- .getLoaded();
+ intermediate =
+ byteBuddy
+ .subclass(
+ Object.class,
+ ConstructorStrategy.Default.NO_CONSTRUCTORS)
+ .name(
+ String.format(
+ "%s$%d",
+ "org.mockito.codegen.MockitoTypeCarrier",
+ Math.abs(random.nextInt())))
+ .defineField(
+ "mockitoType",
+ Class.class,
+ Visibility.PUBLIC,
+ Ownership.STATIC)
+ .make()
+ .load(
+ source.getClassLoader(),
+ loader.resolveStrategy(
+ source, source.getClassLoader(), false))
+ .getLoaded();
field = intermediate.getField("mockitoType");
field.set(null, target);
} catch (Exception e) {
- throw new MockitoException(join("Could not create a carrier for making the Mockito type visible to " + source,
- "",
- "This is required to adjust the module graph to enable mock creation"), e);
+ throw new MockitoException(
+ join(
+ "Could not create a carrier for making the Mockito type visible to "
+ + source,
+ "",
+ "This is required to adjust the module graph to enable mock creation"),
+ e);
}
targetLookup = MethodCall.invoke(getModule).onField(field);
- implementation = MethodCall.invoke(getModule).onMethodCall(MethodCall.invoke(forName).with(intermediate.getName()));
+ implementation =
+ MethodCall.invoke(getModule)
+ .onMethodCall(
+ MethodCall.invoke(forName).with(intermediate.getName()));
}
- MethodCall sourceLookup = MethodCall.invoke(getModule).onMethodCall(MethodCall.invoke(forName).with(source.getName()));
+ MethodCall sourceLookup =
+ MethodCall.invoke(getModule)
+ .onMethodCall(MethodCall.invoke(forName).with(source.getName()));
if (needsExport) {
- implementation = implementation.andThen(MethodCall.invoke(addExports)
- .onMethodCall(sourceLookup)
- .with(target.getPackage().getName())
- .withMethodCall(targetLookup));
+ implementation =
+ implementation.andThen(
+ MethodCall.invoke(addExports)
+ .onMethodCall(sourceLookup)
+ .with(target.getPackage().getName())
+ .withMethodCall(targetLookup));
}
if (needsRead) {
- implementation = implementation.andThen(MethodCall.invoke(addReads)
- .onMethodCall(sourceLookup)
- .withMethodCall(targetLookup));
+ implementation =
+ implementation.andThen(
+ MethodCall.invoke(addReads)
+ .onMethodCall(sourceLookup)
+ .withMethodCall(targetLookup));
}
try {
- Class.forName(byteBuddy.subclass(Object.class)
- .name(String.format("%s$%s$%d", source.getName(), "MockitoModuleProbe", Math.abs(random.nextInt())))
- .invokable(isTypeInitializer()).intercept(implementation)
- .make()
- .load(source.getClassLoader(), loader.resolveStrategy(source, source.getClassLoader(), false))
- .getLoaded()
- .getName(), true, source.getClassLoader());
+ Class.forName(
+ byteBuddy
+ .subclass(Object.class)
+ .name(
+ String.format(
+ "%s$%s$%d",
+ source.getName(),
+ "MockitoModuleProbe",
+ Math.abs(random.nextInt())))
+ .invokable(isTypeInitializer())
+ .intercept(implementation)
+ .make()
+ .load(
+ source.getClassLoader(),
+ loader.resolveStrategy(
+ source, source.getClassLoader(), false))
+ .getLoaded()
+ .getName(),
+ true,
+ source.getClassLoader());
} catch (Exception e) {
- throw new MockitoException(join("Could not force module adjustment of the module of " + source,
- "",
- "This is required to adjust the module graph to enable mock creation"), e);
+ throw new MockitoException(
+ join(
+ "Could not force module adjustment of the module of " + source,
+ "",
+ "This is required to adjust the module graph to enable mock creation"),
+ e);
}
}
@@ -209,9 +291,12 @@ private static Object invoke(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
} catch (Exception e) {
- throw new MockitoException(join("Could not invoke " + method + " using reflection",
- "",
- "Mockito attempted to interact with the Java module system but an unexpected method behavior was encountered"), e);
+ throw new MockitoException(
+ join(
+ "Could not invoke " + method + " using reflection",
+ "",
+ "Mockito attempted to interact with the Java module system but an unexpected method behavior was encountered"),
+ e);
}
}
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMaker.java
index e264a82572..e112d9e281 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMaker.java
@@ -34,7 +34,8 @@ public SubclassByteBuddyMockMaker() {
}
public SubclassByteBuddyMockMaker(SubclassLoader loader) {
- cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(loader), false);
+ cachingMockBytecodeGenerator =
+ new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(loader), false);
}
@Override
@@ -50,36 +51,42 @@ public T createMock(MockCreationSettings settings, MockHandler handler) {
return ensureMockIsAssignableToMockedType(settings, mockInstance);
} catch (ClassCastException cce) {
- throw new MockitoException(join(
- "ClassCastException occurred while creating the mockito mock :",
- " class to mock : " + describeClass(settings.getTypeToMock()),
- " created class : " + describeClass(mockedProxyType),
- " proxy instance class : " + describeClass(mockInstance),
- " instance creation by : " + instantiator.getClass().getSimpleName(),
- "",
- "You might experience classloading issues, please ask the mockito mailing-list.",
- ""
- ), cce);
+ throw new MockitoException(
+ join(
+ "ClassCastException occurred while creating the mockito mock :",
+ " class to mock : " + describeClass(settings.getTypeToMock()),
+ " created class : " + describeClass(mockedProxyType),
+ " proxy instance class : " + describeClass(mockInstance),
+ " instance creation by : " + instantiator.getClass().getSimpleName(),
+ "",
+ "You might experience classloading issues, please ask the mockito mailing-list.",
+ ""),
+ cce);
} catch (org.mockito.creation.instance.InstantiationException e) {
- throw new MockitoException("Unable to create mock instance of type '" + mockedProxyType.getSuperclass().getSimpleName() + "'", e);
+ throw new MockitoException(
+ "Unable to create mock instance of type '"
+ + mockedProxyType.getSuperclass().getSimpleName()
+ + "'",
+ e);
}
}
@Override
public Class extends T> createMockType(MockCreationSettings settings) {
try {
- return cachingMockBytecodeGenerator.mockClass(MockFeatures.withMockFeatures(
- settings.getTypeToMock(),
- settings.getExtraInterfaces(),
- settings.getSerializableMode(),
- settings.isStripAnnotations()
- ));
+ return cachingMockBytecodeGenerator.mockClass(
+ MockFeatures.withMockFeatures(
+ settings.getTypeToMock(),
+ settings.getExtraInterfaces(),
+ settings.getSerializableMode(),
+ settings.isStripAnnotations()));
} catch (Exception bytecodeGenerationFailed) {
throw prettifyFailure(settings, bytecodeGenerationFailed);
}
}
- private static T ensureMockIsAssignableToMockedType(MockCreationSettings settings, T mock) {
+ private static T ensureMockIsAssignableToMockedType(
+ MockCreationSettings settings, T mock) {
// Force explicit cast to mocked type here, instead of
// relying on the JVM to implicitly cast on the client call site.
// This allows us to catch earlier the ClassCastException earlier
@@ -87,38 +94,49 @@ private static T ensureMockIsAssignableToMockedType(MockCreationSettings
return typeToMock.cast(mock);
}
- private RuntimeException prettifyFailure(MockCreationSettings mockFeatures, Exception generationFailed) {
+ private RuntimeException prettifyFailure(
+ MockCreationSettings mockFeatures, Exception generationFailed) {
if (mockFeatures.getTypeToMock().isArray()) {
- throw new MockitoException(join(
- "Mockito cannot mock arrays: " + mockFeatures.getTypeToMock() + ".",
- ""
- ), generationFailed);
+ throw new MockitoException(
+ join("Mockito cannot mock arrays: " + mockFeatures.getTypeToMock() + ".", ""),
+ generationFailed);
}
if (Modifier.isPrivate(mockFeatures.getTypeToMock().getModifiers())) {
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
- "Most likely it is due to mocking a private class that is not visible to Mockito",
- ""
- ), generationFailed);
+ throw new MockitoException(
+ join(
+ "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
+ "Most likely it is due to mocking a private class that is not visible to Mockito",
+ ""),
+ generationFailed);
}
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
- "",
- "Mockito can only mock non-private & non-final classes.",
- "If you're not sure why you're getting this error, please report to the mailing list.",
- "",
- Platform.warnForVM(
- "IBM J9 VM", "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n",
- "Hotspot", Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : ""
- ),
- Platform.describe(),
- "",
- "Underlying exception : " + generationFailed
- ), generationFailed);
+ throw new MockitoException(
+ join(
+ "Mockito cannot mock this class: " + mockFeatures.getTypeToMock() + ".",
+ "",
+ "Mockito can only mock non-private & non-final classes.",
+ "If you're not sure why you're getting this error, please report to the mailing list.",
+ "",
+ Platform.warnForVM(
+ "IBM J9 VM",
+ "Early IBM virtual machine are known to have issues with Mockito, please upgrade to an up-to-date version.\n",
+ "Hotspot",
+ Platform.isJava8BelowUpdate45()
+ ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n"
+ : ""),
+ Platform.describe(),
+ "",
+ "Underlying exception : " + generationFailed),
+ generationFailed);
}
private static String describeClass(Class> type) {
- return type == null ? "null" : "'" + type.getCanonicalName() + "', loaded by classloader : '" + type.getClassLoader() + "'";
+ return type == null
+ ? "null"
+ : "'"
+ + type.getCanonicalName()
+ + "', loaded by classloader : '"
+ + type.getClassLoader()
+ + "'";
}
private static String describeClass(Object instance) {
@@ -135,9 +153,7 @@ public MockHandler getHandler(Object mock) {
@Override
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
- ((MockAccess) mock).setMockitoInterceptor(
- new MockMethodInterceptor(newHandler, settings)
- );
+ ((MockAccess) mock).setMockitoInterceptor(new MockMethodInterceptor(newHandler, settings));
}
@Override
@@ -150,7 +166,7 @@ public boolean mockable() {
@Override
public String nonMockableReason() {
- if(mockable()) {
+ if (mockable()) {
return "";
}
if (type.isPrimitive()) {
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
index 0a56186579..f323f23d44 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
@@ -65,11 +65,15 @@ public SubclassBytecodeGenerator(SubclassLoader loader) {
this(loader, null, any());
}
- public SubclassBytecodeGenerator(Implementation readReplace, ElementMatcher super MethodDescription> matcher) {
+ public SubclassBytecodeGenerator(
+ Implementation readReplace, ElementMatcher super MethodDescription> matcher) {
this(new SubclassInjectionLoader(), readReplace, matcher);
}
- protected SubclassBytecodeGenerator(SubclassLoader loader, Implementation readReplace, ElementMatcher super MethodDescription> matcher) {
+ protected SubclassBytecodeGenerator(
+ SubclassLoader loader,
+ Implementation readReplace,
+ ElementMatcher super MethodDescription> matcher) {
this.loader = loader;
this.readReplace = readReplace;
this.matcher = matcher;
@@ -80,28 +84,40 @@ protected SubclassBytecodeGenerator(SubclassLoader loader, Implementation readRe
@Override
public Class extends T> mockClass(MockFeatures features) {
- ClassLoader classLoader = new MultipleParentClassLoader.Builder()
- .appendMostSpecific(getAllTypes(features.mockedType))
- .appendMostSpecific(features.interfaces)
- .appendMostSpecific(currentThread().getContextClassLoader())
- .appendMostSpecific(MockAccess.class)
- .build();
-
- // If Mockito does not need to create a new class loader and if a mock is not based on a JDK type, we attempt
- // to define the mock class in the user runtime package to allow for mocking package private types and methods.
- // This also requires that we are able to access the package of the mocked class either by override or explicit
+ ClassLoader classLoader =
+ new MultipleParentClassLoader.Builder()
+ .appendMostSpecific(getAllTypes(features.mockedType))
+ .appendMostSpecific(features.interfaces)
+ .appendMostSpecific(currentThread().getContextClassLoader())
+ .appendMostSpecific(MockAccess.class)
+ .build();
+
+ // If Mockito does not need to create a new class loader and if a mock is not based on a JDK
+ // type, we attempt
+ // to define the mock class in the user runtime package to allow for mocking package private
+ // types and methods.
+ // This also requires that we are able to access the package of the mocked class either by
+ // override or explicit
// privilege given by the target package being opened to Mockito.
- boolean localMock = classLoader == features.mockedType.getClassLoader()
- && features.serializableMode != SerializableMode.ACROSS_CLASSLOADERS
- && !isComingFromJDK(features.mockedType)
- && (loader.isDisrespectingOpenness() || handler.isOpened(features.mockedType, MockAccess.class));
+ boolean localMock =
+ classLoader == features.mockedType.getClassLoader()
+ && features.serializableMode != SerializableMode.ACROSS_CLASSLOADERS
+ && !isComingFromJDK(features.mockedType)
+ && (loader.isDisrespectingOpenness()
+ || handler.isOpened(features.mockedType, MockAccess.class));
String typeName;
- if (localMock || loader instanceof MultipleParentClassLoader && !isComingFromJDK(features.mockedType)) {
+ if (localMock
+ || loader instanceof MultipleParentClassLoader
+ && !isComingFromJDK(features.mockedType)) {
typeName = features.mockedType.getName();
} else {
- typeName = InjectionBase.class.getPackage().getName() + "." + features.mockedType.getSimpleName();
+ typeName =
+ InjectionBase.class.getPackage().getName()
+ + "."
+ + features.mockedType.getSimpleName();
}
- String name = String.format("%s$%s$%d", typeName, "MockitoMock", Math.abs(random.nextInt()));
+ String name =
+ String.format("%s$%s$%d", typeName, "MockitoMock", Math.abs(random.nextInt()));
if (localMock) {
handler.adjustModuleGraph(features.mockedType, MockAccess.class, false, true);
@@ -115,8 +131,10 @@ public Class extends T> mockClass(MockFeatures features) {
while (exported && it.hasNext()) {
exported = handler.isExported(it.next());
}
- // We check if all mocked types are exported without qualification to avoid generating a hook type.
- // unless this is necessary. We expect this to be the case for most mocked types what makes this a
+ // We check if all mocked types are exported without qualification to avoid generating a
+ // hook type.
+ // unless this is necessary. We expect this to be the case for most mocked types what
+ // makes this a
// worthy performance optimization.
if (exported) {
assertVisibility(features.mockedType);
@@ -134,45 +152,55 @@ public Class extends T> mockClass(MockFeatures features) {
}
}
- DynamicType.Builder builder = byteBuddy.subclass(features.mockedType)
- .name(name)
- .ignoreAlso(isGroovyMethod())
- .annotateType(features.stripAnnotations
- ? new Annotation[0]
- : features.mockedType.getAnnotations())
- .implement(new ArrayList(features.interfaces))
- .method(matcher)
- .intercept(dispatcher)
- .transform(withModifiers(SynchronizationState.PLAIN))
- .attribute(features.stripAnnotations
- ? MethodAttributeAppender.NoOp.INSTANCE
- : INCLUDING_RECEIVER)
- .method(isHashCode())
- .intercept(hashCode)
- .method(isEquals())
- .intercept(equals)
- .serialVersionUid(42L)
- .defineField("mockitoInterceptor", MockMethodInterceptor.class, PRIVATE)
- .implement(MockAccess.class)
- .intercept(FieldAccessor.ofBeanProperty());
+ DynamicType.Builder builder =
+ byteBuddy
+ .subclass(features.mockedType)
+ .name(name)
+ .ignoreAlso(isGroovyMethod())
+ .annotateType(
+ features.stripAnnotations
+ ? new Annotation[0]
+ : features.mockedType.getAnnotations())
+ .implement(new ArrayList(features.interfaces))
+ .method(matcher)
+ .intercept(dispatcher)
+ .transform(withModifiers(SynchronizationState.PLAIN))
+ .attribute(
+ features.stripAnnotations
+ ? MethodAttributeAppender.NoOp.INSTANCE
+ : INCLUDING_RECEIVER)
+ .method(isHashCode())
+ .intercept(hashCode)
+ .method(isEquals())
+ .intercept(equals)
+ .serialVersionUid(42L)
+ .defineField("mockitoInterceptor", MockMethodInterceptor.class, PRIVATE)
+ .implement(MockAccess.class)
+ .intercept(FieldAccessor.ofBeanProperty());
if (features.serializableMode == SerializableMode.ACROSS_CLASSLOADERS) {
- builder = builder.implement(CrossClassLoaderSerializableMock.class)
- .intercept(writeReplace);
+ builder =
+ builder.implement(CrossClassLoaderSerializableMock.class)
+ .intercept(writeReplace);
}
if (readReplace != null) {
- builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
- .withParameters(ObjectInputStream.class)
- .throwing(ClassNotFoundException.class, IOException.class)
- .intercept(readReplace);
+ builder =
+ builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
+ .withParameters(ObjectInputStream.class)
+ .throwing(ClassNotFoundException.class, IOException.class)
+ .intercept(readReplace);
}
if (name.startsWith(CODEGEN_PACKAGE) || classLoader instanceof MultipleParentClassLoader) {
- builder = builder.ignoreAlso(isPackagePrivate()
- .or(returns(isPackagePrivate()))
- .or(hasParameters(whereAny(hasType(isPackagePrivate())))));
+ builder =
+ builder.ignoreAlso(
+ isPackagePrivate()
+ .or(returns(isPackagePrivate()))
+ .or(hasParameters(whereAny(hasType(isPackagePrivate())))));
}
return builder.make()
- .load(classLoader, loader.resolveStrategy(features.mockedType, classLoader, localMock))
- .getLoaded();
+ .load(
+ classLoader,
+ loader.resolveStrategy(features.mockedType, classLoader, localMock))
+ .getLoaded();
}
private Collection> getAllTypes(Class type) {
@@ -194,20 +222,24 @@ private boolean isComingFromJDK(Class> type) {
// Comes from the manifest entry :
// Implementation-Title: Java Runtime Environment
// This entry is not necessarily present in every jar of the JDK
- return type.getPackage() != null && "Java Runtime Environment".equalsIgnoreCase(type.getPackage().getImplementationTitle())
- || type.getName().startsWith("java.")
- || type.getName().startsWith("javax.");
+ return type.getPackage() != null
+ && "Java Runtime Environment"
+ .equalsIgnoreCase(type.getPackage().getImplementationTitle())
+ || type.getName().startsWith("java.")
+ || type.getName().startsWith("javax.");
}
private static void assertVisibility(Class> type) {
if (!Modifier.isPublic(type.getModifiers())) {
- throw new MockitoException(join("Cannot create mock for " + type,
- "",
- "The type is not public and its mock class is loaded by a different class loader.",
- "This can have multiple reasons:",
- " - You are mocking a class with additional interfaces of another class loader",
- " - Mockito is loaded by a different class loader than the mocked type (e.g. with OSGi)",
- " - The thread's context class loader is different than the mock's class loader"));
+ throw new MockitoException(
+ join(
+ "Cannot create mock for " + type,
+ "",
+ "The type is not public and its mock class is loaded by a different class loader.",
+ "This can have multiple reasons:",
+ " - You are mocking a class with additional interfaces of another class loader",
+ " - Mockito is loaded by a different class loader than the mocked type (e.g. with OSGi)",
+ " - The thread's context class loader is different than the mock's class loader"));
}
}
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java
index a2b34ed706..5211629449 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java
@@ -17,15 +17,18 @@
class SubclassInjectionLoader implements SubclassLoader {
- private static final String ERROR_MESSAGE = join("The current JVM does not support any class injection mechanism.",
- "",
- "Currently, Mockito supports injection via neither by method handle lookups or using sun.misc.Unsafe",
- "Neither seems to be available on your current JVM.");
+ private static final String ERROR_MESSAGE =
+ join(
+ "The current JVM does not support any class injection mechanism.",
+ "",
+ "Currently, Mockito supports injection via neither by method handle lookups or using sun.misc.Unsafe",
+ "Neither seems to be available on your current JVM.");
private final SubclassLoader loader;
SubclassInjectionLoader() {
- if (!Boolean.getBoolean("org.mockito.internal.noUnsafeInjection") && ClassInjector.UsingReflection.isAvailable()) {
+ if (!Boolean.getBoolean("org.mockito.internal.noUnsafeInjection")
+ && ClassInjector.UsingReflection.isAvailable()) {
this.loader = new WithReflection();
} else if (ClassInjector.UsingLookup.isAvailable()) {
this.loader = tryLookup();
@@ -38,7 +41,11 @@ private static SubclassLoader tryLookup() {
try {
Class> methodHandles = Class.forName("java.lang.invoke.MethodHandles");
Object lookup = methodHandles.getMethod("lookup").invoke(null);
- Method privateLookupIn = methodHandles.getMethod("privateLookupIn", Class.class, Class.forName("java.lang.invoke.MethodHandles$Lookup"));
+ Method privateLookupIn =
+ methodHandles.getMethod(
+ "privateLookupIn",
+ Class.class,
+ Class.forName("java.lang.invoke.MethodHandles$Lookup"));
Object codegenLookup = privateLookupIn.invoke(null, InjectionBase.class, lookup);
return new WithLookup(lookup, codegenLookup, privateLookupIn);
} catch (Exception exception) {
@@ -54,8 +61,12 @@ public boolean isDisrespectingOpenness() {
}
@Override
- public ClassLoadingStrategy resolveStrategy(Class> mockedType, ClassLoader classLoader, boolean localMock) {
- return ClassLoadingStrategy.Default.INJECTION.with(localMock ? mockedType.getProtectionDomain() : InjectionBase.class.getProtectionDomain());
+ public ClassLoadingStrategy resolveStrategy(
+ Class> mockedType, ClassLoader classLoader, boolean localMock) {
+ return ClassLoadingStrategy.Default.INJECTION.with(
+ localMock
+ ? mockedType.getProtectionDomain()
+ : InjectionBase.class.getProtectionDomain());
}
}
@@ -79,7 +90,8 @@ public boolean isDisrespectingOpenness() {
}
@Override
- public ClassLoadingStrategy resolveStrategy(Class> mockedType, ClassLoader classLoader, boolean localMock) {
+ public ClassLoadingStrategy resolveStrategy(
+ Class> mockedType, ClassLoader classLoader, boolean localMock) {
if (localMock) {
try {
Object privateLookup;
@@ -87,20 +99,22 @@ public ClassLoadingStrategy resolveStrategy(Class> mockedType, Cl
privateLookup = privateLookupIn.invoke(null, mockedType, lookup);
} catch (InvocationTargetException exception) {
if (exception.getCause() instanceof IllegalAccessException) {
- return ClassLoadingStrategy.Default.WRAPPER.with(mockedType.getProtectionDomain());
+ return ClassLoadingStrategy.Default.WRAPPER.with(
+ mockedType.getProtectionDomain());
} else {
throw exception.getCause();
}
}
return ClassLoadingStrategy.UsingLookup.of(privateLookup);
} catch (Throwable exception) {
- throw new MockitoException(join(
- "The Java module system prevents Mockito from defining a mock class in the same package as " + mockedType,
- "",
- "To overcome this, you must open and export the mocked type to Mockito.",
- "Remember that you can also do so programmatically if the mocked class is defined by the same module as your test code",
- exception
- ));
+ throw new MockitoException(
+ join(
+ "The Java module system prevents Mockito from defining a mock class in the same package as "
+ + mockedType,
+ "",
+ "To overcome this, you must open and export the mocked type to Mockito.",
+ "Remember that you can also do so programmatically if the mocked class is defined by the same module as your test code",
+ exception));
}
} else if (classLoader == InjectionBase.class.getClassLoader()) {
return ClassLoadingStrategy.UsingLookup.of(codegenLookup);
@@ -116,7 +130,8 @@ public boolean isDisrespectingOpenness() {
}
@Override
- public ClassLoadingStrategy resolveStrategy(Class> mockedType, ClassLoader classLoader, boolean localMock) {
+ public ClassLoadingStrategy resolveStrategy(
+ Class> mockedType, ClassLoader classLoader, boolean localMock) {
return loader.resolveStrategy(mockedType, classLoader, localMock);
}
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassLoader.java b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassLoader.java
index 011504ea17..289497d23d 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassLoader.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassLoader.java
@@ -26,5 +26,6 @@ public interface SubclassLoader {
* @param localMock {@code true} if the mock is loaded within the runtime package of the mocked type.
* @return An appropriate class loading strategy.
*/
- ClassLoadingStrategy resolveStrategy(Class> mockedType, ClassLoader classLoader, boolean localMock);
+ ClassLoadingStrategy resolveStrategy(
+ Class> mockedType, ClassLoader classLoader, boolean localMock);
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java
index 25fabe5849..18ca2423a6 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java
@@ -11,7 +11,8 @@
import net.bytebuddy.TypeCache;
import org.mockito.mock.SerializableMode;
-class TypeCachingBytecodeGenerator extends ReferenceQueue implements BytecodeGenerator {
+class TypeCachingBytecodeGenerator extends ReferenceQueue
+ implements BytecodeGenerator {
private final Object BOOTSTRAP_LOCK = new Object();
@@ -21,7 +22,9 @@ class TypeCachingBytecodeGenerator extends ReferenceQueue implement
public TypeCachingBytecodeGenerator(BytecodeGenerator bytecodeGenerator, boolean weak) {
this.bytecodeGenerator = bytecodeGenerator;
- typeCache = new TypeCache.WithInlineExpunction(weak ? TypeCache.Sort.WEAK : TypeCache.Sort.SOFT);
+ typeCache =
+ new TypeCache.WithInlineExpunction(
+ weak ? TypeCache.Sort.WEAK : TypeCache.Sort.SOFT);
}
@SuppressWarnings("unchecked")
@@ -29,14 +32,21 @@ public TypeCachingBytecodeGenerator(BytecodeGenerator bytecodeGenerator, boolean
public Class mockClass(final MockFeatures params) {
try {
ClassLoader classLoader = params.mockedType.getClassLoader();
- return (Class) typeCache.findOrInsert(classLoader,
- new MockitoMockKey(params.mockedType, params.interfaces, params.serializableMode, params.stripAnnotations),
- new Callable>() {
- @Override
- public Class> call() throws Exception {
- return bytecodeGenerator.mockClass(params);
- }
- }, BOOTSTRAP_LOCK);
+ return (Class)
+ typeCache.findOrInsert(
+ classLoader,
+ new MockitoMockKey(
+ params.mockedType,
+ params.interfaces,
+ params.serializableMode,
+ params.stripAnnotations),
+ new Callable>() {
+ @Override
+ public Class> call() throws Exception {
+ return bytecodeGenerator.mockClass(params);
+ }
+ },
+ BOOTSTRAP_LOCK);
} catch (IllegalArgumentException exception) {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException) {
@@ -52,10 +62,11 @@ private static class MockitoMockKey extends TypeCache.SimpleKey {
private final SerializableMode serializableMode;
private final boolean stripAnnotations;
- private MockitoMockKey(Class> type,
- Set> additionalType,
- SerializableMode serializableMode,
- boolean stripAnnotations) {
+ private MockitoMockKey(
+ Class> type,
+ Set> additionalType,
+ SerializableMode serializableMode,
+ boolean stripAnnotations) {
super(type, additionalType);
this.serializableMode = serializableMode;
this.stripAnnotations = stripAnnotations;
@@ -68,7 +79,7 @@ public boolean equals(Object object) {
if (!super.equals(object)) return false;
MockitoMockKey that = (MockitoMockKey) object;
return stripAnnotations == that.stripAnnotations
- && serializableMode.equals(that.serializableMode);
+ && serializableMode.equals(that.serializableMode);
}
@Override
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.java b/src/main/java/org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.java
index 12e30db9b3..6c077cfd9e 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.java
@@ -11,10 +11,13 @@
public abstract class MockMethodDispatcher {
- private static final ConcurrentMap INSTANCE = new ConcurrentHashMap();
+ private static final ConcurrentMap INSTANCE =
+ new ConcurrentHashMap();
public static MockMethodDispatcher get(String identifier, Object mock) {
- if (mock == INSTANCE) { // Avoid endless loop if ConcurrentHashMap was redefined to check for being a mock.
+ if (mock
+ == INSTANCE) { // Avoid endless loop if ConcurrentHashMap was redefined to check for
+ // being a mock.
return null;
} else {
return INSTANCE.get(identifier);
@@ -25,7 +28,8 @@ public static void set(String identifier, MockMethodDispatcher dispatcher) {
INSTANCE.putIfAbsent(identifier, dispatcher);
}
- public abstract Callable> handle(Object instance, Method origin, Object[] arguments) throws Throwable;
+ public abstract Callable> handle(Object instance, Method origin, Object[] arguments)
+ throws Throwable;
public abstract boolean isMock(Object instance);
diff --git a/src/main/java/org/mockito/internal/creation/instance/ConstructorInstantiator.java b/src/main/java/org/mockito/internal/creation/instance/ConstructorInstantiator.java
index c3022c7d3b..94e12fa86a 100644
--- a/src/main/java/org/mockito/internal/creation/instance/ConstructorInstantiator.java
+++ b/src/main/java/org/mockito/internal/creation/instance/ConstructorInstantiator.java
@@ -25,6 +25,7 @@ public class ConstructorInstantiator implements Instantiator {
* If an outer inject exists, it would be the first ([0]) element of the {@link #constructorArgs} array.
*/
private final boolean hasOuterClassInstance;
+
private final Object[] constructorArgs;
public ConstructorInstantiator(boolean hasOuterClassInstance, Object... constructorArgs) {
@@ -60,17 +61,22 @@ private T withParams(Class cls, Object... params) {
}
@SuppressWarnings("unchecked")
- private static T invokeConstructor(Constructor> constructor, Object... params) throws java.lang.InstantiationException, IllegalAccessException, InvocationTargetException {
+ private static T invokeConstructor(Constructor> constructor, Object... params)
+ throws java.lang.InstantiationException, IllegalAccessException,
+ InvocationTargetException {
AccessibilityChanger accessibility = new AccessibilityChanger();
accessibility.enableAccess(constructor);
return (T) constructor.newInstance(params);
}
private InstantiationException paramsException(Class> cls, Exception e) {
- return new InstantiationException(join(
- "Unable to create instance of '" + cls.getSimpleName() + "'.",
- "Please ensure the target class has " + constructorArgsString() + " and executes cleanly.")
- , e);
+ return new InstantiationException(
+ join(
+ "Unable to create instance of '" + cls.getSimpleName() + "'.",
+ "Please ensure the target class has "
+ + constructorArgsString()
+ + " and executes cleanly."),
+ e);
}
private String constructorArgTypes() {
@@ -80,7 +86,8 @@ private String constructorArgTypes() {
}
String[] constructorArgTypes = new String[constructorArgs.length - argPos];
for (int i = argPos; i < constructorArgs.length; ++i) {
- constructorArgTypes[i - argPos] = constructorArgs[i] == null ? null : constructorArgs[i].getClass().getName();
+ constructorArgTypes[i - argPos] =
+ constructorArgs[i] == null ? null : constructorArgs[i].getClass().getName();
}
return Arrays.toString(constructorArgTypes);
}
@@ -91,9 +98,14 @@ private InstantiationException noMatchingConstructor(Class> cls) {
if (hasOuterClassInstance) {
outerInstanceHint = " and provided outer instance is correct";
}
- return new InstantiationException(join("Unable to create instance of '" + cls.getSimpleName() + "'.",
- "Please ensure that the target class has " + constructorString + outerInstanceHint + ".")
- , null);
+ return new InstantiationException(
+ join(
+ "Unable to create instance of '" + cls.getSimpleName() + "'.",
+ "Please ensure that the target class has "
+ + constructorString
+ + outerInstanceHint
+ + "."),
+ null);
}
private String constructorArgsString() {
@@ -101,19 +113,25 @@ private String constructorArgsString() {
if (constructorArgs.length == 0 || (hasOuterClassInstance && constructorArgs.length == 1)) {
constructorString = "a 0-arg constructor";
} else {
- constructorString = "a constructor that matches these argument types: " + constructorArgTypes();
+ constructorString =
+ "a constructor that matches these argument types: " + constructorArgTypes();
}
return constructorString;
}
- private InstantiationException multipleMatchingConstructors(Class> cls, List> constructors) {
- return new InstantiationException(join("Unable to create instance of '" + cls.getSimpleName() + "'.",
- "Multiple constructors could be matched to arguments of types " + constructorArgTypes() + ":",
- join("", " - ", constructors),
- "If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.",
- "Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.",
- "See https://github.com/mockito/mockito/issues/685"
- ), null);
+ private InstantiationException multipleMatchingConstructors(
+ Class> cls, List