diff --git a/build.gradle b/build.gradle index beafbf2693..18c35ea3dd 100644 --- a/build.gradle +++ b/build.gradle @@ -11,6 +11,8 @@ buildscript { //Using buildscript.classpath so that we can resolve shipkit from maven local, during local testing classpath 'org.shipkit:shipkit:2.1.6' + + classpath 'com.google.googlejavaformat:google-java-format:1.8' } } @@ -104,15 +106,23 @@ wrapper { } spotless { + // We run the check separately on Travis, so don't run this by default + enforceCheck = false + java { licenseHeaderFile rootProject.file('config/spotless/spotless.header') - removeUnusedImports() - trimTrailingWhitespace() - endWithNewline() - indentWithSpaces(4) + customLazyGroovy('google-java-format') { + com.google.googlejavaformat.java.JavaFormatterOptions options = new com.google.googlejavaformat.java.JavaFormatterOptions.Builder() + .style(com.google.googlejavaformat.java.JavaFormatterOptions.Style.AOSP) + .formatJavadoc(false) + .build() + com.google.googlejavaformat.java.Formatter formatter = new com.google.googlejavaformat.java.Formatter(options) + return { source -> formatter.formatSource(source) } + } - importOrder 'static java', 'static javax', 'static ', 'java', 'javax', '' + // This test contains emulation of same-line stubbings. The formatter would put them on a separate line. + targetExclude 'src/test/java/org/mockitousage/internal/junit/UnusedStubbingsFinderTest.java' } } diff --git a/src/main/java/org/mockito/Answers.java b/src/main/java/org/mockito/Answers.java index 5cbb1f71e6..cdfc1ca62c 100644 --- a/src/main/java/org/mockito/Answers.java +++ b/src/main/java/org/mockito/Answers.java @@ -24,7 +24,7 @@ * * This is not the full list of Answers available in Mockito. Some interesting answers can be found in org.mockito.stubbing.answers package. */ -public enum Answers implements Answer{ +public enum Answers implements Answer { /** * The default configured answer of every mock. * @@ -52,7 +52,6 @@ public enum Answers implements Answer{ */ RETURNS_MOCKS(new ReturnsMocks()), - /** * An answer that returns deep stubs (not mocks). * @@ -78,8 +77,7 @@ public enum Answers implements Answer{ * * @see org.mockito.Mockito#RETURNS_SELF */ - RETURNS_SELF(new TriesToReturnSelf()) - ; + RETURNS_SELF(new TriesToReturnSelf()); private final Answer implementation; diff --git a/src/main/java/org/mockito/ArgumentCaptor.java b/src/main/java/org/mockito/ArgumentCaptor.java index b8b0c1d932..12df16bb75 100644 --- a/src/main/java/org/mockito/ArgumentCaptor.java +++ b/src/main/java/org/mockito/ArgumentCaptor.java @@ -61,7 +61,6 @@ */ public class ArgumentCaptor { - private final CapturingMatcher capturingMatcher = new CapturingMatcher(); private final Class clazz; @@ -145,7 +144,7 @@ public List getAllValues() { * @param Type of object captured by the newly built ArgumentCaptor * @return A new ArgumentCaptor */ - public static ArgumentCaptor forClass(Class clazz) { + public static ArgumentCaptor forClass(Class clazz) { return new ArgumentCaptor(clazz); } } diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java index d449b65011..cb75e2cf16 100644 --- a/src/main/java/org/mockito/ArgumentMatchers.java +++ b/src/main/java/org/mockito/ArgumentMatchers.java @@ -775,8 +775,6 @@ public static Iterable anyIterableOf(Class clazz) { return anyIterable(); } - - /** * boolean argument that is equal to the given value. * @@ -907,8 +905,7 @@ public static short eq(short value) { */ public static T eq(T value) { reportMatcher(new Equals(value)); - if (value == null) - return null; + if (value == null) return null; return (T) Primitives.defaultValue(value.getClass()); } @@ -954,8 +951,7 @@ public static T refEq(T value, String... excludeFields) { */ public static T same(T value) { reportMatcher(new Same(value)); - if (value == null) - return null; + if (value == null) return null; return (T) Primitives.defaultValue(value.getClass()); } @@ -1086,7 +1082,6 @@ public static T isNotNull(Class clazz) { return notNull(clazz); } - /** * Argument that is either null or of the given type. * @@ -1099,7 +1094,7 @@ public static T isNotNull(Class clazz) { */ public static T nullable(Class clazz) { AdditionalMatchers.or(isNull(), isA(clazz)); - return (T) Primitives.defaultValue(clazz); + return (T) Primitives.defaultValue(clazz); } /** diff --git a/src/main/java/org/mockito/BDDMockito.java b/src/main/java/org/mockito/BDDMockito.java index b3ff0e7e5d..c4861ba4a9 100644 --- a/src/main/java/org/mockito/BDDMockito.java +++ b/src/main/java/org/mockito/BDDMockito.java @@ -127,9 +127,12 @@ public interface BDDMyOngoingStubbing { * See original {@link OngoingStubbing#thenThrow(Class, Class[])} * @since 2.1.0 */ - // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation - @SuppressWarnings ({"unchecked", "varargs"}) - BDDMyOngoingStubbing willThrow(Class throwableType, Class... throwableTypes); + // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array + // creation + @SuppressWarnings({"unchecked", "varargs"}) + BDDMyOngoingStubbing willThrow( + Class throwableType, + Class... throwableTypes); /** * See original {@link OngoingStubbing#thenCallRealMethod()} @@ -176,8 +179,11 @@ public BDDMyOngoingStubbing willThrow(Class throwableTyp return new BDDOngoingStubbingImpl(mockitoOngoingStubbing.thenThrow(throwableType)); } - public BDDMyOngoingStubbing willThrow(Class throwableType, Class... throwableTypes) { - return new BDDOngoingStubbingImpl(mockitoOngoingStubbing.thenThrow(throwableType, throwableTypes)); + public BDDMyOngoingStubbing willThrow( + Class throwableType, + Class... throwableTypes) { + return new BDDOngoingStubbingImpl( + mockitoOngoingStubbing.thenThrow(throwableType, throwableTypes)); } public BDDMyOngoingStubbing willCallRealMethod() { @@ -397,8 +403,10 @@ public interface BDDStubber { * See original {@link Stubber#doThrow(Class, Class[])} * @since 2.1.0 */ - @SuppressWarnings ({"unchecked", "varargs"}) - BDDStubber willThrow(Class toBeThrown, Class... nextToBeThrown); + @SuppressWarnings({"unchecked", "varargs"}) + BDDStubber willThrow( + Class toBeThrown, + Class... nextToBeThrown); /** * See original {@link Stubber#doCallRealMethod()} @@ -450,7 +458,8 @@ public BDDStubber willReturn(Object toBeReturned) { } public BDDStubber willReturn(Object toBeReturned, Object... nextToBeReturned) { - return new BDDStubberImpl(mockitoStubber.doReturn(toBeReturned).doReturn(nextToBeReturned)); + return new BDDStubberImpl( + mockitoStubber.doReturn(toBeReturned).doReturn(nextToBeReturned)); } public BDDStubber willThrow(Throwable... toBeThrown) { @@ -461,7 +470,9 @@ public BDDStubber willThrow(Class toBeThrown) { return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown)); } - public BDDStubber willThrow(Class toBeThrown, Class... nextToBeThrown) { + public BDDStubber willThrow( + Class toBeThrown, + Class... nextToBeThrown) { return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown, nextToBeThrown)); } @@ -490,7 +501,8 @@ public static BDDStubber willThrow(Class toBeThrown) { * see original {@link Mockito#doThrow(Class)} * @since 1.9.0 */ - public static BDDStubber willThrow(Class toBeThrown, Class... throwableTypes) { + public static BDDStubber willThrow( + Class toBeThrown, Class... throwableTypes) { return new BDDStubberImpl(Mockito.doThrow(toBeThrown, throwableTypes)); } diff --git a/src/main/java/org/mockito/CheckReturnValue.java b/src/main/java/org/mockito/CheckReturnValue.java index 0498c148a8..7bc3b257bf 100644 --- a/src/main/java/org/mockito/CheckReturnValue.java +++ b/src/main/java/org/mockito/CheckReturnValue.java @@ -9,7 +9,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * This annotation is not supposed to be used by Mockito end-users. Instead, we * use it to annotate methods for Static Analysis tools, including FindBugs and ErrorProne. @@ -21,12 +20,6 @@ * @see ErrorProne check * @since 2.11.4 */ -@Target({ - ElementType.CONSTRUCTOR, - ElementType.METHOD, - ElementType.PACKAGE, - ElementType.TYPE -}) +@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) -public @interface CheckReturnValue { -} +public @interface CheckReturnValue {} diff --git a/src/main/java/org/mockito/InOrder.java b/src/main/java/org/mockito/InOrder.java index b709bd4f1f..02ea019c01 100644 --- a/src/main/java/org/mockito/InOrder.java +++ b/src/main/java/org/mockito/InOrder.java @@ -62,7 +62,6 @@ public interface InOrder { */ T verify(T mock, VerificationMode mode); - /** * Verifies that no more interactions happened in order. * Different from {@link Mockito#verifyNoMoreInteractions(Object...)} because the order of verification matters. diff --git a/src/main/java/org/mockito/Incubating.java b/src/main/java/org/mockito/Incubating.java index 2cdfaddf41..adf011abc7 100644 --- a/src/main/java/org/mockito/Incubating.java +++ b/src/main/java/org/mockito/Incubating.java @@ -25,5 +25,4 @@ */ @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface Incubating { -} +public @interface Incubating {} diff --git a/src/main/java/org/mockito/Matchers.java b/src/main/java/org/mockito/Matchers.java index 807cca1993..f5e70bb658 100644 --- a/src/main/java/org/mockito/Matchers.java +++ b/src/main/java/org/mockito/Matchers.java @@ -9,5 +9,4 @@ * org.hamcrest.Matchers class. This class will likely be removed in version 4.0. */ @Deprecated -public class Matchers extends ArgumentMatchers { -} +public class Matchers extends ArgumentMatchers {} diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 01f0024ff6..07a5dfcb56 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -275,7 +275,7 @@ * If you are using argument matchers, all arguments have to be provided * by matchers. *

- The following example shows verification but the same applies to stubbing: + * The following example shows verification but the same applies to stubbing: * *


  *   verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
@@ -1834,9 +1834,7 @@ public static  T mock(Class classToMock) {
      */
     @CheckReturnValue
     public static  T mock(Class classToMock, String name) {
-        return mock(classToMock, withSettings()
-                .name(name)
-                .defaultAnswer(RETURNS_DEFAULTS));
+        return mock(classToMock, withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS));
     }
 
     /**
@@ -1989,9 +1987,9 @@ public static  T mock(Class classToMock, MockSettings mockSettings) {
      */
     @CheckReturnValue
     public static  T spy(T object) {
-        return MOCKITO_CORE.mock((Class) object.getClass(), withSettings()
-                .spiedInstance(object)
-                .defaultAnswer(CALLS_REAL_METHODS));
+        return MOCKITO_CORE.mock(
+                (Class) object.getClass(),
+                withSettings().spiedInstance(object).defaultAnswer(CALLS_REAL_METHODS));
     }
 
     /**
@@ -2024,9 +2022,8 @@ public static  T spy(T object) {
     @Incubating
     @CheckReturnValue
     public static  T spy(Class classToSpy) {
-        return MOCKITO_CORE.mock(classToSpy, withSettings()
-                .useConstructor()
-                .defaultAnswer(CALLS_REAL_METHODS));
+        return MOCKITO_CORE.mock(
+                classToSpy, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
     }
 
     /**
@@ -2178,7 +2175,7 @@ public static  T verify(T mock, VerificationMode mode) {
      * @param  The Type of the mocks
      * @param mocks to be reset
      */
-    public static  void reset(T ... mocks) {
+    public static  void reset(T... mocks) {
         MOCKITO_CORE.reset(mocks);
     }
 
@@ -2193,7 +2190,7 @@ public static  void reset(T ... mocks) {
      * @param  The type of the mocks
      * @param mocks The mocks to clear the invocations for
      */
-    public static  void clearInvocations(T ... mocks) {
+    public static  void clearInvocations(T... mocks) {
         MOCKITO_CORE.clearInvocations(mocks);
     }
 
@@ -2339,14 +2336,15 @@ public static Stubber doThrow(Class toBeThrown) {
      * @return stubber - to select a method for stubbing
      * @since 2.1.0
      */
-    // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
-    @SuppressWarnings ({"unchecked", "varargs"})
+    // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array
+    // creation
+    @SuppressWarnings({"unchecked", "varargs"})
     @CheckReturnValue
-    public static Stubber doThrow(Class toBeThrown, Class... toBeThrownNext) {
+    public static Stubber doThrow(
+            Class toBeThrown, Class... toBeThrownNext) {
         return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
     }
 
-
     /**
      * Use doCallRealMethod() when you want to call the real implementation of a method.
      * 

@@ -2794,8 +2792,8 @@ public static VerificationMode atMost(int maxNumberOfInvocations) { * @return verification mode */ @CheckReturnValue - public static VerificationMode calls( int wantedNumberOfInvocations ){ - return VerificationModeFactory.calls( wantedNumberOfInvocations ); + public static VerificationMode calls(int wantedNumberOfInvocations) { + return VerificationModeFactory.calls(wantedNumberOfInvocations); } /** diff --git a/src/main/java/org/mockito/MockitoAnnotations.java b/src/main/java/org/mockito/MockitoAnnotations.java index 9199aaa9af..ba355e702f 100644 --- a/src/main/java/org/mockito/MockitoAnnotations.java +++ b/src/main/java/org/mockito/MockitoAnnotations.java @@ -61,10 +61,12 @@ public class MockitoAnnotations { */ public static void initMocks(Object testClass) { if (testClass == null) { - throw new MockitoException("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class"); + throw new MockitoException( + "testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class"); } - AnnotationEngine annotationEngine = new GlobalConfiguration().tryGetPluginAnnotationEngine(); + AnnotationEngine annotationEngine = + new GlobalConfiguration().tryGetPluginAnnotationEngine(); annotationEngine.process(testClass.getClass(), testClass); } } diff --git a/src/main/java/org/mockito/MockitoDebugger.java b/src/main/java/org/mockito/MockitoDebugger.java index 90c7e9ab4b..7ee2229969 100644 --- a/src/main/java/org/mockito/MockitoDebugger.java +++ b/src/main/java/org/mockito/MockitoDebugger.java @@ -16,5 +16,5 @@ public interface MockitoDebugger { * An instance of {@code MockingDetails} can be retrieved via {@link Mockito#mockingDetails(Object)}. */ @Deprecated - String printInvocations(Object ... mocks); + String printInvocations(Object... mocks); } diff --git a/src/main/java/org/mockito/NotExtensible.java b/src/main/java/org/mockito/NotExtensible.java index de67a0a14e..39191ac481 100644 --- a/src/main/java/org/mockito/NotExtensible.java +++ b/src/main/java/org/mockito/NotExtensible.java @@ -26,5 +26,4 @@ */ @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface NotExtensible { -} +public @interface NotExtensible {} diff --git a/src/main/java/org/mockito/Spy.java b/src/main/java/org/mockito/Spy.java index 2f9825f146..b164c8f590 100644 --- a/src/main/java/org/mockito/Spy.java +++ b/src/main/java/org/mockito/Spy.java @@ -105,4 +105,4 @@ @Retention(RUNTIME) @Target(FIELD) @Documented -public @interface Spy { } +public @interface Spy {} diff --git a/src/main/java/org/mockito/configuration/AnnotationEngine.java b/src/main/java/org/mockito/configuration/AnnotationEngine.java index ad08ae345e..d4f8fb0b1f 100644 --- a/src/main/java/org/mockito/configuration/AnnotationEngine.java +++ b/src/main/java/org/mockito/configuration/AnnotationEngine.java @@ -19,10 +19,9 @@ * Note that if it exists on the classpath both a class org.mockito.configuration.MockitoConfiguration * and a file mockito-extensions/org.mockito.plugins.AnnotationEngine then the implementation of * org.mockito.configuration.MockitoConfiguration will be chosen instead of the one in the file. - + * * @deprecated Please use {@link org.mockito.plugins.AnnotationEngine} instead, * this interface will probably be removed in mockito 4. */ @Deprecated -public interface AnnotationEngine extends org.mockito.plugins.AnnotationEngine { -} +public interface AnnotationEngine extends org.mockito.plugins.AnnotationEngine {} diff --git a/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java b/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java index cad13e7577..59fc335e69 100644 --- a/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java +++ b/src/main/java/org/mockito/configuration/DefaultMockitoConfiguration.java @@ -41,6 +41,4 @@ public boolean cleansStackTrace() { public boolean enableClassCache() { return true; } - - } diff --git a/src/main/java/org/mockito/creation/instance/Instantiator.java b/src/main/java/org/mockito/creation/instance/Instantiator.java index 9ce37b5fdd..f634844f0e 100644 --- a/src/main/java/org/mockito/creation/instance/Instantiator.java +++ b/src/main/java/org/mockito/creation/instance/Instantiator.java @@ -18,5 +18,4 @@ public interface Instantiator { * @since 2.15.4 */ T newInstance(Class cls) throws InstantiationException; - } diff --git a/src/main/java/org/mockito/exceptions/base/MockitoException.java b/src/main/java/org/mockito/exceptions/base/MockitoException.java index 24294e95a1..9293870771 100644 --- a/src/main/java/org/mockito/exceptions/base/MockitoException.java +++ b/src/main/java/org/mockito/exceptions/base/MockitoException.java @@ -6,7 +6,6 @@ import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter; - /** * Raised by mockito to emit an error either due to Mockito, or due to the User. * All exception classes that inherit from this class will have the stack trace filtered. diff --git a/src/main/java/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java b/src/main/java/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java index 73e364e04a..94da89d4c5 100644 --- a/src/main/java/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java +++ b/src/main/java/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java @@ -9,7 +9,6 @@ import junit.framework.ComparisonFailure; import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter; - public class ArgumentsAreDifferent extends ComparisonFailure { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java b/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java index 989e6eb70d..281052026a 100644 --- a/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java +++ b/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java @@ -9,7 +9,6 @@ import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter; import org.opentest4j.AssertionFailedError; - public class ArgumentsAreDifferent extends AssertionFailedError { private static final long serialVersionUID = 1L; diff --git a/src/main/java/org/mockito/hamcrest/MockitoHamcrest.java b/src/main/java/org/mockito/hamcrest/MockitoHamcrest.java index d4b4304033..8b2d080ce8 100644 --- a/src/main/java/org/mockito/hamcrest/MockitoHamcrest.java +++ b/src/main/java/org/mockito/hamcrest/MockitoHamcrest.java @@ -59,7 +59,7 @@ public class MockitoHamcrest { @SuppressWarnings("unchecked") public static T argThat(Matcher matcher) { reportMatcher(matcher); - return (T) defaultValue(genericTypeOfMatcher(matcher.getClass())); + return (T) defaultValue(genericTypeOfMatcher(matcher.getClass())); } /** @@ -175,6 +175,8 @@ public static double doubleThat(Matcher matcher) { } private static void reportMatcher(Matcher matcher) { - mockingProgress().getArgumentMatcherStorage().reportMatcher(new HamcrestArgumentMatcher(matcher)); + mockingProgress() + .getArgumentMatcherStorage() + .reportMatcher(new HamcrestArgumentMatcher(matcher)); } } diff --git a/src/main/java/org/mockito/internal/InOrderImpl.java b/src/main/java/org/mockito/internal/InOrderImpl.java index 45aa95aa99..15e861b9f2 100644 --- a/src/main/java/org/mockito/internal/InOrderImpl.java +++ b/src/main/java/org/mockito/internal/InOrderImpl.java @@ -47,9 +47,11 @@ public T verify(T mock, VerificationMode mode) { throw inOrderRequiresFamiliarMock(); } if (mode instanceof VerificationWrapper) { - return mockitoCore.verify(mock, new VerificationWrapperInOrderWrapper((VerificationWrapper) mode, this)); - } else if (!(mode instanceof VerificationInOrderMode)) { - throw new MockitoException(mode.getClass().getSimpleName() + " is not implemented to work with InOrder"); + return mockitoCore.verify( + mock, new VerificationWrapperInOrderWrapper((VerificationWrapper) mode, this)); + } else if (!(mode instanceof VerificationInOrderMode)) { + throw new MockitoException( + mode.getClass().getSimpleName() + " is not implemented to work with InOrder"); } return mockitoCore.verify(mock, new InOrderWrapper((VerificationInOrderMode) mode, this)); } diff --git a/src/main/java/org/mockito/internal/MockitoCore.java b/src/main/java/org/mockito/internal/MockitoCore.java index d9f6312a1c..4353e0fbda 100644 --- a/src/main/java/org/mockito/internal/MockitoCore.java +++ b/src/main/java/org/mockito/internal/MockitoCore.java @@ -46,7 +46,6 @@ import org.mockito.stubbing.Stubber; import org.mockito.verification.VerificationMode; - @SuppressWarnings("unchecked") public class MockitoCore { @@ -56,7 +55,11 @@ public boolean isTypeMockable(Class typeToMock) { public T mock(Class typeToMock, MockSettings settings) { if (!MockSettingsImpl.class.isInstance(settings)) { - throw new IllegalArgumentException("Unexpected implementation of '" + settings.getClass().getCanonicalName() + "'\n" + "At the moment, you cannot provide your own implementations of that class."); + throw new IllegalArgumentException( + "Unexpected implementation of '" + + settings.getClass().getCanonicalName() + + "'\n" + + "At the moment, you cannot provide your own implementations of that class."); } MockSettingsImpl impl = MockSettingsImpl.class.cast(settings); MockCreationSettings creationSettings = impl.build(typeToMock); @@ -87,12 +90,17 @@ public T verify(T mock, VerificationMode mode) { } assertNotStubOnlyMock(mock); MockHandler handler = mockingDetails.getMockHandler(); - mock = (T) VerificationStartedNotifier.notifyVerificationStarted( - handler.getMockSettings().getVerificationStartedListeners(), mockingDetails); + mock = + (T) + VerificationStartedNotifier.notifyVerificationStarted( + handler.getMockSettings().getVerificationStartedListeners(), + mockingDetails); MockingProgress mockingProgress = mockingProgress(); VerificationMode actualMode = mockingProgress.maybeVerifyLazily(mode); - mockingProgress.verificationStarted(new MockAwareVerificationMode(mock, actualMode, mockingProgress.verificationListeners())); + mockingProgress.verificationStarted( + new MockAwareVerificationMode( + mock, actualMode, mockingProgress.verificationListeners())); return mock; } @@ -156,7 +164,9 @@ public void verifyNoInteractions(Object... mocks) { public void verifyNoMoreInteractionsInOrder(List mocks, InOrderContext inOrderContext) { mockingProgress().validateState(); - VerificationDataInOrder data = new VerificationDataInOrderImpl(inOrderContext, VerifiableInvocationsFinder.find(mocks), null); + VerificationDataInOrder data = + new VerificationDataInOrderImpl( + inOrderContext, VerifiableInvocationsFinder.find(mocks), null); VerificationModeFactory.noMoreInteractions().verifyInOrder(data); } @@ -209,7 +219,8 @@ public void validateMockitoUsage() { * @return last invocation */ public Invocation getLastInvocation() { - OngoingStubbingImpl ongoingStubbing = ((OngoingStubbingImpl) mockingProgress().pullOngoingStubbing()); + OngoingStubbingImpl ongoingStubbing = + ((OngoingStubbingImpl) mockingProgress().pullOngoingStubbing()); List allInvocations = ongoingStubbing.getRegisteredInvocations(); return allInvocations.get(allInvocations.size() - 1); } diff --git a/src/main/java/org/mockito/internal/configuration/CaptorAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/CaptorAnnotationProcessor.java index 578defcce4..016f3af22d 100644 --- a/src/main/java/org/mockito/internal/configuration/CaptorAnnotationProcessor.java +++ b/src/main/java/org/mockito/internal/configuration/CaptorAnnotationProcessor.java @@ -18,9 +18,12 @@ public class CaptorAnnotationProcessor implements FieldAnnotationProcessor type = field.getType(); if (!ArgumentCaptor.class.isAssignableFrom(type)) { - throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '" - + field.getName() + "' has wrong type\n" - + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class."); + throw new MockitoException( + "@Captor field must be of the type ArgumentCaptor.\n" + + "Field: '" + + field.getName() + + "' has wrong type\n" + + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class."); } Class cls = new GenericMaster().getGenericType(field); return ArgumentCaptor.forClass(cls); diff --git a/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java b/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java index 67b20405cb..8fc47b425f 100644 --- a/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java +++ b/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java @@ -8,7 +8,6 @@ import org.mockito.exceptions.misusing.MockitoConfigurationException; import org.mockito.plugins.MockMaker; - /** * Loads configuration or extension points available in the classpath. * @@ -47,7 +46,8 @@ */ public class ClassPathLoader { - public static final String MOCKITO_CONFIGURATION_CLASS_NAME = "org.mockito.configuration.MockitoConfiguration"; + public static final String MOCKITO_CONFIGURATION_CLASS_NAME = + "org.mockito.configuration.MockitoConfiguration"; /** * @return configuration loaded from classpath or null @@ -59,16 +59,24 @@ public IMockitoConfiguration loadConfiguration() { try { configClass = Class.forName(MOCKITO_CONFIGURATION_CLASS_NAME); } catch (ClassNotFoundException e) { - //that's ok, it means there is no global config, using default one. + // that's ok, it means there is no global config, using default one. return null; } try { return (IMockitoConfiguration) configClass.newInstance(); } catch (ClassCastException e) { - throw new MockitoConfigurationException("MockitoConfiguration class must implement " + IMockitoConfiguration.class.getName() + " interface.", e); + throw new MockitoConfigurationException( + "MockitoConfiguration class must implement " + + IMockitoConfiguration.class.getName() + + " interface.", + e); } catch (Exception e) { - throw new MockitoConfigurationException("Unable to instantiate " + MOCKITO_CONFIGURATION_CLASS_NAME +" class. Does it have a safe, no-arg constructor?", e); + throw new MockitoConfigurationException( + "Unable to instantiate " + + MOCKITO_CONFIGURATION_CLASS_NAME + + " class. Does it have a safe, no-arg constructor?", + e); } } } diff --git a/src/main/java/org/mockito/internal/configuration/DefaultInjectionEngine.java b/src/main/java/org/mockito/internal/configuration/DefaultInjectionEngine.java index e5e98a1a20..f6b35959b6 100644 --- a/src/main/java/org/mockito/internal/configuration/DefaultInjectionEngine.java +++ b/src/main/java/org/mockito/internal/configuration/DefaultInjectionEngine.java @@ -16,7 +16,8 @@ */ public class DefaultInjectionEngine { - public void injectMocksOnFields(Set needingInjection, Set mocks, Object testClassInstance) { + public void injectMocksOnFields( + Set needingInjection, Set mocks, Object testClassInstance) { MockInjection.onFields(needingInjection, testClassInstance) .withMocks(mocks) .tryConstructorInjection() @@ -24,5 +25,4 @@ public void injectMocksOnFields(Set needingInjection, Set mocks, .handleSpyAnnotation() .apply(); } - } diff --git a/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java b/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java index b4312af50c..120682ddb2 100644 --- a/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java +++ b/src/main/java/org/mockito/internal/configuration/GlobalConfiguration.java @@ -18,15 +18,16 @@ public class GlobalConfiguration implements IMockitoConfiguration, Serializable { private static final long serialVersionUID = -2860353062105505938L; - private static final ThreadLocal GLOBAL_CONFIGURATION = new ThreadLocal(); + private static final ThreadLocal GLOBAL_CONFIGURATION = + new ThreadLocal(); - //back door for testing + // back door for testing IMockitoConfiguration getIt() { return GLOBAL_CONFIGURATION.get(); } public GlobalConfiguration() { - //Configuration should be loaded only once but I cannot really test it + // Configuration should be loaded only once but I cannot really test it if (GLOBAL_CONFIGURATION.get() == null) { GLOBAL_CONFIGURATION.set(createConfig()); } @@ -58,8 +59,6 @@ public org.mockito.plugins.AnnotationEngine tryGetPluginAnnotationEngine() { return configuration.getAnnotationEngine(); } - - public boolean cleansStackTrace() { return GLOBAL_CONFIGURATION.get().cleansStackTrace(); } diff --git a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java index 5bcc00e384..9b1c3767d0 100644 --- a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java @@ -27,8 +27,11 @@ * @see MockitoAnnotations */ @SuppressWarnings("unchecked") -public class IndependentAnnotationEngine implements AnnotationEngine, org.mockito.configuration.AnnotationEngine { - private final Map, FieldAnnotationProcessor> annotationProcessorMap = new HashMap, FieldAnnotationProcessor>(); +public class IndependentAnnotationEngine + implements AnnotationEngine, org.mockito.configuration.AnnotationEngine { + private final Map, FieldAnnotationProcessor> + annotationProcessorMap = + new HashMap, FieldAnnotationProcessor>(); public IndependentAnnotationEngine() { registerAnnotationProcessor(Mock.class, new MockAnnotationProcessor()); @@ -41,7 +44,8 @@ private Object createMockFor(Annotation annotation, Field field) { private FieldAnnotationProcessor forAnnotation(A annotation) { if (annotationProcessorMap.containsKey(annotation.annotationType())) { - return (FieldAnnotationProcessor) annotationProcessorMap.get(annotation.annotationType()); + return (FieldAnnotationProcessor) + annotationProcessorMap.get(annotation.annotationType()); } return new FieldAnnotationProcessor() { public Object process(A annotation, Field field) { @@ -50,7 +54,8 @@ public Object process(A annotation, Field field) { }; } - private void registerAnnotationProcessor(Class annotationClass, FieldAnnotationProcessor fieldAnnotationProcessor) { + private void registerAnnotationProcessor( + Class annotationClass, FieldAnnotationProcessor fieldAnnotationProcessor) { annotationProcessorMap.put(annotationClass, fieldAnnotationProcessor); } @@ -59,16 +64,20 @@ public void process(Class clazz, Object testInstance) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { boolean alreadyAssigned = false; - for(Annotation annotation : field.getAnnotations()) { + for (Annotation annotation : field.getAnnotations()) { Object mock = createMockFor(annotation, field); if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); alreadyAssigned = true; try { - setField(testInstance, field,mock); + setField(testInstance, field, mock); } catch (Exception e) { - throw new MockitoException("Problems setting field " + field.getName() + " annotated with " - + annotation, e); + throw new MockitoException( + "Problems setting field " + + field.getName() + + " annotated with " + + annotation, + e); } } } @@ -80,5 +89,4 @@ void throwIfAlreadyAssigned(Field field, boolean alreadyAssigned) { throw moreThanOneAnnotationNotAllowed(field.getName()); } } - } diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java index 1fba127ef0..ccc7ae4d85 100644 --- a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java @@ -18,7 +18,8 @@ /** * See {@link MockitoAnnotations} */ -public class InjectingAnnotationEngine implements AnnotationEngine, org.mockito.configuration.AnnotationEngine { +public class InjectingAnnotationEngine + implements AnnotationEngine, org.mockito.configuration.AnnotationEngine { private final AnnotationEngine delegate = new IndependentAnnotationEngine(); private final AnnotationEngine spyAnnotationEngine = new SpyAnnotationEngine(); @@ -54,16 +55,15 @@ private void processInjectMocks(final Class clazz, final Object testInstance) private void processIndependentAnnotations(final Class clazz, final Object testInstance) { Class classContext = clazz; while (classContext != Object.class) { - //this will create @Mocks, @Captors, etc: + // this will create @Mocks, @Captors, etc: delegate.process(classContext, testInstance); - //this will create @Spies: + // this will create @Spies: spyAnnotationEngine.process(classContext, testInstance); classContext = classContext.getSuperclass(); } } - /** * Initializes mock/spies dependencies for objects annotated with * @InjectMocks for given testClassInstance. @@ -85,11 +85,13 @@ public void injectMocks(final Object testClassInstance) { clazz = clazz.getSuperclass(); } - new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance); - } - - protected void onInjection(Object testClassInstance, Class clazz, Set mockDependentFields, Set mocks) { - + new DefaultInjectionEngine() + .injectMocksOnFields(mockDependentFields, mocks, testClassInstance); } + protected void onInjection( + Object testClassInstance, + Class clazz, + Set mockDependentFields, + Set 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 annotation, - Field field, - Class... undesiredAnnotations) { + // TODO duplicated elsewhere + private static void assertNoIncompatibleAnnotations( + Class annotation, + Field field, + Class... undesiredAnnotations) { for (Class 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... annotations) { + private static void assertNoAnnotations( + Field field, Class... annotations) { for (Class 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 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 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 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 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 matcher) { + public SubclassBytecodeGenerator( + Implementation readReplace, ElementMatcher matcher) { this(new SubclassInjectionLoader(), readReplace, matcher); } - protected SubclassBytecodeGenerator(SubclassLoader loader, Implementation readReplace, ElementMatcher matcher) { + protected SubclassBytecodeGenerator( + SubclassLoader loader, + Implementation readReplace, + ElementMatcher matcher) { this.loader = loader; this.readReplace = readReplace; this.matcher = matcher; @@ -80,28 +84,40 @@ protected SubclassBytecodeGenerator(SubclassLoader loader, Implementation readRe @Override public Class 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 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 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> 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 static boolean paramsMatch(Class[] types, Object[] params) { @@ -125,8 +143,10 @@ private static boolean paramsMatch(Class[] types, Object[] params) { if (types[i].isPrimitive()) { return false; } - } else if ((!types[i].isPrimitive() && !types[i].isInstance(params[i])) || - (types[i].isPrimitive() && !types[i].equals(Primitives.primitiveTypeOf(params[i].getClass())))) { + } else if ((!types[i].isPrimitive() && !types[i].isInstance(params[i])) + || (types[i].isPrimitive() + && !types[i].equals( + Primitives.primitiveTypeOf(params[i].getClass())))) { return false; } } @@ -156,7 +176,8 @@ private static boolean paramsMatch(Class[] types, Object[] params) { * @param matchingConstructors A list of equivalently best matching constructors found so far * @param constructor The constructor to be evaluated against this list */ - private void evaluateConstructor(List> matchingConstructors, Constructor constructor) { + private void evaluateConstructor( + List> matchingConstructors, Constructor constructor) { boolean newHasBetterParam = false; boolean existingHasBetterParam = false; diff --git a/src/main/java/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java b/src/main/java/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java index 9c414f3f91..026192ea6b 100644 --- a/src/main/java/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java +++ b/src/main/java/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java @@ -10,11 +10,12 @@ public class DefaultInstantiatorProvider implements InstantiatorProvider2 { - private final static Instantiator INSTANCE = new ObjenesisInstantiator(); + private static final Instantiator INSTANCE = new ObjenesisInstantiator(); public Instantiator getInstantiator(MockCreationSettings settings) { if (settings != null && settings.getConstructorArgs() != null) { - return new ConstructorInstantiator(settings.getOuterClassInstance() != null, settings.getConstructorArgs()); + return new ConstructorInstantiator( + settings.getOuterClassInstance() != null, settings.getConstructorArgs()); } else { return INSTANCE; } diff --git a/src/main/java/org/mockito/internal/creation/instance/Instantiator.java b/src/main/java/org/mockito/internal/creation/instance/Instantiator.java index 85b6b3dcdf..3c19e5b97b 100644 --- a/src/main/java/org/mockito/internal/creation/instance/Instantiator.java +++ b/src/main/java/org/mockito/internal/creation/instance/Instantiator.java @@ -18,5 +18,4 @@ public interface Instantiator { * Creates instance of given class */ T newInstance(Class cls) throws InstantiationException; - } diff --git a/src/main/java/org/mockito/internal/creation/instance/ObjenesisInstantiator.java b/src/main/java/org/mockito/internal/creation/instance/ObjenesisInstantiator.java index 7e41f683ac..c72e7fa4d5 100644 --- a/src/main/java/org/mockito/internal/creation/instance/ObjenesisInstantiator.java +++ b/src/main/java/org/mockito/internal/creation/instance/ObjenesisInstantiator.java @@ -10,10 +10,12 @@ class ObjenesisInstantiator implements Instantiator { - //TODO: in order to provide decent exception message when objenesis is not found, - //have a constructor in this class that tries to instantiate ObjenesisStd and if it fails then show decent exception that dependency is missing - //TODO: for the same reason catch and give better feedback when hamcrest core is not found. - private final ObjenesisStd objenesis = new ObjenesisStd(new GlobalConfiguration().enableClassCache()); + // TODO: in order to provide decent exception message when objenesis is not found, + // have a constructor in this class that tries to instantiate ObjenesisStd and if it fails then + // show decent exception that dependency is missing + // TODO: for the same reason catch and give better feedback when hamcrest core is not found. + private final ObjenesisStd objenesis = + new ObjenesisStd(new GlobalConfiguration().enableClassCache()); public T newInstance(Class cls) { return objenesis.newInstance(cls); diff --git a/src/main/java/org/mockito/internal/creation/settings/CreationSettings.java b/src/main/java/org/mockito/internal/creation/settings/CreationSettings.java index 6501c95393..f3dd7c82f2 100644 --- a/src/main/java/org/mockito/internal/creation/settings/CreationSettings.java +++ b/src/main/java/org/mockito/internal/creation/settings/CreationSettings.java @@ -32,11 +32,15 @@ public class CreationSettings implements MockCreationSettings, Serializabl protected SerializableMode serializableMode = SerializableMode.NONE; protected List invocationListeners = new ArrayList(); - //Other listeners in this class may also need concurrency-safe implementation. However, no issue was reported about it. - // If we do it, we need to understand usage patterns and choose the right concurrent implementation. - protected List stubbingLookupListeners = new CopyOnWriteArrayList(); - - protected List verificationStartedListeners = new LinkedList(); + // Other listeners in this class may also need concurrency-safe implementation. However, no + // issue was reported about it. + // If we do it, we need to understand usage patterns and choose the right concurrent + // implementation. + protected List stubbingLookupListeners = + new CopyOnWriteArrayList(); + + protected List verificationStartedListeners = + new LinkedList(); protected boolean stubOnly; protected boolean stripAnnotations; private boolean useConstructor; @@ -48,7 +52,7 @@ public CreationSettings() {} @SuppressWarnings("unchecked") public CreationSettings(CreationSettings copy) { - //TODO can we have a reflection test here? We had a couple of bugs here in the past. + // TODO can we have a reflection test here? We had a couple of bugs here in the past. this.typeToMock = copy.typeToMock; this.extraInterfaces = copy.extraInterfaces; this.name = copy.name; diff --git a/src/main/java/org/mockito/internal/creation/util/MockitoMethodProxy.java b/src/main/java/org/mockito/internal/creation/util/MockitoMethodProxy.java index 585a0c1b73..21642e4c0b 100644 --- a/src/main/java/org/mockito/internal/creation/util/MockitoMethodProxy.java +++ b/src/main/java/org/mockito/internal/creation/util/MockitoMethodProxy.java @@ -4,7 +4,7 @@ */ package org.mockito.internal.creation.util; -//TODO SF Replace with RealMethod and get rid of (possibly). +// TODO SF Replace with RealMethod and get rid of (possibly). public interface MockitoMethodProxy { Object invokeSuper(Object target, Object[] arguments); } diff --git a/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java b/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java index a643190cf0..4c53847e1b 100644 --- a/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java +++ b/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java @@ -26,7 +26,7 @@ public String printInvocations(Object mock) { StringBuilder sb = new StringBuilder(); int x = 1; - for(Invocation i:invocations) { + for (Invocation i : invocations) { if (x == 1) { sb.append("[Mockito] Interactions of: ").append(mock).append("\n"); } @@ -37,11 +37,14 @@ public String printInvocations(Object mock) { } } - LinkedList unused = ListUtil.filter(stubbings, new ListUtil.Filter() { - public boolean isOut(Stubbing s) { - return s.wasUsed(); - } - }); + LinkedList unused = + ListUtil.filter( + stubbings, + new ListUtil.Filter() { + public boolean isOut(Stubbing s) { + return s.wasUsed(); + } + }); if (unused.isEmpty()) { return sb.toString(); @@ -49,7 +52,7 @@ public boolean isOut(Stubbing s) { sb.append("[Mockito] Unused stubbings of: ").append(mock).append("\n"); x = 1; - for(Stubbing s:stubbings) { + for (Stubbing s : stubbings) { sb.append(" ").append(x++).append(". ").append(s.getInvocation()).append("\n"); sb.append(" - stubbed ").append(s.getInvocation().getLocation()).append("\n"); } diff --git a/src/main/java/org/mockito/internal/debugging/Localized.java b/src/main/java/org/mockito/internal/debugging/Localized.java index 0588042086..d1d7912dc4 100644 --- a/src/main/java/org/mockito/internal/debugging/Localized.java +++ b/src/main/java/org/mockito/internal/debugging/Localized.java @@ -4,7 +4,6 @@ */ package org.mockito.internal.debugging; - import org.mockito.invocation.Location; public class Localized { diff --git a/src/main/java/org/mockito/internal/debugging/LocationImpl.java b/src/main/java/org/mockito/internal/debugging/LocationImpl.java index 399ecbcf4f..d307c09f4c 100644 --- a/src/main/java/org/mockito/internal/debugging/LocationImpl.java +++ b/src/main/java/org/mockito/internal/debugging/LocationImpl.java @@ -30,7 +30,8 @@ public LocationImpl(StackTraceFilter stackTraceFilter) { this(stackTraceFilter, new Throwable(), false); } - private LocationImpl(StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) { + private LocationImpl( + StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) { computeStackTraceInformation(stackTraceFilter, stackTraceHolder, isInline); } @@ -45,7 +46,7 @@ public String toString() { * mocks. */ private void computeStackTraceInformation( - StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) { + StackTraceFilter stackTraceFilter, Throwable stackTraceHolder, boolean isInline) { StackTraceElement filtered = stackTraceFilter.filterFirst(stackTraceHolder, isInline); // there are corner cases where exception can have a null or empty stack trace diff --git a/src/main/java/org/mockito/internal/debugging/LoggingListener.java b/src/main/java/org/mockito/internal/debugging/LoggingListener.java index 4a21a863aa..73bc2430c8 100644 --- a/src/main/java/org/mockito/internal/debugging/LoggingListener.java +++ b/src/main/java/org/mockito/internal/debugging/LoggingListener.java @@ -24,15 +24,16 @@ public LoggingListener(boolean warnAboutUnstubbed) { } public void foundStubCalledWithDifferentArgs(Invocation unused, InvocationMatcher unstubbed) { - //TODO there is not good reason we should get Invocation and InvocationMatcher here + // TODO there is not good reason we should get Invocation and InvocationMatcher here // we should pass 2 InvocationMatchers and testing is easier - // it's also confusing that unstubbed invocation is passed as InvocationMatcher (should be rather Invocation) + // it's also confusing that unstubbed invocation is passed as InvocationMatcher (should be + // rather Invocation) - //this information comes in pairs + // this information comes in pairs String index = Integer.toString(indexOfNextPair(argMismatchStubs.size())); - //making sure indentation is correct + // making sure indentation is correct String padding = index.replaceAll("\\d", " "); - argMismatchStubs.add(index + ". Stubbed " + unused.getLocation()); + argMismatchStubs.add(index + ". Stubbed " + unused.getLocation()); argMismatchStubs.add(padding + " Invoked " + unstubbed.getInvocation().getLocation()); } @@ -46,7 +47,8 @@ public void foundUnusedStub(Invocation unused) { public void foundUnstubbed(InvocationMatcher unstubbed) { if (warnAboutUnstubbed) { - unstubbedCalls.add((unstubbedCalls.size() + 1) + ". " + unstubbed.getInvocation().getLocation()); + unstubbedCalls.add( + (unstubbedCalls.size() + 1) + ". " + unstubbed.getInvocation().getLocation()); } } @@ -56,11 +58,13 @@ public String getStubbingInfo() { } List lines = new LinkedList(); - lines.add("[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):"); + lines.add( + "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):"); if (!argMismatchStubs.isEmpty()) { lines.add("[Mockito]"); - lines.add("[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):"); + lines.add( + "[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):"); lines.add("[Mockito]"); addOrderedList(lines, argMismatchStubs); } @@ -74,7 +78,8 @@ public String getStubbingInfo() { if (!unstubbedCalls.isEmpty()) { lines.add("[Mockito]"); - lines.add("[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):"); + lines.add( + "[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):"); lines.add("[Mockito]"); addOrderedList(lines, unstubbedCalls); } diff --git a/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java b/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java index 00e278af4f..a01e878440 100644 --- a/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java +++ b/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java @@ -21,13 +21,13 @@ public class MockitoDebuggerImpl implements MockitoDebugger { * TODO: when MockitoDebugger is deleted, delete this implementation, too */ @Deprecated - public String printInvocations(Object ... mocks) { + public String printInvocations(Object... mocks) { String out = ""; List invocations = AllInvocationsFinder.find(asList(mocks)); out += line("********************************"); out += line("*** Mockito interactions log ***"); out += line("********************************"); - for(Invocation i:invocations) { + for (Invocation i : invocations) { out += line(i.toString()); out += line(" invoked: " + i.getLocation()); if (i.stubInfo() != null) { @@ -43,7 +43,7 @@ public String printInvocations(Object ... mocks) { out += line("*** Unused stubs ***"); out += line("********************************"); - for(Invocation i:invocations) { + for (Invocation i : invocations) { out += line(i.toString()); out += line(" stubbed: " + i.getLocation()); } diff --git a/src/main/java/org/mockito/internal/debugging/VerboseMockInvocationLogger.java b/src/main/java/org/mockito/internal/debugging/VerboseMockInvocationLogger.java index b4f63de0d4..b474373e44 100644 --- a/src/main/java/org/mockito/internal/debugging/VerboseMockInvocationLogger.java +++ b/src/main/java/org/mockito/internal/debugging/VerboseMockInvocationLogger.java @@ -40,11 +40,21 @@ public void reportInvocation(MethodInvocationReport methodInvocationReport) { private void printReturnedValueOrThrowable(MethodInvocationReport methodInvocationReport) { if (methodInvocationReport.threwException()) { - String message = methodInvocationReport.getThrowable().getMessage() == null ? "" : " with message " + methodInvocationReport.getThrowable().getMessage(); - printlnIndented("has thrown: " + methodInvocationReport.getThrowable().getClass() + message); + String message = + methodInvocationReport.getThrowable().getMessage() == null + ? "" + : " with message " + methodInvocationReport.getThrowable().getMessage(); + printlnIndented( + "has thrown: " + methodInvocationReport.getThrowable().getClass() + message); } else { - String type = (methodInvocationReport.getReturnedValue() == null) ? "" : " (" + methodInvocationReport.getReturnedValue().getClass().getName() + ")"; - printlnIndented("has returned: \"" + methodInvocationReport.getReturnedValue() + "\"" + type); + String type = + (methodInvocationReport.getReturnedValue() == null) + ? "" + : " (" + + methodInvocationReport.getReturnedValue().getClass().getName() + + ")"; + printlnIndented( + "has returned: \"" + methodInvocationReport.getReturnedValue() + "\"" + type); } } @@ -56,12 +66,15 @@ private void printStubInfo(MethodInvocationReport methodInvocationReport) { private void printHeader() { mockInvocationsCounter++; - printStream.println("############ Logging method invocation #" + mockInvocationsCounter + " on mock/spy ########"); + printStream.println( + "############ Logging method invocation #" + + mockInvocationsCounter + + " on mock/spy ########"); } private void printInvocation(DescribedInvocation invocation) { printStream.println(invocation.toString()); -// printStream.println("Handling method call on a mock/spy."); + // printStream.println("Handling method call on a mock/spy."); printlnIndented("invoked: " + invocation.getLocation().toString()); } @@ -72,5 +85,4 @@ private void printFooter() { private void printlnIndented(String message) { printStream.println(" " + message); } - } diff --git a/src/main/java/org/mockito/internal/debugging/WarningsFinder.java b/src/main/java/org/mockito/internal/debugging/WarningsFinder.java index 68ab15e7e1..f3b3ed368d 100644 --- a/src/main/java/org/mockito/internal/debugging/WarningsFinder.java +++ b/src/main/java/org/mockito/internal/debugging/WarningsFinder.java @@ -22,15 +22,16 @@ public WarningsFinder(List unusedStubs, List allI public void find(FindingsListener findingsListener) { List unusedStubs = new LinkedList(this.baseUnusedStubs); - List allInvocations = new LinkedList(this.baseAllInvocations); + List allInvocations = + new LinkedList(this.baseAllInvocations); Iterator unusedIterator = unusedStubs.iterator(); - while(unusedIterator.hasNext()) { + while (unusedIterator.hasNext()) { Invocation unused = unusedIterator.next(); Iterator unstubbedIterator = allInvocations.iterator(); - while(unstubbedIterator.hasNext()) { + while (unstubbedIterator.hasNext()) { InvocationMatcher unstubbed = unstubbedIterator.next(); - if(unstubbed.hasSimilarMethod(unused)) { + if (unstubbed.hasSimilarMethod(unused)) { findingsListener.foundStubCalledWithDifferentArgs(unused, unstubbed); unusedIterator.remove(); unstubbedIterator.remove(); diff --git a/src/main/java/org/mockito/internal/debugging/WarningsPrinterImpl.java b/src/main/java/org/mockito/internal/debugging/WarningsPrinterImpl.java index 9f235e7ee6..e02e139b0f 100644 --- a/src/main/java/org/mockito/internal/debugging/WarningsPrinterImpl.java +++ b/src/main/java/org/mockito/internal/debugging/WarningsPrinterImpl.java @@ -14,7 +14,10 @@ public class WarningsPrinterImpl { private final boolean warnAboutUnstubbed; private final WarningsFinder finder; - public WarningsPrinterImpl(List unusedStubs, List allInvocations, boolean warnAboutUnstubbed) { + public WarningsPrinterImpl( + List unusedStubs, + List allInvocations, + boolean warnAboutUnstubbed) { this(warnAboutUnstubbed, new WarningsFinder(unusedStubs, allInvocations)); } diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java index 75e98edcac..b491a7fd3a 100644 --- a/src/main/java/org/mockito/internal/exceptions/Reporter.java +++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java @@ -50,299 +50,313 @@ */ public class Reporter { - private final static String NON_PUBLIC_PARENT = "Mocking methods declared on non-public parent classes is not supported."; + private static final String NON_PUBLIC_PARENT = + "Mocking methods declared on non-public parent classes is not supported."; - private Reporter() { - } + private Reporter() {} public static MockitoException checkedExceptionInvalid(Throwable t) { - return new MockitoException(join( - "Checked exception is invalid for this method!", - "Invalid: " + t - )); + return new MockitoException( + join("Checked exception is invalid for this method!", "Invalid: " + t)); } public static MockitoException cannotStubWithNullThrowable() { - return new MockitoException(join( - "Cannot stub with null throwable!" - )); - + return new MockitoException(join("Cannot stub with null throwable!")); } public static MockitoException unfinishedStubbing(Location location) { - return new UnfinishedStubbingException(join( - "Unfinished stubbing detected here:", - location, - "", - "E.g. thenReturn() may be missing.", - "Examples of correct stubbing:", - " when(mock.isOk()).thenReturn(true);", - " when(mock.isOk()).thenThrow(exception);", - " doThrow(exception).when(mock).someVoidMethod();", - "Hints:", - " 1. missing thenReturn()", - " 2. you are trying to stub a final method, which is not supported", - " 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed", - "" - )); + return new UnfinishedStubbingException( + join( + "Unfinished stubbing detected here:", + location, + "", + "E.g. thenReturn() may be missing.", + "Examples of correct stubbing:", + " when(mock.isOk()).thenReturn(true);", + " when(mock.isOk()).thenThrow(exception);", + " doThrow(exception).when(mock).someVoidMethod();", + "Hints:", + " 1. missing thenReturn()", + " 2. you are trying to stub a final method, which is not supported", + " 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed", + "")); } public static MockitoException incorrectUseOfApi() { - return new MockitoException(join( - "Incorrect use of API detected here:", - new LocationImpl(), - "", - "You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.", - "Examples of correct usage:", - " when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);", - " when(mock.isOk()).thenReturn(true, false).thenThrow(exception);", - "" - )); + return new MockitoException( + join( + "Incorrect use of API detected here:", + new LocationImpl(), + "", + "You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.", + "Examples of correct usage:", + " when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);", + " when(mock.isOk()).thenReturn(true, false).thenThrow(exception);", + "")); } public static MockitoException missingMethodInvocation() { - return new MissingMethodInvocationException(join( - "when() requires an argument which has to be 'a method call on a mock'.", - "For example:", - " when(mock.getArticles()).thenReturn(articles);", - "", - "Also, this error might show up because:", - "1. you stub either of: final/private/equals()/hashCode() methods.", - " Those methods *cannot* be stubbed/verified.", - " " + NON_PUBLIC_PARENT, - "2. inside when() you don't call method on mock but on some other object.", - "" - )); + return new MissingMethodInvocationException( + join( + "when() requires an argument which has to be 'a method call on a mock'.", + "For example:", + " when(mock.getArticles()).thenReturn(articles);", + "", + "Also, this error might show up because:", + "1. you stub either of: final/private/equals()/hashCode() methods.", + " Those methods *cannot* be stubbed/verified.", + " " + NON_PUBLIC_PARENT, + "2. inside when() you don't call method on mock but on some other object.", + "")); } public static MockitoException unfinishedVerificationException(Location location) { - return new UnfinishedVerificationException(join( - "Missing method call for verify(mock) here:", - location, - "", - "Example of correct verification:", - " verify(mock).doSomething()", - "", - "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.", - "Those methods *cannot* be stubbed/verified.", - NON_PUBLIC_PARENT, - "" - )); + return new UnfinishedVerificationException( + join( + "Missing method call for verify(mock) here:", + location, + "", + "Example of correct verification:", + " verify(mock).doSomething()", + "", + "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.", + "Those methods *cannot* be stubbed/verified.", + NON_PUBLIC_PARENT, + "")); } public static MockitoException notAMockPassedToVerify(Class type) { - return new NotAMockException(join( - "Argument passed to verify() is of type " + type.getSimpleName() + " and is not a mock!", - "Make sure you place the parenthesis correctly!", - "See the examples of correct verifications:", - " verify(mock).someMethod();", - " verify(mock, times(10)).someMethod();", - " verify(mock, atLeastOnce()).someMethod();" - )); + return new NotAMockException( + join( + "Argument passed to verify() is of type " + + type.getSimpleName() + + " and is not a mock!", + "Make sure you place the parenthesis correctly!", + "See the examples of correct verifications:", + " verify(mock).someMethod();", + " verify(mock, times(10)).someMethod();", + " verify(mock, atLeastOnce()).someMethod();")); } public static MockitoException nullPassedToVerify() { - return new NullInsteadOfMockException(join( - "Argument passed to verify() should be a mock but is null!", - "Examples of correct verifications:", - " verify(mock).someMethod();", - " verify(mock, times(10)).someMethod();", - " verify(mock, atLeastOnce()).someMethod();", - " not: verify(mock.someMethod());", - "Also, if you use @Mock annotation don't miss initMocks()" - )); + return new NullInsteadOfMockException( + join( + "Argument passed to verify() should be a mock but is null!", + "Examples of correct verifications:", + " verify(mock).someMethod();", + " verify(mock, times(10)).someMethod();", + " verify(mock, atLeastOnce()).someMethod();", + " not: verify(mock.someMethod());", + "Also, if you use @Mock annotation don't miss initMocks()")); } public static MockitoException notAMockPassedToWhenMethod() { - return new NotAMockException(join( - "Argument passed to when() is not a mock!", - "Example of correct stubbing:", - " doThrow(new RuntimeException()).when(mock).someMethod();" - )); + return new NotAMockException( + join( + "Argument passed to when() is not a mock!", + "Example of correct stubbing:", + " doThrow(new RuntimeException()).when(mock).someMethod();")); } public static MockitoException nullPassedToWhenMethod() { - return new NullInsteadOfMockException(join( - "Argument passed to when() is null!", - "Example of correct stubbing:", - " doThrow(new RuntimeException()).when(mock).someMethod();", - "Also, if you use @Mock annotation don't miss initMocks()" - )); + return new NullInsteadOfMockException( + join( + "Argument passed to when() is null!", + "Example of correct stubbing:", + " doThrow(new RuntimeException()).when(mock).someMethod();", + "Also, if you use @Mock annotation don't miss initMocks()")); } public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() { - return new MockitoException(join( - "Method requires argument(s)!", - "Pass mocks that should be verified, e.g:", - " verifyNoMoreInteractions(mockOne, mockTwo);", - " verifyNoInteractions(mockOne, mockTwo);", - "" - )); + return new MockitoException( + join( + "Method requires argument(s)!", + "Pass mocks that should be verified, e.g:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);", + "")); } public static MockitoException notAMockPassedToVerifyNoMoreInteractions() { - return new NotAMockException(join( - "Argument(s) passed is not a mock!", - "Examples of correct verifications:", - " verifyNoMoreInteractions(mockOne, mockTwo);", - " verifyNoInteractions(mockOne, mockTwo);", - "" - )); + return new NotAMockException( + join( + "Argument(s) passed is not a mock!", + "Examples of correct verifications:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);", + "")); } public static MockitoException nullPassedToVerifyNoMoreInteractions() { - return new NullInsteadOfMockException(join( - "Argument(s) passed is null!", - "Examples of correct verifications:", - " verifyNoMoreInteractions(mockOne, mockTwo);", - " verifyNoInteractions(mockOne, mockTwo);" - )); + return new NullInsteadOfMockException( + join( + "Argument(s) passed is null!", + "Examples of correct verifications:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);")); } public static MockitoException notAMockPassedWhenCreatingInOrder() { - return new NotAMockException(join( - "Argument(s) passed is not a mock!", - "Pass mocks that require verification in order.", - "For example:", - " InOrder inOrder = inOrder(mockOne, mockTwo);" - )); + return new NotAMockException( + join( + "Argument(s) passed is not a mock!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);")); } public static MockitoException nullPassedWhenCreatingInOrder() { - return new NullInsteadOfMockException(join( - "Argument(s) passed is null!", - "Pass mocks that require verification in order.", - "For example:", - " InOrder inOrder = inOrder(mockOne, mockTwo);" - )); + return new NullInsteadOfMockException( + join( + "Argument(s) passed is null!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);")); } public static MockitoException mocksHaveToBePassedWhenCreatingInOrder() { - return new MockitoException(join( - "Method requires argument(s)!", - "Pass mocks that require verification in order.", - "For example:", - " InOrder inOrder = inOrder(mockOne, mockTwo);" - )); + return new MockitoException( + join( + "Method requires argument(s)!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);")); } public static MockitoException inOrderRequiresFamiliarMock() { - return new MockitoException(join( - "InOrder can only verify mocks that were passed in during creation of InOrder.", - "For example:", - " InOrder inOrder = inOrder(mockOne);", - " inOrder.verify(mockOne).doStuff();" - )); - } - - public static MockitoException invalidUseOfMatchers(int expectedMatchersCount, List recordedMatchers) { - return new InvalidUseOfMatchersException(join( - "Invalid use of argument matchers!", - expectedMatchersCount + " matchers expected, " + recordedMatchers.size() + " recorded:" + - locationsOf(recordedMatchers), - "", - "This exception may occur if matchers are combined with raw values:", - " //incorrect:", - " someMethod(any(), \"raw String\");", - "When using matchers, all arguments have to be provided by matchers.", - "For example:", - " //correct:", - " someMethod(any(), eq(\"String by matcher\"));", - "", - "For more info see javadoc for Matchers class.", - "" - )); - } - - public static MockitoException incorrectUseOfAdditionalMatchers(String additionalMatcherName, int expectedSubMatchersCount, Collection matcherStack) { - return new InvalidUseOfMatchersException(join( - "Invalid use of argument matchers inside additional matcher " + additionalMatcherName + " !", - new LocationImpl(), - "", - expectedSubMatchersCount + " sub matchers expected, " + matcherStack.size() + " recorded:", - locationsOf(matcherStack), - "", - "This exception may occur if matchers are combined with raw values:", - " //incorrect:", - " someMethod(AdditionalMatchers.and(isNotNull(), \"raw String\");", - "When using matchers, all arguments have to be provided by matchers.", - "For example:", - " //correct:", - " someMethod(AdditionalMatchers.and(isNotNull(), eq(\"raw String\"));", - "", - "For more info see javadoc for Matchers and AdditionalMatchers classes.", - "" - )); + return new MockitoException( + join( + "InOrder can only verify mocks that were passed in during creation of InOrder.", + "For example:", + " InOrder inOrder = inOrder(mockOne);", + " inOrder.verify(mockOne).doStuff();")); + } + + public static MockitoException invalidUseOfMatchers( + int expectedMatchersCount, List recordedMatchers) { + return new InvalidUseOfMatchersException( + join( + "Invalid use of argument matchers!", + expectedMatchersCount + + " matchers expected, " + + recordedMatchers.size() + + " recorded:" + + locationsOf(recordedMatchers), + "", + "This exception may occur if matchers are combined with raw values:", + " //incorrect:", + " someMethod(anyObject(), \"raw String\");", + "When using matchers, all arguments have to be provided by matchers.", + "For example:", + " //correct:", + " someMethod(anyObject(), eq(\"String by matcher\"));", + "", + "For more info see javadoc for Matchers class.", + "")); + } + + public static MockitoException incorrectUseOfAdditionalMatchers( + String additionalMatcherName, + int expectedSubMatchersCount, + Collection matcherStack) { + return new InvalidUseOfMatchersException( + join( + "Invalid use of argument matchers inside additional matcher " + + additionalMatcherName + + " !", + new LocationImpl(), + "", + expectedSubMatchersCount + + " sub matchers expected, " + + matcherStack.size() + + " recorded:", + locationsOf(matcherStack), + "", + "This exception may occur if matchers are combined with raw values:", + " //incorrect:", + " someMethod(AdditionalMatchers.and(isNotNull(), \"raw String\");", + "When using matchers, all arguments have to be provided by matchers.", + "For example:", + " //correct:", + " someMethod(AdditionalMatchers.and(isNotNull(), eq(\"raw String\"));", + "", + "For more info see javadoc for Matchers and AdditionalMatchers classes.", + "")); } public static MockitoException stubPassedToVerify(Object mock) { - return new CannotVerifyStubOnlyMock(join( - "Argument \"" + MockUtil.getMockName(mock) + "\" passed to verify is a stubOnly() mock which cannot be verified.", - "If you intend to verify invocations on this mock, don't use stubOnly() in its MockSettings." - )); + return new CannotVerifyStubOnlyMock( + join( + "Argument \"" + + MockUtil.getMockName(mock) + + "\" passed to verify is a stubOnly() mock which cannot be verified.", + "If you intend to verify invocations on this mock, don't use stubOnly() in its MockSettings.")); } public static MockitoException reportNoSubMatchersFound(String additionalMatcherName) { - return new InvalidUseOfMatchersException(join( - "No matchers found for additional matcher " + additionalMatcherName, - new LocationImpl(), - "" - )); + return new InvalidUseOfMatchersException( + join( + "No matchers found for additional matcher " + additionalMatcherName, + new LocationImpl(), + "")); } - private static Object locationsOf(Collection matchers) { List description = new ArrayList(); - for (LocalizedMatcher matcher : matchers) - description.add(matcher.getLocation().toString()); + for (LocalizedMatcher matcher : matchers) description.add(matcher.getLocation().toString()); return join(description.toArray()); } - public static AssertionError argumentsAreDifferent(String wanted, List actualCalls, List actualLocations) { - if (actualCalls == null || actualLocations == null || actualCalls.size() != actualLocations.size()) { + public static AssertionError argumentsAreDifferent( + String wanted, List actualCalls, List actualLocations) { + if (actualCalls == null + || actualLocations == null + || actualCalls.size() != actualLocations.size()) { throw new IllegalArgumentException("actualCalls and actualLocations list must match"); } - StringBuilder actualBuilder = new StringBuilder(); StringBuilder messageBuilder = new StringBuilder(); - messageBuilder.append("\n") - .append("Argument(s) are different! Wanted:\n") - .append(wanted) - .append("\n") - .append(new LocationImpl()) - .append("\n") - .append("Actual invocations have different arguments:\n"); + messageBuilder + .append("\n") + .append("Argument(s) are different! Wanted:\n") + .append(wanted) + .append("\n") + .append(new LocationImpl()) + .append("\n") + .append("Actual invocations have different arguments:\n"); for (int i = 0; i < actualCalls.size(); i++) { - actualBuilder.append(actualCalls.get(i)) - .append("\n"); + actualBuilder.append(actualCalls.get(i)).append("\n"); - messageBuilder.append(actualCalls.get(i)) - .append("\n") - .append(actualLocations.get(i)) - .append("\n"); + messageBuilder + .append(actualCalls.get(i)) + .append("\n") + .append(actualLocations.get(i)) + .append("\n"); } - return ExceptionFactory.createArgumentsAreDifferentException(messageBuilder.toString(), wanted, actualBuilder.toString()); + return ExceptionFactory.createArgumentsAreDifferentException( + messageBuilder.toString(), wanted, actualBuilder.toString()); } public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted) { return new WantedButNotInvoked(createWantedButNotInvokedMessage(wanted)); } - public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted, List invocations) { + public static MockitoAssertionError wantedButNotInvoked( + DescribedInvocation wanted, List invocations) { String allInvocations; if (invocations.isEmpty()) { allInvocations = "Actually, there were zero interactions with this mock.\n"; } else { - StringBuilder sb = new StringBuilder( - "\nHowever, there " + were_exactly_x_interactions(invocations.size()) + " with this mock:\n"); + StringBuilder sb = + new StringBuilder( + "\nHowever, there " + + were_exactly_x_interactions(invocations.size()) + + " with this mock:\n"); for (DescribedInvocation i : invocations) { - sb.append(i.toString()) - .append("\n") - .append(i.getLocation()) - .append("\n\n"); + sb.append(i.toString()).append("\n").append(i.getLocation()).append("\n\n"); } allInvocations = sb.toString(); } @@ -352,59 +366,66 @@ public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation want } private static String createWantedButNotInvokedMessage(DescribedInvocation wanted) { - return join( - "Wanted but not invoked:", - wanted.toString(), - new LocationImpl(), - "" - ); - } - - public static MockitoAssertionError wantedButNotInvokedInOrder(DescribedInvocation wanted, DescribedInvocation previous) { - return new VerificationInOrderFailure(join( - "Verification in order failure", - "Wanted but not invoked:", - wanted.toString(), - new LocationImpl(), - "Wanted anywhere AFTER following interaction:", - previous.toString(), - previous.getLocation(), - "" - )); - } - - public static MockitoAssertionError tooManyActualInvocations(int wantedCount, int actualCount, DescribedInvocation wanted, List locations) { - String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, locations); + return join("Wanted but not invoked:", wanted.toString(), new LocationImpl(), ""); + } + + public static MockitoAssertionError wantedButNotInvokedInOrder( + DescribedInvocation wanted, DescribedInvocation previous) { + return new VerificationInOrderFailure( + join( + "Verification in order failure", + "Wanted but not invoked:", + wanted.toString(), + new LocationImpl(), + "Wanted anywhere AFTER following interaction:", + previous.toString(), + previous.getLocation(), + "")); + } + + public static MockitoAssertionError tooManyActualInvocations( + int wantedCount, + int actualCount, + DescribedInvocation wanted, + List locations) { + String message = + createTooManyInvocationsMessage(wantedCount, actualCount, wanted, locations); return new TooManyActualInvocations(message); } - private static String createTooManyInvocationsMessage(int wantedCount, int actualCount, DescribedInvocation wanted, - List invocations) { + private static String createTooManyInvocationsMessage( + int wantedCount, + int actualCount, + DescribedInvocation wanted, + List invocations) { return join( wanted.toString(), "Wanted " + pluralize(wantedCount) + ":", new LocationImpl(), "But was " + pluralize(actualCount) + ":", createAllLocationsMessage(invocations), - "" - ); + ""); } - public static MockitoAssertionError neverWantedButInvoked(DescribedInvocation wanted, List invocations) { - return new NeverWantedButInvoked(join( - wanted.toString(), - "Never wanted here:", - new LocationImpl(), - "But invoked here:", - createAllLocationsMessage(invocations) - )); + public static MockitoAssertionError neverWantedButInvoked( + DescribedInvocation wanted, List invocations) { + return new NeverWantedButInvoked( + join( + wanted.toString(), + "Never wanted here:", + new LocationImpl(), + "But invoked here:", + createAllLocationsMessage(invocations))); } - public static MockitoAssertionError tooManyActualInvocationsInOrder(int wantedCount, int actualCount, DescribedInvocation wanted, List invocations) { - String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, invocations); - return new VerificationInOrderFailure(join( - "Verification in order failure:" + message - )); + public static MockitoAssertionError tooManyActualInvocationsInOrder( + int wantedCount, + int actualCount, + DescribedInvocation wanted, + List invocations) { + String message = + createTooManyInvocationsMessage(wantedCount, actualCount, wanted, invocations); + return new VerificationInOrderFailure(join("Verification in order failure:" + message)); } private static String createAllLocationsMessage(List locations) { @@ -418,55 +439,69 @@ private static String createAllLocationsMessage(List locations) { return sb.toString(); } - private static String createTooFewInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy, - DescribedInvocation wanted, - List locations) { + private static String createTooFewInvocationsMessage( + org.mockito.internal.reporting.Discrepancy discrepancy, + DescribedInvocation wanted, + List locations) { return join( wanted.toString(), - "Wanted " + discrepancy.getPluralizedWantedCount() + (discrepancy.getWantedCount() == 0 ? "." : ":"), + "Wanted " + + discrepancy.getPluralizedWantedCount() + + (discrepancy.getWantedCount() == 0 ? "." : ":"), new LocationImpl(), - "But was " + discrepancy.getPluralizedActualCount() + (discrepancy.getActualCount() == 0 ? "." : ":"), - createAllLocationsMessage(locations) - ); + "But was " + + discrepancy.getPluralizedActualCount() + + (discrepancy.getActualCount() == 0 ? "." : ":"), + createAllLocationsMessage(locations)); } - public static MockitoAssertionError tooFewActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List allLocations) { + public static MockitoAssertionError tooFewActualInvocations( + org.mockito.internal.reporting.Discrepancy discrepancy, + DescribedInvocation wanted, + List allLocations) { String message = createTooFewInvocationsMessage(discrepancy, wanted, allLocations); return new TooFewActualInvocations(message); } - public static MockitoAssertionError tooFewActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List locations) { + public static MockitoAssertionError tooFewActualInvocationsInOrder( + org.mockito.internal.reporting.Discrepancy discrepancy, + DescribedInvocation wanted, + List locations) { String message = createTooFewInvocationsMessage(discrepancy, wanted, locations); - return new VerificationInOrderFailure(join( - "Verification in order failure:" + message - )); + return new VerificationInOrderFailure(join("Verification in order failure:" + message)); } - public static MockitoAssertionError noMoreInteractionsWanted(Invocation undesired, List invocations) { + public static MockitoAssertionError noMoreInteractionsWanted( + Invocation undesired, List invocations) { ScenarioPrinter scenarioPrinter = new ScenarioPrinter(); String scenario = scenarioPrinter.print(invocations); - return new NoInteractionsWanted(join( - "No interactions wanted here:", - new LocationImpl(), - "But found this interaction on mock '" + MockUtil.getMockName(undesired.getMock()) + "':", - undesired.getLocation(), - scenario - )); + return new NoInteractionsWanted( + join( + "No interactions wanted here:", + new LocationImpl(), + "But found this interaction on mock '" + + MockUtil.getMockName(undesired.getMock()) + + "':", + undesired.getLocation(), + scenario)); } public static MockitoAssertionError noMoreInteractionsWantedInOrder(Invocation undesired) { - return new VerificationInOrderFailure(join( - "No interactions wanted here:", - new LocationImpl(), - "But found this interaction on mock '" + MockUtil.getMockName(undesired.getMock()) + "':", - undesired.getLocation() - )); - } - - public static MockitoAssertionError noInteractionsWanted(Object mock, List invocations) { + return new VerificationInOrderFailure( + join( + "No interactions wanted here:", + new LocationImpl(), + "But found this interaction on mock '" + + MockUtil.getMockName(undesired.getMock()) + + "':", + undesired.getLocation())); + } + + public static MockitoAssertionError noInteractionsWanted( + Object mock, List invocations) { ScenarioPrinter scenarioPrinter = new ScenarioPrinter(); String scenario = scenarioPrinter.print(invocations); @@ -474,266 +509,321 @@ public static MockitoAssertionError noInteractionsWanted(Object mock, List clazz, String reason) { - return new MockitoException(join( - "Cannot mock/spy " + clazz.toString(), - "Mockito cannot mock/spy because :", - " - " + reason - )); + return new MockitoException( + join( + "Cannot mock/spy " + clazz.toString(), + "Mockito cannot mock/spy because :", + " - " + reason)); } public static MockitoException cannotStubVoidMethodWithAReturnValue(String methodName) { - return new CannotStubVoidMethodWithReturnValue(join( - "'" + methodName + "' is a *void method* and it *cannot* be stubbed with a *return value*!", - "Voids are usually stubbed with Throwables:", - " doThrow(exception).when(mock).someVoidMethod();", - "If you need to set the void method to do nothing you can use:", - " doNothing().when(mock).someVoidMethod();", - "For more information, check out the javadocs for Mockito.doNothing().", - "***", - "If you're unsure why you're getting above error read on.", - "Due to the nature of the syntax above problem might occur because:", - "1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.", - "2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.", - "3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", - " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", - "4. " + NON_PUBLIC_PARENT, - "" - )); + return new CannotStubVoidMethodWithReturnValue( + join( + "'" + + methodName + + "' is a *void method* and it *cannot* be stubbed with a *return value*!", + "Voids are usually stubbed with Throwables:", + " doThrow(exception).when(mock).someVoidMethod();", + "If you need to set the void method to do nothing you can use:", + " doNothing().when(mock).someVoidMethod();", + "For more information, check out the javadocs for Mockito.doNothing().", + "***", + "If you're unsure why you're getting above error read on.", + "Due to the nature of the syntax above problem might occur because:", + "1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.", + "2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.", + "3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", + " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", + "4. " + NON_PUBLIC_PARENT, + "")); } public static MockitoException onlyVoidMethodsCanBeSetToDoNothing() { - return new MockitoException(join( - "Only void methods can doNothing()!", - "Example of correct use of doNothing():", - " doNothing().", - " doThrow(new RuntimeException())", - " .when(mock).someVoidMethod();", - "Above means:", - "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called" - )); - } - - public static MockitoException wrongTypeOfReturnValue(String expectedType, String actualType, String methodName) { - return new WrongTypeOfReturnValue(join( - actualType + " cannot be returned by " + methodName + "()", - methodName + "() should return " + expectedType, - "***", - "If you're unsure why you're getting above error read on.", - "Due to the nature of the syntax above problem might occur because:", - "1. This exception *might* occur in wrongly written multi-threaded tests.", - " Please refer to Mockito FAQ on limitations of concurrency testing.", - "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", - " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", - "" - )); - } - - public static MockitoException wrongTypeReturnedByDefaultAnswer(Object mock, String expectedType, String actualType, String methodName) { - return new WrongTypeOfReturnValue(join( - "Default answer returned a result with the wrong type:", - actualType + " cannot be returned by " + methodName + "()", - methodName + "() should return " + expectedType, - "", - "The default answer of " + MockUtil.getMockName(mock) + " that was configured on the mock is probably incorrectly implemented.", - "" - )); - } - - public static MoreThanAllowedActualInvocations wantedAtMostX(int maxNumberOfInvocations, int foundSize) { - return new MoreThanAllowedActualInvocations(join("Wanted at most " + pluralize(maxNumberOfInvocations) + " but was " + foundSize)); + return new MockitoException( + join( + "Only void methods can doNothing()!", + "Example of correct use of doNothing():", + " doNothing().", + " doThrow(new RuntimeException())", + " .when(mock).someVoidMethod();", + "Above means:", + "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called")); + } + + public static MockitoException wrongTypeOfReturnValue( + String expectedType, String actualType, String methodName) { + return new WrongTypeOfReturnValue( + join( + actualType + " cannot be returned by " + methodName + "()", + methodName + "() should return " + expectedType, + "***", + "If you're unsure why you're getting above error read on.", + "Due to the nature of the syntax above problem might occur because:", + "1. This exception *might* occur in wrongly written multi-threaded tests.", + " Please refer to Mockito FAQ on limitations of concurrency testing.", + "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", + " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", + "")); + } + + public static MockitoException wrongTypeReturnedByDefaultAnswer( + Object mock, String expectedType, String actualType, String methodName) { + return new WrongTypeOfReturnValue( + join( + "Default answer returned a result with the wrong type:", + actualType + " cannot be returned by " + methodName + "()", + methodName + "() should return " + expectedType, + "", + "The default answer of " + + MockUtil.getMockName(mock) + + " that was configured on the mock is probably incorrectly implemented.", + "")); + } + + public static MoreThanAllowedActualInvocations wantedAtMostX( + int maxNumberOfInvocations, int foundSize) { + return new MoreThanAllowedActualInvocations( + join( + "Wanted at most " + + pluralize(maxNumberOfInvocations) + + " but was " + + foundSize)); } public static MockitoException misplacedArgumentMatcher(List lastMatchers) { - return new InvalidUseOfMatchersException(join( - "Misplaced or misused argument matcher detected here:", - locationsOf(lastMatchers), - "", - "You cannot use argument matchers outside of verification or stubbing.", - "Examples of correct usage of argument matchers:", - " when(mock.get(anyInt())).thenReturn(null);", - " doThrow(new RuntimeException()).when(mock).someVoidMethod(any());", - " verify(mock).someMethod(contains(\"foo\"))", - "", - "This message may appear after an NullPointerException if the last matcher is returning an object ", - "like any() but the stubbed method signature expect a primitive argument, in this case,", - "use primitive alternatives.", - " when(mock.get(any())); // bad use, will raise NPE", - " when(mock.get(anyInt())); // correct usage use", - "", - "Also, this error might show up because you use argument matchers with methods that cannot be mocked.", - "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().", - NON_PUBLIC_PARENT, - "" - )); + return new InvalidUseOfMatchersException( + join( + "Misplaced or misused argument matcher detected here:", + locationsOf(lastMatchers), + "", + "You cannot use argument matchers outside of verification or stubbing.", + "Examples of correct usage of argument matchers:", + " when(mock.get(anyInt())).thenReturn(null);", + " doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());", + " verify(mock).someMethod(contains(\"foo\"))", + "", + "This message may appear after an NullPointerException if the last matcher is returning an object ", + "like any() but the stubbed method signature expect a primitive argument, in this case,", + "use primitive alternatives.", + " when(mock.get(any())); // bad use, will raise NPE", + " when(mock.get(anyInt())); // correct usage use", + "", + "Also, this error might show up because you use argument matchers with methods that cannot be mocked.", + "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().", + NON_PUBLIC_PARENT, + "")); } public static MockitoException smartNullPointerException(String invocation, Location location) { - return new SmartNullPointerException(join( - "You have a NullPointerException here:", - new LocationImpl(), - "because this method call was *not* stubbed correctly:", - location, - invocation, - "" - )); + return new SmartNullPointerException( + join( + "You have a NullPointerException here:", + new LocationImpl(), + "because this method call was *not* stubbed correctly:", + location, + invocation, + "")); } public static MockitoException noArgumentValueWasCaptured() { - return new MockitoException(join( - "No argument value was captured!", - "You might have forgotten to use argument.capture() in verify()...", - "...or you used capture() in stubbing but stubbed method was not called.", - "Be aware that it is recommended to use capture() only with verify()", - "", - "Examples of correct argument capturing:", - " ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class);", - " verify(mock).doSomething(argument.capture());", - " assertEquals(\"John\", argument.getValue().getName());", - "" - )); + return new MockitoException( + join( + "No argument value was captured!", + "You might have forgotten to use argument.capture() in verify()...", + "...or you used capture() in stubbing but stubbed method was not called.", + "Be aware that it is recommended to use capture() only with verify()", + "", + "Examples of correct argument capturing:", + " ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class);", + " verify(mock).doSomething(argument.capture());", + " assertEquals(\"John\", argument.getValue().getName());", + "")); } public static MockitoException extraInterfacesDoesNotAcceptNullParameters() { - return new MockitoException(join( - "extraInterfaces() does not accept null parameters." - )); + return new MockitoException(join("extraInterfaces() does not accept null parameters.")); } public static MockitoException extraInterfacesAcceptsOnlyInterfaces(Class wrongType) { - return new MockitoException(join( - "extraInterfaces() accepts only interfaces.", - "You passed following type: " + wrongType.getSimpleName() + " which is not an interface." - )); + return new MockitoException( + join( + "extraInterfaces() accepts only interfaces.", + "You passed following type: " + + wrongType.getSimpleName() + + " which is not an interface.")); } public static MockitoException extraInterfacesCannotContainMockedType(Class wrongType) { - return new MockitoException(join( - "extraInterfaces() does not accept the same type as the mocked type.", - "You mocked following type: " + wrongType.getSimpleName(), - "and you passed the same very interface to the extraInterfaces()" - )); + return new MockitoException( + join( + "extraInterfaces() does not accept the same type as the mocked type.", + "You mocked following type: " + wrongType.getSimpleName(), + "and you passed the same very interface to the extraInterfaces()")); } public static MockitoException extraInterfacesRequiresAtLeastOneInterface() { - return new MockitoException(join( - "extraInterfaces() requires at least one interface." - )); + return new MockitoException(join("extraInterfaces() requires at least one interface.")); } - public static MockitoException mockedTypeIsInconsistentWithSpiedInstanceType(Class mockedType, Object spiedInstance) { - return new MockitoException(join( - "Mocked type must be the same as the type of your spied instance.", - "Mocked type must be: " + spiedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(), - " //correct spying:", - " spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );", - " //incorrect - types don't match:", - " spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );" - )); + public static MockitoException mockedTypeIsInconsistentWithSpiedInstanceType( + Class mockedType, Object spiedInstance) { + return new MockitoException( + join( + "Mocked type must be the same as the type of your spied instance.", + "Mocked type must be: " + + spiedInstance.getClass().getSimpleName() + + ", but is: " + + mockedType.getSimpleName(), + " //correct spying:", + " spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );", + " //incorrect - types don't match:", + " spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );")); } public static MockitoException cannotCallAbstractRealMethod() { - return new MockitoException(join( - "Cannot call abstract real method on java object!", - "Calling real methods is only possible when mocking non abstract method.", - " //correct example:", - " when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();" - )); + return new MockitoException( + join( + "Cannot call abstract real method on java object!", + "Calling real methods is only possible when mocking non abstract method.", + " //correct example:", + " when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();")); } public static MockitoException cannotVerifyToString() { - return new MockitoException(join( - "Mockito cannot verify toString()", - "toString() is too often used behind of scenes (i.e. during String concatenation, in IDE debugging views). " + - "Verifying it may give inconsistent or hard to understand results. " + - "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)", - "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases." - )); + return new MockitoException( + join( + "Mockito cannot verify toString()", + "toString() is too often used behind of scenes (i.e. during String concatenation, in IDE debugging views). " + + "Verifying it may give inconsistent or hard to understand results. " + + "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)", + "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases.")); } public static MockitoException moreThanOneAnnotationNotAllowed(String fieldName) { - return new MockitoException("You cannot have more than one Mockito annotation on a field!\n" + - "The field '" + fieldName + "' has multiple Mockito annotations.\n" + - "For info how to use annotations see examples in javadoc for MockitoAnnotations class."); - } - - public static MockitoException unsupportedCombinationOfAnnotations(String undesiredAnnotationOne, String undesiredAnnotationTwo) { - return new MockitoException("This combination of annotations is not permitted on a single field:\n" + - "@" + undesiredAnnotationOne + " and @" + undesiredAnnotationTwo); - } - - public static MockitoException cannotInitializeForSpyAnnotation(String fieldName, Exception details) { - return new MockitoException(join("Cannot instantiate a @Spy for '" + fieldName + "' field.", - "You haven't provided the instance for spying at field declaration so I tried to construct the instance.", - "However, I failed because: " + details.getMessage(), - "Examples of correct usage of @Spy:", - " @Spy List mock = new LinkedList();", - " @Spy Foo foo; //only if Foo has parameterless constructor", - " //also, don't forget about MockitoAnnotations.initMocks();", - ""), details); - } - - public static MockitoException cannotInitializeForInjectMocksAnnotation(String fieldName, String causeMessage) { - return new MockitoException(join("Cannot instantiate @InjectMocks field named '" + fieldName + "'! Cause: "+causeMessage, - "You haven't provided the instance at field declaration so I tried to construct the instance.", - "Examples of correct usage of @InjectMocks:", - " @InjectMocks Service service = new Service();", - " @InjectMocks Service service;", - " //and... don't forget about some @Mocks for injection :)", - "")); + return new MockitoException( + "You cannot have more than one Mockito annotation on a field!\n" + + "The field '" + + fieldName + + "' has multiple Mockito annotations.\n" + + "For info how to use annotations see examples in javadoc for MockitoAnnotations class."); + } + + public static MockitoException unsupportedCombinationOfAnnotations( + String undesiredAnnotationOne, String undesiredAnnotationTwo) { + return new MockitoException( + "This combination of annotations is not permitted on a single field:\n" + + "@" + + undesiredAnnotationOne + + " and @" + + undesiredAnnotationTwo); + } + + public static MockitoException cannotInitializeForSpyAnnotation( + String fieldName, Exception details) { + return new MockitoException( + join( + "Cannot instantiate a @Spy for '" + fieldName + "' field.", + "You haven't provided the instance for spying at field declaration so I tried to construct the instance.", + "However, I failed because: " + details.getMessage(), + "Examples of correct usage of @Spy:", + " @Spy List mock = new LinkedList();", + " @Spy Foo foo; //only if Foo has parameterless constructor", + " //also, don't forget about MockitoAnnotations.initMocks();", + ""), + details); + } + + public static MockitoException cannotInitializeForInjectMocksAnnotation( + String fieldName, String causeMessage) { + return new MockitoException( + join( + "Cannot instantiate @InjectMocks field named '" + + fieldName + + "'! Cause: " + + causeMessage, + "You haven't provided the instance at field declaration so I tried to construct the instance.", + "Examples of correct usage of @InjectMocks:", + " @InjectMocks Service service = new Service();", + " @InjectMocks Service service;", + " //and... don't forget about some @Mocks for injection :)", + "")); } public static MockitoException atMostAndNeverShouldNotBeUsedWithTimeout() { - return new FriendlyReminderException(join("", - "Don't panic! I'm just a friendly reminder!", - "timeout() should not be used with atMost() or never() because...", - "...it does not make much sense - the test would have passed immediately in concurrency", - "We kept this method only to avoid compilation errors when upgrading Mockito.", - "In future release we will remove timeout(x).atMost(y) from the API.", - "If you want to find out more please refer to issue 235", - "")); - } - - public static MockitoException fieldInitialisationThrewException(Field field, Throwable details) { - return new InjectMocksException(join( - "Cannot instantiate @InjectMocks field named '" + field.getName() + "' of type '" + field.getType() + "'.", - "You haven't provided the instance at field declaration so I tried to construct the instance.", - "However the constructor or the initialization block threw an exception : " + details.getMessage(), - ""), details); - + return new FriendlyReminderException( + join( + "", + "Don't panic! I'm just a friendly reminder!", + "timeout() should not be used with atMost() or never() because...", + "...it does not make much sense - the test would have passed immediately in concurrency", + "We kept this method only to avoid compilation errors when upgrading Mockito.", + "In future release we will remove timeout(x).atMost(y) from the API.", + "If you want to find out more please refer to issue 235", + "")); + } + + public static MockitoException fieldInitialisationThrewException( + Field field, Throwable details) { + return new InjectMocksException( + join( + "Cannot instantiate @InjectMocks field named '" + + field.getName() + + "' of type '" + + field.getType() + + "'.", + "You haven't provided the instance at field declaration so I tried to construct the instance.", + "However the constructor or the initialization block threw an exception : " + + details.getMessage(), + ""), + details); } public static MockitoException methodDoesNotAcceptParameter(String method, String parameter) { - return new MockitoException(method + "() does not accept " + parameter + " See the Javadoc."); + return new MockitoException( + method + "() does not accept " + parameter + " See the Javadoc."); } public static MockitoException requiresAtLeastOneListener(String method) { return new MockitoException(method + "() requires at least one listener"); } - public static MockitoException invocationListenerThrewException(InvocationListener listener, Throwable listenerThrowable) { - return new MockitoException(join( - "The invocation listener with type " + listener.getClass().getName(), - "threw an exception : " + listenerThrowable.getClass().getName() + listenerThrowable.getMessage()), listenerThrowable); - } - - public static MockitoException cannotInjectDependency(Field field, Object matchingMock, Exception details) { - return new MockitoException(join( - "Mockito couldn't inject mock dependency '" + MockUtil.getMockName(matchingMock) + "' on field ", - "'" + field + "'", - "whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.", - "Also I failed because: " + exceptionCauseMessageIfAvailable(details), - "" - ), details); + public static MockitoException invocationListenerThrewException( + InvocationListener listener, Throwable listenerThrowable) { + return new MockitoException( + join( + "The invocation listener with type " + listener.getClass().getName(), + "threw an exception : " + + listenerThrowable.getClass().getName() + + listenerThrowable.getMessage()), + listenerThrowable); + } + + public static MockitoException cannotInjectDependency( + Field field, Object matchingMock, Exception details) { + return new MockitoException( + join( + "Mockito couldn't inject mock dependency '" + + MockUtil.getMockName(matchingMock) + + "' on field ", + "'" + field + "'", + "whose type '" + + field.getDeclaringClass().getCanonicalName() + + "' was annotated by @InjectMocks in your test.", + "Also I failed because: " + exceptionCauseMessageIfAvailable(details), + ""), + details); } private static String exceptionCauseMessageIfAvailable(Exception details) { @@ -743,43 +833,55 @@ private static String exceptionCauseMessageIfAvailable(Exception details) { return details.getCause().getMessage(); } - public static MockitoException mockedTypeIsInconsistentWithDelegatedInstanceType(Class mockedType, Object delegatedInstance) { - return new MockitoException(join( - "Mocked type must be the same as the type of your delegated instance.", - "Mocked type must be: " + delegatedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(), - " //correct delegate:", - " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );", - " //incorrect - types don't match:", - " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );" - )); + public static MockitoException mockedTypeIsInconsistentWithDelegatedInstanceType( + Class mockedType, Object delegatedInstance) { + return new MockitoException( + join( + "Mocked type must be the same as the type of your delegated instance.", + "Mocked type must be: " + + delegatedInstance.getClass().getSimpleName() + + ", but is: " + + mockedType.getSimpleName(), + " //correct delegate:", + " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );", + " //incorrect - types don't match:", + " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );")); } public static MockitoException spyAndDelegateAreMutuallyExclusive() { - return new MockitoException(join( - "Settings should not define a spy instance and a delegated instance at the same time." - )); + return new MockitoException( + join( + "Settings should not define a spy instance and a delegated instance at the same time.")); } public static MockitoException invalidArgumentRangeAtIdentityAnswerCreationTime() { - return new MockitoException(join( - "Invalid argument index.", - "The index need to be a positive number that indicates the position of the argument to return.", - "However it is possible to use the -1 value to indicates that the last argument should be", - "returned.")); - } - - public static MockitoException invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) { - return new MockitoException(join( - "Invalid argument index for the current invocation of method : ", - " -> " + MockUtil.getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()", - "", - (willReturnLastParameter ? - "Last parameter wanted" : - "Wanted parameter at position " + argumentIndex) + " but " + possibleArgumentTypesOf(invocation), - "The index need to be a positive number that indicates a valid position of the argument in the invocation.", - "However it is possible to use the -1 value to indicates that the last argument should be returned.", - "" - )); + return new MockitoException( + join( + "Invalid argument index.", + "The index need to be a positive number that indicates the position of the argument to return.", + "However it is possible to use the -1 value to indicates that the last argument should be", + "returned.")); + } + + public static MockitoException invalidArgumentPositionRangeAtInvocationTime( + InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) { + return new MockitoException( + join( + "Invalid argument index for the current invocation of method : ", + " -> " + + MockUtil.getMockName(invocation.getMock()) + + "." + + invocation.getMethod().getName() + + "()", + "", + (willReturnLastParameter + ? "Last parameter wanted" + : "Wanted parameter at position " + argumentIndex) + + " but " + + possibleArgumentTypesOf(invocation), + "The index need to be a positive number that indicates a valid position of the argument in the invocation.", + "However it is possible to use the -1 value to indicates that the last argument should be returned.", + "")); } private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocation) { @@ -788,12 +890,19 @@ private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocation return new StringBuilder("the method has no arguments.\n"); } - StringBuilder stringBuilder = new StringBuilder("the possible argument indexes for this method are :\n"); - for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) { + StringBuilder stringBuilder = + new StringBuilder("the possible argument indexes for this method are :\n"); + for (int i = 0, parameterTypesLength = parameterTypes.length; + i < parameterTypesLength; + i++) { stringBuilder.append(" [").append(i); if (invocation.getMethod().isVarArgs() && i == parameterTypesLength - 1) { - stringBuilder.append("+] ").append(parameterTypes[i].getComponentType().getSimpleName()).append(" <- Vararg").append("\n"); + stringBuilder + .append("+] ") + .append(parameterTypes[i].getComponentType().getSimpleName()) + .append(" <- Vararg") + .append("\n"); } else { stringBuilder.append("] ").append(parameterTypes[i].getSimpleName()).append("\n"); } @@ -801,101 +910,134 @@ private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocation return stringBuilder; } - public static MockitoException wrongTypeOfArgumentToReturn(InvocationOnMock invocation, String expectedType, Class actualType, int argumentIndex) { - return new WrongTypeOfReturnValue(join( - "The argument of type '" + actualType.getSimpleName() + "' cannot be returned because the following ", - "method should return the type '" + expectedType + "'", - " -> " + MockUtil.getMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()", - "", - "The reason for this error can be :", - "1. The wanted argument position is incorrect.", - "2. The answer is used on the wrong interaction.", - "", - "Position of the wanted argument is " + argumentIndex + " and " + possibleArgumentTypesOf(invocation), - "***", - "However if you're still unsure why you're getting above error read on.", - "Due to the nature of the syntax above problem might occur because:", - "1. This exception *might* occur in wrongly written multi-threaded tests.", - " Please refer to Mockito FAQ on limitations of concurrency testing.", - "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", - " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", - "" - )); + public static MockitoException wrongTypeOfArgumentToReturn( + InvocationOnMock invocation, + String expectedType, + Class actualType, + int argumentIndex) { + return new WrongTypeOfReturnValue( + join( + "The argument of type '" + + actualType.getSimpleName() + + "' cannot be returned because the following ", + "method should return the type '" + expectedType + "'", + " -> " + + MockUtil.getMockName(invocation.getMock()) + + "." + + invocation.getMethod().getName() + + "()", + "", + "The reason for this error can be :", + "1. The wanted argument position is incorrect.", + "2. The answer is used on the wrong interaction.", + "", + "Position of the wanted argument is " + + argumentIndex + + " and " + + possibleArgumentTypesOf(invocation), + "***", + "However if you're still unsure why you're getting above error read on.", + "Due to the nature of the syntax above problem might occur because:", + "1. This exception *might* occur in wrongly written multi-threaded tests.", + " Please refer to Mockito FAQ on limitations of concurrency testing.", + "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ", + " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.", + "")); } public static MockitoException defaultAnswerDoesNotAcceptNullParameter() { return new MockitoException("defaultAnswer() does not accept null parameter"); } - public static MockitoException serializableWontWorkForObjectsThatDontImplementSerializable(Class classToMock) { - return new MockitoException(join( - "You are using the setting 'withSettings().serializable()' however the type you are trying to mock '" + classToMock.getSimpleName() + "'", - "do not implement Serializable AND do not have a no-arg constructor.", - "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized", - "", - "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,", - "i.e. the top-most superclass has to implements Serializable.", - "" - )); - } - - public static MockitoException delegatedMethodHasWrongReturnType(Method mockMethod, Method delegateMethod, Object mock, Object delegate) { - return new MockitoException(join( - "Methods called on delegated instance must have compatible return types with the mock.", - "When calling: " + mockMethod + " on mock: " + MockUtil.getMockName(mock), - "return type should be: " + mockMethod.getReturnType().getSimpleName() + ", but was: " + delegateMethod.getReturnType().getSimpleName(), - "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", - "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")" - )); - } - - public static MockitoException delegatedMethodDoesNotExistOnDelegate(Method mockMethod, Object mock, Object delegate) { - return new MockitoException(join( - "Methods called on mock must exist in delegated instance.", - "When calling: " + mockMethod + " on mock: " + MockUtil.getMockName(mock), - "no such method was found.", - "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", - "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")" - )); + public static MockitoException serializableWontWorkForObjectsThatDontImplementSerializable( + Class classToMock) { + return new MockitoException( + join( + "You are using the setting 'withSettings().serializable()' however the type you are trying to mock '" + + classToMock.getSimpleName() + + "'", + "do not implement Serializable AND do not have a no-arg constructor.", + "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized", + "", + "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,", + "i.e. the top-most superclass has to implements Serializable.", + "")); + } + + public static MockitoException delegatedMethodHasWrongReturnType( + Method mockMethod, Method delegateMethod, Object mock, Object delegate) { + return new MockitoException( + join( + "Methods called on delegated instance must have compatible return types with the mock.", + "When calling: " + mockMethod + " on mock: " + MockUtil.getMockName(mock), + "return type should be: " + + mockMethod.getReturnType().getSimpleName() + + ", but was: " + + delegateMethod.getReturnType().getSimpleName(), + "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", + "(delegate instance had type: " + + delegate.getClass().getSimpleName() + + ")")); + } + + public static MockitoException delegatedMethodDoesNotExistOnDelegate( + Method mockMethod, Object mock, Object delegate) { + return new MockitoException( + join( + "Methods called on mock must exist in delegated instance.", + "When calling: " + mockMethod + " on mock: " + MockUtil.getMockName(mock), + "no such method was found.", + "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", + "(delegate instance had type: " + + delegate.getClass().getSimpleName() + + ")")); } public static MockitoException usingConstructorWithFancySerializable(SerializableMode mode) { - return new MockitoException("Mocks instantiated with constructor cannot be combined with " + mode + " serialization mode."); + return new MockitoException( + "Mocks instantiated with constructor cannot be combined with " + + mode + + " serialization mode."); } public static MockitoException cannotCreateTimerWithNegativeDurationTime(long durationMillis) { - return new FriendlyReminderException(join( - "", - "Don't panic! I'm just a friendly reminder!", - "It is impossible for time to go backward, therefore...", - "You cannot put negative value of duration: (" + durationMillis + ")", - "as argument of timer methods (after(), timeout())", - "" - )); + return new FriendlyReminderException( + join( + "", + "Don't panic! I'm just a friendly reminder!", + "It is impossible for time to go backward, therefore...", + "You cannot put negative value of duration: (" + durationMillis + ")", + "as argument of timer methods (after(), timeout())", + "")); } public static MockitoException notAnException() { - return new MockitoException(join( - "Exception type cannot be null.", - "This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter.")); + return new MockitoException( + join( + "Exception type cannot be null.", + "This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter.")); } - public static UnnecessaryStubbingException formatUnncessaryStubbingException(Class testClass, Collection unnecessaryStubbings) { + public static UnnecessaryStubbingException formatUnncessaryStubbingException( + Class testClass, Collection unnecessaryStubbings) { StringBuilder stubbings = new StringBuilder(); int count = 1; for (Invocation u : unnecessaryStubbings) { stubbings.append("\n ").append(count++).append(". ").append(u.getLocation()); } - String heading = (testClass != null)? - "Unnecessary stubbings detected in test class: " + testClass.getSimpleName() : - "Unnecessary stubbings detected."; + String heading = + (testClass != null) + ? "Unnecessary stubbings detected in test class: " + + testClass.getSimpleName() + : "Unnecessary stubbings detected."; - return new UnnecessaryStubbingException(join( - heading, - "Clean & maintainable test code requires zero unnecessary code.", - "Following stubbings are unnecessary (click to navigate to relevant line of code):" + stubbings, - "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class." - )); + return new UnnecessaryStubbingException( + join( + heading, + "Clean & maintainable test code requires zero unnecessary code.", + "Following stubbings are unnecessary (click to navigate to relevant line of code):" + + stubbings, + "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.")); } public static void unncessaryStubbingException(List unused) { @@ -910,39 +1052,46 @@ public static void potentialStubbingProblem( stubbings.append(" ").append(count++).append(". ").append(s); stubbings.append("\n ").append(s.getLocation()).append("\n"); } - stubbings.deleteCharAt(stubbings.length()-1); //remove trailing end of line - - throw new PotentialStubbingProblem(join( - "Strict stubbing argument mismatch. Please check:", - " - this invocation of '" + actualInvocation.getMethod().getName() + "' method:", - " " + actualInvocation, - " " + actualInvocation.getLocation(), - " - has following stubbing(s) with different arguments:", - stubbings, - "Typically, stubbing argument mismatch indicates user mistake when writing tests.", - "Mockito fails early so that you can debug potential problem easily.", - "However, there are legit scenarios when this exception generates false negative signal:", - " - stubbing the same method multiple times using 'given().will()' or 'when().then()' API", - " Please use 'will().given()' or 'doReturn().when()' API for stubbing.", - " - stubbed method is intentionally invoked with different arguments by code under test", - " Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).", - "For more information see javadoc for PotentialStubbingProblem class.")); + stubbings.deleteCharAt(stubbings.length() - 1); // remove trailing end of line + + throw new PotentialStubbingProblem( + join( + "Strict stubbing argument mismatch. Please check:", + " - this invocation of '" + + actualInvocation.getMethod().getName() + + "' method:", + " " + actualInvocation, + " " + actualInvocation.getLocation(), + " - has following stubbing(s) with different arguments:", + stubbings, + "Typically, stubbing argument mismatch indicates user mistake when writing tests.", + "Mockito fails early so that you can debug potential problem easily.", + "However, there are legit scenarios when this exception generates false negative signal:", + " - stubbing the same method multiple times using 'given().will()' or 'when().then()' API", + " Please use 'will().given()' or 'doReturn().when()' API for stubbing.", + " - stubbed method is intentionally invoked with different arguments by code under test", + " Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).", + "For more information see javadoc for PotentialStubbingProblem class.")); } public static void redundantMockitoListener(String listenerType) { - throw new RedundantListenerException(join( - "Problems adding Mockito listener.", - "Listener of type '" + listenerType + "' has already been added and not removed.", - "It indicates that previous listener was not removed according to the API.", - "When you add a listener, don't forget to remove the listener afterwards:", - " Mockito.framework().removeListener(myListener);", - "For more information, see the javadoc for RedundantListenerException class.")); + throw new RedundantListenerException( + join( + "Problems adding Mockito listener.", + "Listener of type '" + + listenerType + + "' has already been added and not removed.", + "It indicates that previous listener was not removed according to the API.", + "When you add a listener, don't forget to remove the listener afterwards:", + " Mockito.framework().removeListener(myListener);", + "For more information, see the javadoc for RedundantListenerException class.")); } public static void unfinishedMockingSession() { - throw new UnfinishedMockingSessionException(join( - "Unfinished mocking session detected.", - "Previous MockitoSession was not concluded with 'finishMocking()'.", - "For examples of correct usage see javadoc for MockitoSession class.")); + throw new UnfinishedMockingSessionException( + join( + "Unfinished mocking session detected.", + "Previous MockitoSession was not concluded with 'finishMocking()'.", + "For examples of correct usage see javadoc for MockitoSession class.")); } } diff --git a/src/main/java/org/mockito/internal/exceptions/VerificationAwareInvocation.java b/src/main/java/org/mockito/internal/exceptions/VerificationAwareInvocation.java index f5bcd4e21f..865ee586ec 100644 --- a/src/main/java/org/mockito/internal/exceptions/VerificationAwareInvocation.java +++ b/src/main/java/org/mockito/internal/exceptions/VerificationAwareInvocation.java @@ -9,5 +9,4 @@ public interface VerificationAwareInvocation extends DescribedInvocation { boolean isVerified(); - } diff --git a/src/main/java/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java b/src/main/java/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java index 6f7b956ed3..6b0575273e 100644 --- a/src/main/java/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java +++ b/src/main/java/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java @@ -23,7 +23,8 @@ public boolean isIn(StackTraceElement e) { } private static boolean isMockDispatcher(String className) { - return (className.contains("$$EnhancerByMockitoWithCGLIB$$") || className.contains("$MockitoMock$")); + return (className.contains("$$EnhancerByMockitoWithCGLIB$$") + || className.contains("$MockitoMock$")); } private static boolean isFromMockito(String className) { @@ -36,7 +37,7 @@ private static boolean isFromMockitoRule(String className) { private static boolean isFromMockitoRunner(String className) { return className.startsWith("org.mockito.internal.runners.") - || className.startsWith("org.mockito.runners.") - || className.startsWith("org.mockito.junit."); + || className.startsWith("org.mockito.runners.") + || className.startsWith("org.mockito.junit."); } } diff --git a/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java b/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java index e846795d6d..2ae888e26f 100644 --- a/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java +++ b/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java @@ -17,7 +17,8 @@ public class StackTraceFilter implements Serializable { static final long serialVersionUID = -5499819791513105700L; private static final StackTraceCleaner CLEANER = - Plugins.getStackTraceCleanerProvider().getStackTraceCleaner(new DefaultStackTraceCleaner()); + Plugins.getStackTraceCleanerProvider() + .getStackTraceCleaner(new DefaultStackTraceCleaner()); private static Object JAVA_LANG_ACCESS; private static Method GET_STACK_TRACE_ELEMENT; @@ -25,12 +26,12 @@ public class StackTraceFilter implements Serializable { static { try { JAVA_LANG_ACCESS = - Class.forName("sun.misc.SharedSecrets") - .getMethod("getJavaLangAccess") - .invoke(null); + Class.forName("sun.misc.SharedSecrets") + .getMethod("getJavaLangAccess") + .invoke(null); GET_STACK_TRACE_ELEMENT = - Class.forName("sun.misc.JavaLangAccess") - .getMethod("getStackTraceElement", Throwable.class, int.class); + Class.forName("sun.misc.JavaLangAccess") + .getMethod("getStackTraceElement", Throwable.class, int.class); } catch (Exception ignored) { // Use the slow computational path for filtering stacktraces if fast path does not exist // in JVM @@ -44,8 +45,8 @@ public class StackTraceFilter implements Serializable { * If any good are in the middle of bad those are also removed. */ public StackTraceElement[] filter(StackTraceElement[] target, boolean keepTop) { - //TODO: profile - //TODO: investigate "keepTop" commit history - no effect! + // TODO: profile + // TODO: investigate "keepTop" commit history - no effect! final List filtered = new ArrayList(); for (StackTraceElement element : target) { if (CLEANER.isIn(element)) { @@ -85,8 +86,8 @@ public StackTraceElement filterFirst(Throwable target, boolean isInline) { while (true) { try { StackTraceElement stackTraceElement = - (StackTraceElement) - GET_STACK_TRACE_ELEMENT.invoke(JAVA_LANG_ACCESS, target, i); + (StackTraceElement) + GET_STACK_TRACE_ELEMENT.invoke(JAVA_LANG_ACCESS, target, i); if (CLEANER.isIn(stackTraceElement)) { if (shouldSkip) { diff --git a/src/main/java/org/mockito/internal/exceptions/util/ScenarioPrinter.java b/src/main/java/org/mockito/internal/exceptions/util/ScenarioPrinter.java index a3e60fe6e1..7b4375d423 100644 --- a/src/main/java/org/mockito/internal/exceptions/util/ScenarioPrinter.java +++ b/src/main/java/org/mockito/internal/exceptions/util/ScenarioPrinter.java @@ -14,9 +14,10 @@ public String print(List invocations) { if (invocations.size() == 1) { return "Actually, above is the only interaction with this mock."; } - StringBuilder sb = new StringBuilder( - "***\n" + - "For your reference, here is the list of all invocations ([?] - means unverified).\n"); + StringBuilder sb = + new StringBuilder( + "***\n" + + "For your reference, here is the list of all invocations ([?] - means unverified).\n"); int counter = 0; for (VerificationAwareInvocation i : invocations) { @@ -28,5 +29,4 @@ public String print(List invocations) { } return sb.toString(); } - } diff --git a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java index 9c07658866..5e60099726 100644 --- a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java +++ b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java @@ -21,11 +21,15 @@ public class DefaultMockitoSession implements MockitoSession { private final String name; private final UniversalTestListener listener; - public DefaultMockitoSession(List testClassInstances, String name, Strictness strictness, MockitoLogger logger) { + public DefaultMockitoSession( + List testClassInstances, + String name, + Strictness strictness, + MockitoLogger logger) { this.name = name; listener = new UniversalTestListener(strictness, logger); try { - //So that the listener can capture mock creation events + // So that the listener can capture mock creation events Mockito.framework().addListener(listener); } catch (RedundantListenerException e) { Reporter.unfinishedMockingSession(); @@ -35,7 +39,7 @@ public DefaultMockitoSession(List testClassInstances, String name, Stric MockitoAnnotations.initMocks(testClassInstance); } } catch (RuntimeException e) { - //clean up in case 'initMocks' fails + // clean up in case 'initMocks' fails listener.setListenerDirty(); throw e; } @@ -53,26 +57,28 @@ public void finishMocking() { @Override public void finishMocking(final Throwable failure) { - //Cleaning up the state, we no longer need the listener hooked up - //The listener implements MockCreationListener and at this point - //we no longer need to listen on mock creation events. We are wrapping up the session + // Cleaning up the state, we no longer need the listener hooked up + // The listener implements MockCreationListener and at this point + // we no longer need to listen on mock creation events. We are wrapping up the session Mockito.framework().removeListener(listener); - //Emit test finished event so that validation such as strict stubbing can take place - listener.testFinished(new TestFinishedEvent() { - @Override - public Throwable getFailure() { - return failure; - } - @Override - public String getTestName() { - return name; - } - }); + // Emit test finished event so that validation such as strict stubbing can take place + listener.testFinished( + new TestFinishedEvent() { + @Override + public Throwable getFailure() { + return failure; + } + + @Override + public String getTestName() { + return name; + } + }); - //Validate only when there is no test failure to avoid reporting multiple problems + // Validate only when there is no test failure to avoid reporting multiple problems if (failure == null) { - //Finally, validate user's misuse of Mockito framework. + // Finally, validate user's misuse of Mockito framework. Mockito.validateMockitoUsage(); } } diff --git a/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java b/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java index 5183136ae7..d9b52b6d6d 100644 --- a/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java +++ b/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java @@ -26,7 +26,7 @@ public boolean isVarargMatcher() { } public String toString() { - //TODO SF add unit tests and integ test coverage for toString() + // TODO SF add unit tests and integ test coverage for toString() return StringDescription.toString(matcher); } } diff --git a/src/main/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java b/src/main/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java index 5c154f4d4c..0104f86391 100644 --- a/src/main/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java +++ b/src/main/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java @@ -19,7 +19,7 @@ public class MatcherGenericTypeExtractor { * for matcher class that extends BaseMatcher[Integer] this method returns Integer */ public static Class genericTypeOfMatcher(Class matcherClass) { - //TODO SF check if we can reuse it for Mockito ArgumentMatcher + // TODO SF check if we can reuse it for Mockito ArgumentMatcher return genericTypeOf(matcherClass, BaseMatcher.class, Matcher.class); } } diff --git a/src/main/java/org/mockito/internal/handler/InvocationNotifierHandler.java b/src/main/java/org/mockito/internal/handler/InvocationNotifierHandler.java index 2c26b3ddfa..06695babc0 100644 --- a/src/main/java/org/mockito/internal/handler/InvocationNotifierHandler.java +++ b/src/main/java/org/mockito/internal/handler/InvocationNotifierHandler.java @@ -33,18 +33,18 @@ public Object handle(Invocation invocation) throws Throwable { Object returnedValue = mockHandler.handle(invocation); notifyMethodCall(invocation, returnedValue); return returnedValue; - } catch (Throwable t){ + } catch (Throwable t) { notifyMethodCallException(invocation, t); throw t; } } - private void notifyMethodCall(Invocation invocation, Object returnValue) { for (InvocationListener listener : invocationListeners) { try { - listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, returnValue)); - } catch(Throwable listenerThrowable) { + listener.reportInvocation( + new NotifiedMethodInvocationReport(invocation, returnValue)); + } catch (Throwable listenerThrowable) { throw invocationListenerThrewException(listener, listenerThrowable); } } @@ -53,8 +53,9 @@ private void notifyMethodCall(Invocation invocation, Object returnValue) { private void notifyMethodCallException(Invocation invocation, Throwable exception) { for (InvocationListener listener : invocationListeners) { try { - listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, exception)); - } catch(Throwable listenerThrowable) { + listener.reportInvocation( + new NotifiedMethodInvocationReport(invocation, exception)); + } catch (Throwable listenerThrowable) { throw invocationListenerThrewException(listener, listenerThrowable); } } @@ -67,5 +68,4 @@ public MockCreationSettings getMockSettings() { public InvocationContainer getInvocationContainer() { return mockHandler.getInvocationContainer(); } - } diff --git a/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java b/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java index c0438cd5aa..3d81b362c5 100644 --- a/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java +++ b/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java @@ -47,19 +47,17 @@ public MockHandlerImpl(MockCreationSettings mockSettings) { public Object handle(Invocation invocation) throws Throwable { if (invocationContainer.hasAnswersForStubbing()) { // stubbing voids with doThrow() or doAnswer() style - InvocationMatcher invocationMatcher = matchersBinder.bindMatchers( - mockingProgress().getArgumentMatcherStorage(), - invocation - ); + InvocationMatcher invocationMatcher = + matchersBinder.bindMatchers( + mockingProgress().getArgumentMatcherStorage(), invocation); invocationContainer.setMethodForStubbing(invocationMatcher); return null; } VerificationMode verificationMode = mockingProgress().pullVerificationMode(); - InvocationMatcher invocationMatcher = matchersBinder.bindMatchers( - mockingProgress().getArgumentMatcherStorage(), - invocation - ); + InvocationMatcher invocationMatcher = + matchersBinder.bindMatchers( + mockingProgress().getArgumentMatcherStorage(), invocation); mockingProgress().validateState(); @@ -68,11 +66,13 @@ public Object handle(Invocation invocation) throws Throwable { // We need to check if verification was started on the correct mock // - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138) if (((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) { - VerificationDataImpl data = new VerificationDataImpl(invocationContainer, invocationMatcher); + VerificationDataImpl data = + new VerificationDataImpl(invocationContainer, invocationMatcher); verificationMode.verify(data); return null; } else { - // this means there is an invocation on a different mock. Re-adding verification mode + // this means there is an invocation on a different mock. Re-adding verification + // mode // - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138) mockingProgress().verificationStarted(verificationMode); } @@ -86,8 +86,11 @@ public Object handle(Invocation invocation) throws Throwable { // look for existing answer for this invocation StubbedInvocationMatcher stubbing = invocationContainer.findAnswerFor(invocation); // TODO #793 - when completed, we should be able to get rid of the casting below - notifyStubbedAnswerLookup(invocation, stubbing, invocationContainer.getStubbingsAscending(), - (CreationSettings) mockSettings); + notifyStubbedAnswerLookup( + invocation, + stubbing, + invocationContainer.getStubbingsAscending(), + (CreationSettings) mockSettings); if (stubbing != null) { stubbing.captureArgumentsFrom(invocation); @@ -95,19 +98,21 @@ public Object handle(Invocation invocation) throws Throwable { try { return stubbing.answer(invocation); } finally { - //Needed so that we correctly isolate stubbings in some scenarios - //see MockitoStubbedCallInAnswerTest or issue #1279 + // Needed so that we correctly isolate stubbings in some scenarios + // see MockitoStubbedCallInAnswerTest or issue #1279 mockingProgress().reportOngoingStubbing(ongoingStubbing); } } else { Object ret = mockSettings.getDefaultAnswer().answer(invocation); DefaultAnswerValidator.validateReturnValueFor(invocation, ret); - //Mockito uses it to redo setting invocation for potential stubbing in case of partial mocks / spies. - //Without it, the real method inside 'when' might have delegated to other self method - //and overwrite the intended stubbed method with a different one. - //This means we would be stubbing a wrong method. - //Typically this would led to runtime exception that validates return type with stubbed method signature. + // Mockito uses it to redo setting invocation for potential stubbing in case of partial + // mocks / spies. + // Without it, the real method inside 'when' might have delegated to other self method + // and overwrite the intended stubbed method with a different one. + // This means we would be stubbing a wrong method. + // Typically this would led to runtime exception that validates return type with stubbed + // method signature. invocationContainer.resetInvocationForPotentialStubbing(invocationMatcher); return ret; } diff --git a/src/main/java/org/mockito/internal/handler/NotifiedMethodInvocationReport.java b/src/main/java/org/mockito/internal/handler/NotifiedMethodInvocationReport.java index e44543df57..30d1808c55 100644 --- a/src/main/java/org/mockito/internal/handler/NotifiedMethodInvocationReport.java +++ b/src/main/java/org/mockito/internal/handler/NotifiedMethodInvocationReport.java @@ -18,7 +18,6 @@ public class NotifiedMethodInvocationReport implements MethodInvocationReport { private final Object returnedValue; private final Throwable throwable; - /** * Build a new {@link org.mockito.listeners.MethodInvocationReport} with a return value. * @@ -62,19 +61,20 @@ public boolean threwException() { } public String getLocationOfStubbing() { - return (invocation.stubInfo() == null) ? null : invocation.stubInfo().stubbedAt().toString(); + return (invocation.stubInfo() == null) + ? null + : invocation.stubInfo().stubbedAt().toString(); } - public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NotifiedMethodInvocationReport that = (NotifiedMethodInvocationReport) o; - return areEqual(invocation, that.invocation) && - areEqual(returnedValue, that.returnedValue) && - areEqual(throwable, that.throwable); + return areEqual(invocation, that.invocation) + && areEqual(returnedValue, that.returnedValue) + && areEqual(throwable, that.throwable); } public int hashCode() { diff --git a/src/main/java/org/mockito/internal/handler/NullResultGuardian.java b/src/main/java/org/mockito/internal/handler/NullResultGuardian.java index 10671d7ced..65de62e069 100644 --- a/src/main/java/org/mockito/internal/handler/NullResultGuardian.java +++ b/src/main/java/org/mockito/internal/handler/NullResultGuardian.java @@ -28,12 +28,12 @@ public NullResultGuardian(MockHandler delegate) { public Object handle(Invocation invocation) throws Throwable { Object result = delegate.handle(invocation); Class returnType = invocation.getMethod().getReturnType(); - if(result == null && returnType.isPrimitive()) { - //primitive values cannot be null + if (result == null && returnType.isPrimitive()) { + // primitive values cannot be null return defaultValue(returnType); } return result; - } + } @Override public MockCreationSettings getMockSettings() { diff --git a/src/main/java/org/mockito/internal/invocation/ArgumentsProcessor.java b/src/main/java/org/mockito/internal/invocation/ArgumentsProcessor.java index be642bfc1e..1f810a97ac 100644 --- a/src/main/java/org/mockito/internal/invocation/ArgumentsProcessor.java +++ b/src/main/java/org/mockito/internal/invocation/ArgumentsProcessor.java @@ -16,19 +16,26 @@ * by Szczepan Faber, created at: 3/31/12 */ public class ArgumentsProcessor { - // drops hidden synthetic parameters (last continuation parameter from Kotlin suspending functions) + // drops hidden synthetic parameters (last continuation parameter from Kotlin suspending + // functions) // and expands varargs public static Object[] expandArgs(MockitoMethod method, Object[] args) { int nParams = method.getParameterTypes().length; if (args != null && args.length > nParams) - args = Arrays.copyOf(args, nParams); // drop extra args (currently -- Kotlin continuation synthetic arg) + args = + Arrays.copyOf( + args, + nParams); // drop extra args (currently -- Kotlin continuation synthetic + // arg) return expandVarArgs(method.isVarArgs(), args); } // expands array varArgs that are given by runtime (1, [a, b]) into true // varArgs (1, a, b); private static Object[] expandVarArgs(final boolean isVarArgs, final Object[] args) { - if (!isVarArgs || isNullOrEmpty(args) || args[args.length - 1] != null && !args[args.length - 1].getClass().isArray()) { + if (!isVarArgs + || isNullOrEmpty(args) + || args[args.length - 1] != null && !args[args.length - 1].getClass().isArray()) { return args == null ? new Object[0] : args; } @@ -36,7 +43,7 @@ private static Object[] expandVarArgs(final boolean isVarArgs, final Object[] ar Object[] varArgs; if (args[nonVarArgsCount] == null) { // in case someone deliberately passed null varArg array - varArgs = new Object[] { null }; + varArgs = new Object[] {null}; } else { varArgs = ArrayEquals.createObjectArray(args[nonVarArgsCount]); } @@ -62,6 +69,4 @@ public static List argumentsToMatchers(Object[] arguments) { } return matchers; } - - } diff --git a/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java b/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java index 46236d04af..d8f0e7173f 100644 --- a/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java +++ b/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java @@ -18,34 +18,59 @@ public class DefaultInvocationFactory implements InvocationFactory { - public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) { + public Invocation createInvocation( + Object target, + MockCreationSettings settings, + Method method, + final Callable realMethod, + Object... args) { RealMethod superMethod = new RealMethod.FromCallable(realMethod); return createInvocation(target, settings, method, superMethod, args); } - public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, RealMethodBehavior realMethod, Object... args) { + public Invocation createInvocation( + Object target, + MockCreationSettings settings, + Method method, + RealMethodBehavior realMethod, + Object... args) { RealMethod superMethod = new RealMethod.FromBehavior(realMethod); return createInvocation(target, settings, method, superMethod, args); } - private Invocation createInvocation(Object target, MockCreationSettings settings, Method method, RealMethod superMethod, Object[] args) { + private Invocation createInvocation( + Object target, + MockCreationSettings settings, + Method method, + RealMethod superMethod, + Object[] args) { return createInvocation(target, method, args, superMethod, settings); } - public static InterceptedInvocation createInvocation(Object mock, Method invokedMethod, Object[] arguments, RealMethod realMethod, MockCreationSettings settings, Location location) { + public static InterceptedInvocation createInvocation( + Object mock, + Method invokedMethod, + Object[] arguments, + RealMethod realMethod, + MockCreationSettings settings, + Location location) { return new InterceptedInvocation( - new MockWeakReference(mock), - createMockitoMethod(invokedMethod, settings), - arguments, - realMethod, - location, - SequenceNumber.next() - ); + new MockWeakReference(mock), + createMockitoMethod(invokedMethod, settings), + arguments, + realMethod, + location, + SequenceNumber.next()); } - private static InterceptedInvocation createInvocation(Object mock, Method invokedMethod, Object[] - arguments, RealMethod realMethod, MockCreationSettings settings) { - return createInvocation(mock, invokedMethod, arguments, realMethod, settings, new LocationImpl()); + private static InterceptedInvocation createInvocation( + Object mock, + Method invokedMethod, + Object[] arguments, + RealMethod realMethod, + MockCreationSettings settings) { + return createInvocation( + mock, invokedMethod, arguments, realMethod, settings, new LocationImpl()); } private static MockitoMethod createMockitoMethod(Method method, MockCreationSettings settings) { diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java index 0c7535cc47..4ef871dce5 100644 --- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java +++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java @@ -36,12 +36,13 @@ public class InterceptedInvocation implements Invocation, VerificationAwareInvoc private boolean isIgnoredForVerification; private StubInfo stubInfo; - public InterceptedInvocation(MockReference mockRef, - MockitoMethod mockitoMethod, - Object[] arguments, - RealMethod realMethod, - Location location, - int sequenceNumber) { + public InterceptedInvocation( + MockReference mockRef, + MockitoMethod mockitoMethod, + Object[] arguments, + RealMethod realMethod, + Location location, + int sequenceNumber) { this.mockRef = mockRef; this.mockitoMethod = mockitoMethod; this.arguments = ArgumentsProcessor.expandArgs(mockitoMethod, arguments); @@ -154,7 +155,8 @@ public Object callRealMethod() throws Throwable { @Override public int hashCode() { - //TODO SF we need to provide hash code implementation so that there are no unexpected, slight perf issues + // TODO SF we need to provide hash code implementation so that there are no unexpected, + // slight perf issues return 1; } @@ -177,13 +179,14 @@ public String toString() { return new PrintSettings().print(getArgumentsAsMatchers(), this); } - public final static RealMethod NO_OP = new RealMethod() { - public boolean isInvokable() { - return false; - } - public Object invoke() throws Throwable { - return null; - } - }; + public static final RealMethod NO_OP = + new RealMethod() { + public boolean isInvokable() { + return false; + } + public Object invoke() throws Throwable { + return null; + } + }; } diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMarker.java b/src/main/java/org/mockito/internal/invocation/InvocationMarker.java index d960e86b13..5f32dea4b8 100644 --- a/src/main/java/org/mockito/internal/invocation/InvocationMarker.java +++ b/src/main/java/org/mockito/internal/invocation/InvocationMarker.java @@ -12,7 +12,7 @@ public class InvocationMarker { - private InvocationMarker(){} + private InvocationMarker() {} public static void markVerified(List invocations, MatchableInvocation wanted) { for (Invocation invocation : invocations) { @@ -25,7 +25,8 @@ public static void markVerified(Invocation invocation, MatchableInvocation wante wanted.captureArgumentsFrom(invocation); } - public static void markVerifiedInOrder(List chunk, MatchableInvocation wanted, InOrderContext context) { + public static void markVerifiedInOrder( + List chunk, MatchableInvocation wanted, InOrderContext context) { markVerified(chunk, wanted); for (Invocation i : chunk) { diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java index 81bd483ab1..7952b81fd0 100644 --- a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java +++ b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java @@ -31,7 +31,7 @@ public class InvocationMatcher implements MatchableInvocation, DescribedInvocati private final Invocation invocation; private final List> matchers; - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) public InvocationMatcher(Invocation invocation, List matchers) { this.invocation = invocation; if (matchers.isEmpty()) { @@ -43,7 +43,7 @@ public InvocationMatcher(Invocation invocation, List matchers) @SuppressWarnings("rawtypes") public InvocationMatcher(Invocation invocation) { - this(invocation, Collections. emptyList()); + this(invocation, Collections.emptyList()); } public static List createFrom(List invocations) { @@ -64,20 +64,22 @@ public Invocation getInvocation() { } @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public List getMatchers() { return (List) matchers; } @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public String toString() { return new PrintSettings().print((List) matchers, invocation); } @Override public boolean matches(Invocation candidate) { - return invocation.getMock().equals(candidate.getMock()) && hasSameMethod(candidate) && argumentsMatch(candidate); + return invocation.getMock().equals(candidate.getMock()) + && hasSameMethod(candidate) + && argumentsMatch(candidate); } /** @@ -107,7 +109,8 @@ public boolean hasSimilarMethod(Invocation candidate) { @Override public boolean hasSameMethod(Invocation candidate) { // not using method.equals() for 1 good reason: - // sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest + // sometimes java generates forwarding methods when generics are in play see + // JavaGenericsForwardingMethodsTest Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); @@ -127,7 +130,8 @@ public Location getLocation() { @Override public void captureArgumentsFrom(Invocation invocation) { - MatcherApplicationStrategy strategy = getMatcherApplicationStrategyFor(invocation, matchers); + MatcherApplicationStrategy strategy = + getMatcherApplicationStrategyFor(invocation, matchers); strategy.forEachMatcherAndArgument(captureArgument()); } @@ -145,9 +149,10 @@ public boolean apply(ArgumentMatcher matcher, Object argument) { }; } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) private boolean argumentsMatch(Invocation actual) { List matchers = getMatchers(); - return getMatcherApplicationStrategyFor(actual, matchers).forEachMatcherAndArgument( matchesTypeSafe()); + return getMatcherApplicationStrategyFor(actual, matchers) + .forEachMatcherAndArgument(matchesTypeSafe()); } } diff --git a/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java b/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java index 75002c74da..f89ca47989 100644 --- a/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java +++ b/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java @@ -16,14 +16,17 @@ public class InvocationsFinder { - private InvocationsFinder() { - } + private InvocationsFinder() {} - public static List findInvocations(List invocations, MatchableInvocation wanted) { + public static List findInvocations( + List invocations, MatchableInvocation wanted) { return ListUtil.filter(invocations, new RemoveNotMatching(wanted)); } - public static List findAllMatchingUnverifiedChunks(List invocations, MatchableInvocation wanted, InOrderContext orderingContext) { + public static List findAllMatchingUnverifiedChunks( + List invocations, + MatchableInvocation wanted, + InOrderContext orderingContext) { List unverified = removeVerifiedInOrder(invocations, orderingContext); return ListUtil.filter(unverified, new RemoveNotMatching(wanted)); } @@ -43,7 +46,11 @@ public static List findAllMatchingUnverifiedChunks(List * if wanted is 1 and mode is times(x), where x != 2 then returns * 1,1,1 */ - public static List findMatchingChunk(List invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) { + public static List findMatchingChunk( + List invocations, + MatchableInvocation wanted, + int wantedCount, + InOrderContext context) { List unverified = removeVerifiedInOrder(invocations, context); List firstChunk = getFirstMatchingChunk(wanted, unverified); @@ -54,7 +61,8 @@ public static List findMatchingChunk(List invocations, M } } - private static List getFirstMatchingChunk(MatchableInvocation wanted, List unverified) { + private static List getFirstMatchingChunk( + MatchableInvocation wanted, List unverified) { List firstChunk = new LinkedList(); for (Invocation invocation : unverified) { if (wanted.matches(invocation)) { @@ -66,16 +74,18 @@ private static List getFirstMatchingChunk(MatchableInvocation wanted return firstChunk; } - public static Invocation findFirstMatchingUnverifiedInvocation(List invocations, MatchableInvocation wanted, InOrderContext context ){ - for( Invocation invocation : removeVerifiedInOrder( invocations, context )){ - if( wanted.matches( invocation )){ + public static Invocation findFirstMatchingUnverifiedInvocation( + List invocations, MatchableInvocation wanted, InOrderContext context) { + for (Invocation invocation : removeVerifiedInOrder(invocations, context)) { + if (wanted.matches(invocation)) { return invocation; } } return null; } - public static Invocation findSimilarInvocation(List invocations, MatchableInvocation wanted) { + public static Invocation findSimilarInvocation( + List invocations, MatchableInvocation wanted) { Invocation firstSimilar = null; for (Invocation invocation : invocations) { if (!wanted.hasSimilarMethod(invocation)) { @@ -115,8 +125,10 @@ public static Location getLastLocation(List invocations) { } } - public static Invocation findPreviousVerifiedInOrder(List invocations, InOrderContext context) { - LinkedList verifiedOnly = ListUtil.filter(invocations, new RemoveUnverifiedInOrder(context)); + public static Invocation findPreviousVerifiedInOrder( + List invocations, InOrderContext context) { + LinkedList verifiedOnly = + ListUtil.filter(invocations, new RemoveUnverifiedInOrder(context)); if (verifiedOnly.isEmpty()) { return null; @@ -125,7 +137,8 @@ public static Invocation findPreviousVerifiedInOrder(List invocation } } - private static List removeVerifiedInOrder(List invocations, InOrderContext orderingContext) { + private static List removeVerifiedInOrder( + List invocations, InOrderContext orderingContext) { List unverified = new LinkedList(); for (Invocation i : invocations) { if (orderingContext.isVerified(i)) { @@ -183,9 +196,10 @@ public boolean isOut(Invocation invocation) { * @param context * @param orderedInvocations */ - public static Invocation findFirstUnverifiedInOrder(InOrderContext context, List orderedInvocations) { + public static Invocation findFirstUnverifiedInOrder( + InOrderContext context, List orderedInvocations) { Invocation candidate = null; - for(Invocation i : orderedInvocations) { + for (Invocation i : orderedInvocations) { if (!context.isVerified(i)) { candidate = candidate != null ? candidate : i; } else { diff --git a/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java index e47156f07f..486e919090 100644 --- a/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java +++ b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java @@ -23,9 +23,10 @@ public class MatcherApplicationStrategy { private final List> matchers; private final MatcherApplicationType matchingType; - - - private MatcherApplicationStrategy(Invocation invocation, List> matchers, MatcherApplicationType matchingType) { + private MatcherApplicationStrategy( + Invocation invocation, + List> matchers, + MatcherApplicationType matchingType) { this.invocation = invocation; if (matchingType == MATCH_EACH_VARARGS_WITH_LAST_MATCHER) { int times = varargLength(invocation); @@ -49,7 +50,8 @@ private MatcherApplicationStrategy(Invocation invocation, Listnull */ - public static MatcherApplicationStrategy getMatcherApplicationStrategyFor(Invocation invocation, List> matchers) { + public static MatcherApplicationStrategy getMatcherApplicationStrategyFor( + Invocation invocation, List> matchers) { MatcherApplicationType type = getMatcherApplicationType(invocation, matchers); return new MatcherApplicationStrategy(invocation, matchers, type); @@ -72,8 +74,7 @@ public static MatcherApplicationStrategy getMatcherApplicationStrategyFor(Invoca * */ public boolean forEachMatcherAndArgument(ArgumentMatcherAction action) { - if (matchingType == ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS) - return false; + if (matchingType == ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS) return false; Object[] arguments = invocation.getArguments(); for (int i = 0; i < arguments.length; i++) { @@ -87,7 +88,8 @@ public boolean forEachMatcherAndArgument(ArgumentMatcherAction action) { return true; } - private static MatcherApplicationType getMatcherApplicationType(Invocation invocation, List> matchers) { + private static MatcherApplicationType getMatcherApplicationType( + Invocation invocation, List> matchers) { final int rawArguments = invocation.getRawArguments().length; final int expandedArguments = invocation.getArguments().length; final int matcherCount = matchers.size(); @@ -106,12 +108,13 @@ private static MatcherApplicationType getMatcherApplicationType(Invocation invoc private static boolean isLastMatcherVarargMatcher(final List> matchers) { ArgumentMatcher argumentMatcher = lastMatcher(matchers); if (argumentMatcher instanceof HamcrestArgumentMatcher) { - return ((HamcrestArgumentMatcher) argumentMatcher).isVarargMatcher(); + return ((HamcrestArgumentMatcher) argumentMatcher).isVarargMatcher(); } return argumentMatcher instanceof VarargMatcher; } - private static List> appendLastMatcherNTimes(List> matchers, int timesToAppendLastMatcher) { + private static List> appendLastMatcherNTimes( + List> matchers, int timesToAppendLastMatcher) { ArgumentMatcher lastMatcher = lastMatcher(matchers); List> expandedMatchers = new ArrayList>(matchers); @@ -132,6 +135,8 @@ private static ArgumentMatcher lastMatcher(List> matchers) } enum MatcherApplicationType { - ONE_MATCHER_PER_ARGUMENT, MATCH_EACH_VARARGS_WITH_LAST_MATCHER, ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS; + ONE_MATCHER_PER_ARGUMENT, + MATCH_EACH_VARARGS_WITH_LAST_MATCHER, + ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS; } } diff --git a/src/main/java/org/mockito/internal/invocation/MatchersBinder.java b/src/main/java/org/mockito/internal/invocation/MatchersBinder.java index 68c2caf2fb..56f5096429 100644 --- a/src/main/java/org/mockito/internal/invocation/MatchersBinder.java +++ b/src/main/java/org/mockito/internal/invocation/MatchersBinder.java @@ -4,7 +4,6 @@ */ package org.mockito.internal.invocation; - import static org.mockito.internal.exceptions.Reporter.invalidUseOfMatchers; import java.io.Serializable; @@ -19,7 +18,8 @@ @SuppressWarnings("unchecked") public class MatchersBinder implements Serializable { - public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) { + public InvocationMatcher bindMatchers( + ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) { List lastMatchers = argumentMatcherStorage.pullLocalizedMatchers(); validateMatchers(invocation, lastMatchers); diff --git a/src/main/java/org/mockito/internal/invocation/RealMethod.java b/src/main/java/org/mockito/internal/invocation/RealMethod.java index a7b5a150e7..8cb8b721a0 100644 --- a/src/main/java/org/mockito/internal/invocation/RealMethod.java +++ b/src/main/java/org/mockito/internal/invocation/RealMethod.java @@ -18,7 +18,6 @@ public interface RealMethod extends Serializable { enum IsIllegal implements RealMethod { - INSTANCE; @Override @@ -34,12 +33,13 @@ public Object invoke() { class FromCallable extends FromBehavior implements RealMethod { public FromCallable(final Callable callable) { - super(new InvocationFactory.RealMethodBehavior() { - @Override - public Object call() throws Throwable { - return callable.call(); - } - }); + super( + new InvocationFactory.RealMethodBehavior() { + @Override + public Object call() throws Throwable { + return callable.call(); + } + }); } } diff --git a/src/main/java/org/mockito/internal/invocation/SerializableMethod.java b/src/main/java/org/mockito/internal/invocation/SerializableMethod.java index dfc3bc46d7..afcdc5647d 100644 --- a/src/main/java/org/mockito/internal/invocation/SerializableMethod.java +++ b/src/main/java/org/mockito/internal/invocation/SerializableMethod.java @@ -24,7 +24,7 @@ public class SerializableMethod implements Serializable, MockitoMethod { private final boolean isVarArgs; private final boolean isAbstract; - private volatile transient Method method; + private transient volatile Method method; public SerializableMethod(Method method) { this.method = method; @@ -69,14 +69,18 @@ public Method getJavaMethod() { method = declaringClass.getDeclaredMethod(methodName, parameterTypes); return method; } catch (SecurityException e) { - String message = String.format( - "The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" + - "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); + String message = + String.format( + "The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" + + "Please report this as a defect with an example of how to reproduce it.", + declaringClass, methodName); throw new MockitoException(message, e); } catch (NoSuchMethodException e) { - String message = String.format( - "The method %1$s.%2$s does not exists and you should not get to this point.\n" + - "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); + String message = + String.format( + "The method %1$s.%2$s does not exists and you should not get to this point.\n" + + "Please report this as a defect with an example of how to reproduce it.", + declaringClass, methodName); throw new MockitoException(message, e); } } @@ -88,30 +92,20 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; SerializableMethod other = (SerializableMethod) obj; if (declaringClass == null) { - if (other.declaringClass != null) - return false; - } else if (!declaringClass.equals(other.declaringClass)) - return false; + if (other.declaringClass != null) return false; + } else if (!declaringClass.equals(other.declaringClass)) return false; if (methodName == null) { - if (other.methodName != null) - return false; - } else if (!methodName.equals(other.methodName)) - return false; - if (!Arrays.equals(parameterTypes, other.parameterTypes)) - return false; + if (other.methodName != null) return false; + } else if (!methodName.equals(other.methodName)) return false; + if (!Arrays.equals(parameterTypes, other.parameterTypes)) return false; if (returnType == null) { - if (other.returnType != null) - return false; - } else if (!returnType.equals(other.returnType)) - return false; + if (other.returnType != null) return false; + } else if (!returnType.equals(other.returnType)) return false; return true; } } diff --git a/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java b/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java index 1452137650..a4b2c4e96a 100644 --- a/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java +++ b/src/main/java/org/mockito/internal/invocation/TypeSafeMatching.java @@ -8,31 +8,29 @@ import org.mockito.ArgumentMatcher; -@SuppressWarnings({"unchecked","rawtypes"}) +@SuppressWarnings({"unchecked", "rawtypes"}) public class TypeSafeMatching implements ArgumentMatcherAction { - private final static ArgumentMatcherAction TYPE_SAFE_MATCHING_ACTION = new TypeSafeMatching(); + private static final ArgumentMatcherAction TYPE_SAFE_MATCHING_ACTION = new TypeSafeMatching(); private TypeSafeMatching() {} - - public static ArgumentMatcherAction matchesTypeSafe(){ + public static ArgumentMatcherAction matchesTypeSafe() { return TYPE_SAFE_MATCHING_ACTION; } + @Override public boolean apply(ArgumentMatcher matcher, Object argument) { return isCompatible(matcher, argument) && matcher.matches(argument); } - /** * Returns true if the given argument can be passed to * the given argumentMatcher without causing a * {@link ClassCastException}. */ private static boolean isCompatible(ArgumentMatcher argumentMatcher, Object argument) { - if (argument == null) - return true; + if (argument == null) return true; Class expectedArgumentType = getArgumentType(argumentMatcher); @@ -51,7 +49,10 @@ private static Class getArgumentType(ArgumentMatcher argumentMatcher) { return method.getParameterTypes()[0]; } } - throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new "); + throw new NoSuchMethodError( + "Method 'matches(T)' not found in ArgumentMatcher: " + + argumentMatcher + + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new "); } /** diff --git a/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java b/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java index 3f8803f86d..5144991784 100644 --- a/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java +++ b/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java @@ -22,10 +22,11 @@ public class UnusedStubsFinder { public List find(List mocks) { List unused = new LinkedList(); for (Object mock : mocks) { - List fromSingleMock = MockUtil.getInvocationContainer(mock).getStubbingsDescending(); - for(Stubbing s : fromSingleMock) { + List fromSingleMock = + MockUtil.getInvocationContainer(mock).getStubbingsDescending(); + for (Stubbing s : fromSingleMock) { if (!s.wasUsed()) { - unused.add(s.getInvocation()); + unused.add(s.getInvocation()); } } } diff --git a/src/main/java/org/mockito/internal/invocation/finder/AllInvocationsFinder.java b/src/main/java/org/mockito/internal/invocation/finder/AllInvocationsFinder.java index 91bb69a6e7..ea9c6d63f4 100644 --- a/src/main/java/org/mockito/internal/invocation/finder/AllInvocationsFinder.java +++ b/src/main/java/org/mockito/internal/invocation/finder/AllInvocationsFinder.java @@ -25,7 +25,8 @@ private AllInvocationsFinder() {} public static List find(Iterable mocks) { Set invocationsInOrder = new TreeSet(new InvocationComparator()); for (Object mock : mocks) { - Collection fromSingleMock = new DefaultMockingDetails(mock).getInvocations(); + Collection fromSingleMock = + new DefaultMockingDetails(mock).getInvocations(); invocationsInOrder.addAll(fromSingleMock); } @@ -41,7 +42,8 @@ public static List find(Iterable mocks) { public static Set findStubbings(Iterable mocks) { Set stubbings = new TreeSet(new StubbingComparator()); for (Object mock : mocks) { - Collection fromSingleMock = new DefaultMockingDetails(mock).getStubbings(); + Collection fromSingleMock = + new DefaultMockingDetails(mock).getStubbings(); stubbings.addAll(fromSingleMock); } diff --git a/src/main/java/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java b/src/main/java/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java index e3a4677c0b..b02011f012 100644 --- a/src/main/java/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java +++ b/src/main/java/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java @@ -22,7 +22,7 @@ public static List find(List mocks) { return ListUtil.filter(invocations, new RemoveIgnoredForVerification()); } - private static class RemoveIgnoredForVerification implements Filter{ + private static class RemoveIgnoredForVerification implements Filter { public boolean isOut(Invocation invocation) { return invocation.isIgnoredForVerification(); } diff --git a/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java b/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java index ed7cf8d8b4..ddf7f6814b 100644 --- a/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java +++ b/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java @@ -28,14 +28,15 @@ public T get() { T ref = this.ref.get(); if (ref == null) { - throw new IllegalStateException("The mock object was garbage collected. " + - "This should not happen in normal circumstances when using public API. " + - "Typically, the test class keeps strong reference to the mock object " + - "and it prevents getting the mock collected. Mockito internally needs " + - "to keep weak references to mock objects to avoid memory leaks for " + - "certain types of MockMaker implementations. If you see this exception " + - "using Mockito public API, please file a bug. For more information see " + - "issue #1313."); + throw new IllegalStateException( + "The mock object was garbage collected. " + + "This should not happen in normal circumstances when using public API. " + + "Typically, the test class keeps strong reference to the mock object " + + "and it prevents getting the mock collected. Mockito internally needs " + + "to keep weak references to mock objects to avoid memory leaks for " + + "certain types of MockMaker implementations. If you see this exception " + + "using Mockito public API, please file a bug. For more information see " + + "issue #1313."); } return ref; diff --git a/src/main/java/org/mockito/internal/junit/ArgMismatchFinder.java b/src/main/java/org/mockito/internal/junit/ArgMismatchFinder.java index e1de44545c..9c4ec4442c 100644 --- a/src/main/java/org/mockito/internal/junit/ArgMismatchFinder.java +++ b/src/main/java/org/mockito/internal/junit/ArgMismatchFinder.java @@ -20,9 +20,13 @@ StubbingArgMismatches getStubbingArgMismatches(Iterable mocks) { continue; } for (Stubbing stubbing : AllInvocationsFinder.findStubbings(mocks)) { - //method name & mock matches - if (!stubbing.wasUsed() && stubbing.getInvocation().getMock() == i.getMock() - && stubbing.getInvocation().getMethod().getName().equals(i.getMethod().getName())) { + // method name & mock matches + if (!stubbing.wasUsed() + && stubbing.getInvocation().getMock() == i.getMock() + && stubbing.getInvocation() + .getMethod() + .getName() + .equals(i.getMethod().getName())) { mismatches.add(i, stubbing.getInvocation()); } } diff --git a/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java b/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java index d5b6eed750..38bbbcc5d0 100644 --- a/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java +++ b/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java @@ -35,36 +35,50 @@ class DefaultStubbingLookupListener implements StubbingLookupListener, Serializa } public void onStubbingLookup(StubbingLookupEvent event) { - Strictness actualStrictness = determineStrictness(event.getStubbingFound(), event.getMockSettings(), currentStrictness); + Strictness actualStrictness = + determineStrictness( + event.getStubbingFound(), event.getMockSettings(), currentStrictness); if (actualStrictness != Strictness.STRICT_STUBS) { return; } if (event.getStubbingFound() == null) { - //If stubbing was not found for invocation it means that either the mock invocation was not stubbed or - //we have a stubbing arg mismatch. - List argMismatchStubbings = potentialArgMismatches(event.getInvocation(), event.getAllStubbings()); + // If stubbing was not found for invocation it means that either the mock invocation was + // not stubbed or + // we have a stubbing arg mismatch. + List argMismatchStubbings = + potentialArgMismatches(event.getInvocation(), event.getAllStubbings()); if (!argMismatchStubbings.isEmpty()) { mismatchesReported = true; Reporter.potentialStubbingProblem(event.getInvocation(), argMismatchStubbings); } } else { - //when strict stubs are in use, every time a stub is realized in the code it is implicitly marked as verified - //this way, the users don't have to repeat themselves to verify stubbed invocations (DRY) + // when strict stubs are in use, every time a stub is realized in the code it is + // implicitly marked as verified + // this way, the users don't have to repeat themselves to verify stubbed invocations + // (DRY) event.getInvocation().markVerified(); } } - private static List potentialArgMismatches(Invocation invocation, Collection stubbings) { + private static List potentialArgMismatches( + Invocation invocation, Collection stubbings) { List matchingStubbings = new LinkedList(); for (Stubbing s : stubbings) { if (UnusedStubbingReporting.shouldBeReported(s) - && s.getInvocation().getMethod().getName().equals(invocation.getMethod().getName()) - //If stubbing and invocation are in the same source file we assume they are in the test code, - // and we don't flag it as mismatch: - && !s.getInvocation().getLocation().getSourceFile().equals(invocation.getLocation().getSourceFile())) { - matchingStubbings.add(s.getInvocation()); + && s.getInvocation() + .getMethod() + .getName() + .equals(invocation.getMethod().getName()) + // If stubbing and invocation are in the same source file we assume they are in + // the test code, + // and we don't flag it as mismatch: + && !s.getInvocation() + .getLocation() + .getSourceFile() + .equals(invocation.getLocation().getSourceFile())) { + matchingStubbings.add(s.getInvocation()); } } return matchingStubbings; diff --git a/src/main/java/org/mockito/internal/junit/DefaultTestFinishedEvent.java b/src/main/java/org/mockito/internal/junit/DefaultTestFinishedEvent.java index c3b348bb5d..269ab9cc27 100644 --- a/src/main/java/org/mockito/internal/junit/DefaultTestFinishedEvent.java +++ b/src/main/java/org/mockito/internal/junit/DefaultTestFinishedEvent.java @@ -9,7 +9,8 @@ public class DefaultTestFinishedEvent implements TestFinishedEvent { private final String testMethodName; private final Throwable testFailure; - public DefaultTestFinishedEvent(Object testClassInstance, String testMethodName, Throwable testFailure) { + public DefaultTestFinishedEvent( + Object testClassInstance, String testMethodName, Throwable testFailure) { this.testClassInstance = testClassInstance; this.testMethodName = testMethodName; this.testFailure = testFailure; diff --git a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java index 171024cb7a..7c5a841abb 100644 --- a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java +++ b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java @@ -8,14 +8,13 @@ public class ExceptionFactory { - private ExceptionFactory() { - } + private ExceptionFactory() {} private static interface ExceptionFactoryImpl { AssertionError create(String message, String wanted, String actual); } - private final static ExceptionFactoryImpl factory; + private static final ExceptionFactoryImpl factory; static { ExceptionFactoryImpl theFactory = null; @@ -42,7 +41,8 @@ private static interface ExceptionFactoryImpl { * it returns an instance of * {@link org.mockito.exceptions.verification.ArgumentsAreDifferent}. */ - public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) { + public static AssertionError createArgumentsAreDifferentException( + String message, String wanted, String actual) { return factory.create(message, wanted, actual); } } diff --git a/src/main/java/org/mockito/internal/junit/JUnitRule.java b/src/main/java/org/mockito/internal/junit/JUnitRule.java index 2ab4be2b1a..aae49ceb50 100644 --- a/src/main/java/org/mockito/internal/junit/JUnitRule.java +++ b/src/main/java/org/mockito/internal/junit/JUnitRule.java @@ -21,8 +21,10 @@ public JUnitRule(MockitoLogger logger, Strictness strictness) { } @Override - public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { - return sessionStore.createStatement(base, target.getClass().getSimpleName() + "." + method.getName(), target); + public Statement apply( + final Statement base, final FrameworkMethod method, final Object target) { + return sessionStore.createStatement( + base, target.getClass().getSimpleName() + "." + method.getName(), target); } public MockitoRule silent() { diff --git a/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java b/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java index 8fe4080af5..fa065acd9c 100644 --- a/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java +++ b/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java @@ -14,54 +14,53 @@ class JUnitSessionStore { - private final MockitoLogger logger; - private MockitoSession session; - protected Strictness strictness; + private final MockitoLogger logger; + private MockitoSession session; + protected Strictness strictness; - JUnitSessionStore(MockitoLogger logger, Strictness strictness) { - this.logger = logger; - this.strictness = strictness; - } + JUnitSessionStore(MockitoLogger logger, Strictness strictness) { + this.logger = logger; + this.strictness = strictness; + } - Statement createStatement(final Statement base, final String methodName, final Object target) { - return new Statement() { - public void evaluate() throws Throwable { - if (session == null) { - session = - Mockito.mockitoSession() - .name(methodName) - .strictness(strictness) - .logger(new MockitoSessionLoggerAdapter(logger)) - .initMocks(target) - .startMocking(); - } else { - MockitoAnnotations.initMocks(target); - } - Throwable testFailure = evaluateSafely(base); - session.finishMocking(testFailure); - if (testFailure != null) { - throw testFailure; - } - } + Statement createStatement(final Statement base, final String methodName, final Object target) { + return new Statement() { + public void evaluate() throws Throwable { + if (session == null) { + session = + Mockito.mockitoSession() + .name(methodName) + .strictness(strictness) + .logger(new MockitoSessionLoggerAdapter(logger)) + .initMocks(target) + .startMocking(); + } else { + MockitoAnnotations.initMocks(target); + } + Throwable testFailure = evaluateSafely(base); + session.finishMocking(testFailure); + if (testFailure != null) { + throw testFailure; + } + } - private Throwable evaluateSafely(Statement base) { - try { - base.evaluate(); - return null; - } catch (Throwable throwable) { - return throwable; - } - } - }; - } - - void setStrictness(Strictness strictness) { - this.strictness = strictness; - // session is null when this method is called during initialization of - // the @Rule field of the test class - if (session != null) { - session.setStrictness(strictness); + private Throwable evaluateSafely(Statement base) { + try { + base.evaluate(); + return null; + } catch (Throwable throwable) { + return throwable; + } + } + }; } - } + void setStrictness(Strictness strictness) { + this.strictness = strictness; + // session is null when this method is called during initialization of + // the @Rule field of the test class + if (session != null) { + session.setStrictness(strictness); + } + } } diff --git a/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java b/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java index 9c496bbc28..6a97e3436c 100644 --- a/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java +++ b/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java @@ -25,13 +25,18 @@ public MismatchReportingTestListener(MockitoLogger logger) { public void testFinished(TestFinishedEvent event) { Collection createdMocks = mocks; - //At this point, we don't need the mocks any more and we can mark all collected mocks for gc - //TODO make it better, it's easy to forget to clean up mocks and we still create new instance of list that nobody will read, it's also duplicated + // At this point, we don't need the mocks any more and we can mark all collected mocks for + // gc + // TODO make it better, it's easy to forget to clean up mocks and we still create new + // instance of list that nobody will read, it's also duplicated mocks = new LinkedList(); if (event.getFailure() != null) { - //print unused stubbings only when test succeeds to avoid reporting multiple problems and confusing users - new ArgMismatchFinder().getStubbingArgMismatches(createdMocks).format(event.getTestName(), logger); + // print unused stubbings only when test succeeds to avoid reporting multiple problems + // and confusing users + new ArgMismatchFinder() + .getStubbingArgMismatches(createdMocks) + .format(event.getTestName(), logger); } } diff --git a/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java b/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java index d23431bae1..8d6cc6c73a 100644 --- a/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java +++ b/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java @@ -12,17 +12,18 @@ */ public class StrictStubsRunnerTestListener implements MockitoTestListener { - private final DefaultStubbingLookupListener stubbingLookupListener = new DefaultStubbingLookupListener(Strictness.STRICT_STUBS); + private final DefaultStubbingLookupListener stubbingLookupListener = + new DefaultStubbingLookupListener(Strictness.STRICT_STUBS); @Override public void testFinished(TestFinishedEvent event) {} @Override public void onMockCreated(Object mock, MockCreationSettings settings) { - //It is not ideal that we modify the state of MockCreationSettings object - //MockCreationSettings is intended to be an immutable view of the creation settings - //However, we our previous listeners work this way and it hasn't backfired. - //Since it is simple and pragmatic, we'll keep it for now. + // It is not ideal that we modify the state of MockCreationSettings object + // MockCreationSettings is intended to be an immutable view of the creation settings + // However, we our previous listeners work this way and it hasn't backfired. + // Since it is simple and pragmatic, we'll keep it for now. settings.getStubbingLookupListeners().add(stubbingLookupListener); } } diff --git a/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java b/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java index 1c7b00ad32..324ba6bc7b 100644 --- a/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java +++ b/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java @@ -17,7 +17,8 @@ */ class StubbingArgMismatches { - final Map> mismatches = new LinkedHashMap>(); + final Map> mismatches = + new LinkedHashMap>(); public void add(Invocation invocation, Invocation stubbing) { Set matchingInvocations = mismatches.get(stubbing); diff --git a/src/main/java/org/mockito/internal/junit/StubbingHint.java b/src/main/java/org/mockito/internal/junit/StubbingHint.java index 3675a4d8a9..8478850a5c 100644 --- a/src/main/java/org/mockito/internal/junit/StubbingHint.java +++ b/src/main/java/org/mockito/internal/junit/StubbingHint.java @@ -12,11 +12,13 @@ class StubbingHint { private final StringBuilder hint; StubbingHint(String testName) { - hint = new StringBuilder("[MockitoHint] ") - .append(testName).append(" (see javadoc for MockitoHint):"); + hint = + new StringBuilder("[MockitoHint] ") + .append(testName) + .append(" (see javadoc for MockitoHint):"); } - void appendLine(Object ... elements) { + void appendLine(Object... elements) { hint.append("\n[MockitoHint] "); for (Object e : elements) { hint.append(e); diff --git a/src/main/java/org/mockito/internal/junit/TestFinishedEvent.java b/src/main/java/org/mockito/internal/junit/TestFinishedEvent.java index 43b373a56f..a2c10cfb73 100644 --- a/src/main/java/org/mockito/internal/junit/TestFinishedEvent.java +++ b/src/main/java/org/mockito/internal/junit/TestFinishedEvent.java @@ -9,5 +9,4 @@ public interface TestFinishedEvent { Throwable getFailure(); String getTestName(); - } diff --git a/src/main/java/org/mockito/internal/junit/UniversalTestListener.java b/src/main/java/org/mockito/internal/junit/UniversalTestListener.java index 6155c19a6a..e94e4a813c 100644 --- a/src/main/java/org/mockito/internal/junit/UniversalTestListener.java +++ b/src/main/java/org/mockito/internal/junit/UniversalTestListener.java @@ -24,7 +24,8 @@ public class UniversalTestListener implements MockitoTestListener, AutoCleanable private Strictness currentStrictness; private final MockitoLogger logger; - private Map mocks = new IdentityHashMap(); + private Map mocks = + new IdentityHashMap(); private DefaultStubbingLookupListener stubbingLookupListener; private boolean listenerDirty; @@ -32,43 +33,59 @@ public UniversalTestListener(Strictness initialStrictness, MockitoLogger logger) this.currentStrictness = initialStrictness; this.logger = logger; - //creating single stubbing lookup listener per junit rule instance / test method - //this way, when strictness is updated in the middle of the test it will affect the behavior of the stubbing listener + // creating single stubbing lookup listener per junit rule instance / test method + // this way, when strictness is updated in the middle of the test it will affect the + // behavior of the stubbing listener this.stubbingLookupListener = new DefaultStubbingLookupListener(currentStrictness); } @Override public void testFinished(TestFinishedEvent event) { Collection createdMocks = mocks.keySet(); - //At this point, we don't need the mocks any more and we can mark all collected mocks for gc - //TODO make it better, it's easy to forget to clean up mocks and we still create new instance of list that nobody will read, it's also duplicated - //TODO clean up all other state, null out stubbingLookupListener + // At this point, we don't need the mocks any more and we can mark all collected mocks for + // gc + // TODO make it better, it's easy to forget to clean up mocks and we still create new + // instance of list that nobody will read, it's also duplicated + // TODO clean up all other state, null out stubbingLookupListener mocks = new IdentityHashMap(); switch (currentStrictness) { - case WARN: emitWarnings(logger, event, createdMocks); break; - case STRICT_STUBS: reportUnusedStubs(event, createdMocks); break; - case LENIENT: break; - default: throw new IllegalStateException("Unknown strictness: " + currentStrictness); + case WARN: + emitWarnings(logger, event, createdMocks); + break; + case STRICT_STUBS: + reportUnusedStubs(event, createdMocks); + break; + case LENIENT: + break; + default: + throw new IllegalStateException("Unknown strictness: " + currentStrictness); } } private void reportUnusedStubs(TestFinishedEvent event, Collection mocks) { - //If there is some other failure (or mismatches were detected) don't report another exception to avoid confusion + // If there is some other failure (or mismatches were detected) don't report another + // exception to avoid confusion if (event.getFailure() == null && !stubbingLookupListener.isMismatchesReported()) { UnusedStubbings unused = new UnusedStubbingsFinder().getUnusedStubbings(mocks); unused.reportUnused(); } } - private static void emitWarnings(MockitoLogger logger, TestFinishedEvent event, Collection mocks) { + private static void emitWarnings( + MockitoLogger logger, TestFinishedEvent event, Collection mocks) { if (event.getFailure() != null) { - //print stubbing mismatches only when there is a test failure - //to avoid false negatives. Give hint only when test fails. - new ArgMismatchFinder().getStubbingArgMismatches(mocks).format(event.getTestName(), logger); + // print stubbing mismatches only when there is a test failure + // to avoid false negatives. Give hint only when test fails. + new ArgMismatchFinder() + .getStubbingArgMismatches(mocks) + .format(event.getTestName(), logger); } else { - //print unused stubbings only when test succeeds to avoid reporting multiple problems and confusing users - new UnusedStubbingsFinder().getUnusedStubbings(mocks).format(event.getTestName(), logger); + // print unused stubbings only when test succeeds to avoid reporting multiple problems + // and confusing users + new UnusedStubbingsFinder() + .getUnusedStubbings(mocks) + .format(event.getTestName(), logger); } } @@ -76,10 +93,11 @@ private static void emitWarnings(MockitoLogger logger, TestFinishedEvent event, public void onMockCreated(Object mock, MockCreationSettings settings) { this.mocks.put(mock, settings); - //It is not ideal that we modify the state of MockCreationSettings object - //MockCreationSettings is intended to be an immutable view of the creation settings - //In future, we should start passing MockSettings object to the creation listener - //TODO #793 - when completed, we should be able to get rid of the CreationSettings casting below + // It is not ideal that we modify the state of MockCreationSettings object + // MockCreationSettings is intended to be an immutable view of the creation settings + // In future, we should start passing MockSettings object to the creation listener + // TODO #793 - when completed, we should be able to get rid of the CreationSettings casting + // below ((CreationSettings) settings).getStubbingLookupListeners().add(stubbingLookupListener); } diff --git a/src/main/java/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java b/src/main/java/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java index 764659373a..ab15143ec3 100644 --- a/src/main/java/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java +++ b/src/main/java/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java @@ -24,15 +24,19 @@ public class UnnecessaryStubbingsReporter implements MockCreationListener { private List mocks = new LinkedList(); public void validateUnusedStubs(Class testClass, RunNotifier notifier) { - Collection unused = new UnusedStubbingsFinder().getUnusedStubbingsByLocation(mocks); + Collection unused = + new UnusedStubbingsFinder().getUnusedStubbingsByLocation(mocks); if (unused.isEmpty()) { - return; //whoa!!! All stubbings were used! + return; // whoa!!! All stubbings were used! } - //Oups, there are unused stubbings - Description unnecessaryStubbings = Description.createTestDescription(testClass, "unnecessary Mockito stubbings"); - notifier.fireTestFailure(new Failure(unnecessaryStubbings, - Reporter.formatUnncessaryStubbingException(testClass, unused))); + // Oups, there are unused stubbings + Description unnecessaryStubbings = + Description.createTestDescription(testClass, "unnecessary Mockito stubbings"); + notifier.fireTestFailure( + new Failure( + unnecessaryStubbings, + Reporter.formatUnncessaryStubbingException(testClass, unused))); } @Override diff --git a/src/main/java/org/mockito/internal/junit/UnusedStubbingsFinder.java b/src/main/java/org/mockito/internal/junit/UnusedStubbingsFinder.java index c602b0771a..3b1fc8c92e 100644 --- a/src/main/java/org/mockito/internal/junit/UnusedStubbingsFinder.java +++ b/src/main/java/org/mockito/internal/junit/UnusedStubbingsFinder.java @@ -31,11 +31,14 @@ public class UnusedStubbingsFinder { public UnusedStubbings getUnusedStubbings(Iterable mocks) { Set stubbings = AllInvocationsFinder.findStubbings(mocks); - List unused = filter(stubbings, new Filter() { - public boolean isOut(Stubbing s) { - return !UnusedStubbingReporting.shouldBeReported(s); - } - }); + List unused = + filter( + stubbings, + new Filter() { + public boolean isOut(Stubbing s) { + return !UnusedStubbingReporting.shouldBeReported(s); + } + }); return new UnusedStubbings(unused); } @@ -53,8 +56,8 @@ public boolean isOut(Stubbing s) { public Collection getUnusedStubbingsByLocation(Iterable mocks) { Set stubbings = AllInvocationsFinder.findStubbings(mocks); - //1st pass, collect all the locations of the stubbings that were used - //note that those are _not_ locations where the stubbings was used + // 1st pass, collect all the locations of the stubbings that were used + // note that those are _not_ locations where the stubbings was used Set locationsOfUsedStubbings = new HashSet(); for (Stubbing s : stubbings) { if (!UnusedStubbingReporting.shouldBeReported(s)) { @@ -63,10 +66,11 @@ public Collection getUnusedStubbingsByLocation(Iterable mock } } - //2nd pass, collect unused stubbings by location - //If the location matches we assume the stubbing was used in at least one test method - //Also, using map to deduplicate reported unused stubbings - // if unused stubbing appear in the setup method / constructor we don't want to report it per each test case + // 2nd pass, collect unused stubbings by location + // If the location matches we assume the stubbing was used in at least one test method + // Also, using map to deduplicate reported unused stubbings + // if unused stubbing appear in the setup method / constructor we don't want to report it + // per each test case Map out = new LinkedHashMap(); for (Stubbing s : stubbings) { String location = s.getInvocation().getLocation().toString(); diff --git a/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java index e54d47864e..4dd81265c3 100644 --- a/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java +++ b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java @@ -36,16 +36,20 @@ public void evaluate() throws Throwable { base.evaluate(); VerificationCollectorImpl.this.collectAndReport(); } finally { - // If base.evaluate() throws an error, we must explicitly reset the VerificationStrategy + // If base.evaluate() throws an error, we must explicitly reset the + // VerificationStrategy // to prevent subsequent tests to be assert lazily - mockingProgress().setVerificationStrategy(MockingProgressImpl.getDefaultVerificationStrategy()); + mockingProgress() + .setVerificationStrategy( + MockingProgressImpl.getDefaultVerificationStrategy()); } } }; } public void collectAndReport() throws MockitoAssertionError { - mockingProgress().setVerificationStrategy(MockingProgressImpl.getDefaultVerificationStrategy()); + mockingProgress() + .setVerificationStrategy(MockingProgressImpl.getDefaultVerificationStrategy()); if (this.numberOfFailures > 0) { String error = this.builder.toString(); @@ -57,25 +61,29 @@ public void collectAndReport() throws MockitoAssertionError { } public VerificationCollector assertLazily() { - mockingProgress().setVerificationStrategy(new VerificationStrategy() { - public VerificationMode maybeVerifyLazily(VerificationMode mode) { - return new VerificationWrapper(mode); - } - }); + mockingProgress() + .setVerificationStrategy( + new VerificationStrategy() { + public VerificationMode maybeVerifyLazily(VerificationMode mode) { + return new VerificationWrapper(mode); + } + }); return this; } private void resetBuilder() { - this.builder = new StringBuilder() - .append("There were multiple verification failures:"); + this.builder = new StringBuilder().append("There were multiple verification failures:"); this.numberOfFailures = 0; } private void append(String message) { this.numberOfFailures++; - this.builder.append('\n') - .append(this.numberOfFailures).append(". ") - .append(message.trim()).append('\n'); + this.builder + .append('\n') + .append(this.numberOfFailures) + .append(". ") + .append(message.trim()) + .append('\n'); } private class VerificationWrapper implements VerificationMode { @@ -98,5 +106,4 @@ public VerificationMode description(String description) { throw new IllegalStateException("Should not fail in this mode"); } } - } diff --git a/src/main/java/org/mockito/internal/junit/util/JUnitFailureHacker.java b/src/main/java/org/mockito/internal/junit/util/JUnitFailureHacker.java index fdeb1790d2..89bd4f1f4b 100644 --- a/src/main/java/org/mockito/internal/junit/util/JUnitFailureHacker.java +++ b/src/main/java/org/mockito/internal/junit/util/JUnitFailureHacker.java @@ -16,13 +16,17 @@ public void appendWarnings(Failure failure, String warnings) { if (isEmpty(warnings)) { return; } - //TODO: this has to protect the use in case jUnit changes and this internal state logic fails + // TODO: this has to protect the use in case jUnit changes and this internal state logic + // fails Throwable throwable = (Throwable) getInternalState(failure, "fThrownException"); - String newMessage = "contains both: actual test failure *and* Mockito warnings.\n" + - warnings + "\n *** The actual failure is because of: ***\n"; + String newMessage = + "contains both: actual test failure *and* Mockito warnings.\n" + + warnings + + "\n *** The actual failure is because of: ***\n"; - ExceptionIncludingMockitoWarnings e = new ExceptionIncludingMockitoWarnings(newMessage, throwable); + ExceptionIncludingMockitoWarnings e = + new ExceptionIncludingMockitoWarnings(newMessage, throwable); e.setStackTrace(throwable.getStackTrace()); setInternalState(failure, "fThrownException", e); } @@ -38,7 +42,9 @@ private static Object getInternalState(Object target, String field) { f.setAccessible(true); return f.get(target); } catch (Exception e) { - throw new RuntimeException("Unable to get internal state on a private field. Please report to mockito mailing list.", e); + throw new RuntimeException( + "Unable to get internal state on a private field. Please report to mockito mailing list.", + e); } } @@ -49,7 +55,9 @@ private static void setInternalState(Object target, String field, Object value) f.setAccessible(true); f.set(target, value); } catch (Exception e) { - throw new RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e); + throw new RuntimeException( + "Unable to set internal state on a private field. Please report to mockito mailing list.", + e); } } @@ -61,9 +69,11 @@ private static Field getFieldFromHierarchy(Class clazz, String field) { } if (f == null) { throw new RuntimeException( - "You want me to get this field: '" + field + - "' on this class: '" + clazz.getSimpleName() + - "' but this field is not declared within the hierarchy of this class!"); + "You want me to get this field: '" + + field + + "' on this class: '" + + clazz.getSimpleName() + + "' but this field is not declared within the hierarchy of this class!"); } return f; } diff --git a/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java b/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java index 0463164dfb..d844727acc 100644 --- a/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java +++ b/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java @@ -16,28 +16,33 @@ public class StubbingLookupNotifier { - public static void notifyStubbedAnswerLookup(Invocation invocation, Stubbing stubbingFound, - Collection allStubbings, CreationSettings creationSettings) { + public static void notifyStubbedAnswerLookup( + Invocation invocation, + Stubbing stubbingFound, + Collection allStubbings, + CreationSettings creationSettings) { List listeners = creationSettings.getStubbingLookupListeners(); if (listeners.isEmpty()) { return; } - StubbingLookupEvent event = new Event(invocation, stubbingFound, allStubbings, creationSettings); + StubbingLookupEvent event = + new Event(invocation, stubbingFound, allStubbings, creationSettings); for (StubbingLookupListener listener : listeners) { listener.onStubbingLookup(event); } } static class Event implements StubbingLookupEvent { - final private Invocation invocation; - final private Stubbing stubbing; - final private Collection allStubbings; - final private MockCreationSettings mockSettings; + private final Invocation invocation; + private final Stubbing stubbing; + private final Collection allStubbings; + private final MockCreationSettings mockSettings; - public Event(Invocation invocation, - Stubbing stubbing, - Collection allStubbings, - MockCreationSettings mockSettings) { + public Event( + Invocation invocation, + Stubbing stubbing, + Collection allStubbings, + MockCreationSettings mockSettings) { this.invocation = invocation; this.stubbing = stubbing; this.allStubbings = allStubbings; diff --git a/src/main/java/org/mockito/internal/listeners/VerificationStartedNotifier.java b/src/main/java/org/mockito/internal/listeners/VerificationStartedNotifier.java index 5703567eb3..c092d2bae5 100644 --- a/src/main/java/org/mockito/internal/listeners/VerificationStartedNotifier.java +++ b/src/main/java/org/mockito/internal/listeners/VerificationStartedNotifier.java @@ -17,7 +17,8 @@ public class VerificationStartedNotifier { - public static Object notifyVerificationStarted(List listeners, MockingDetails originalMockingDetails) { + public static Object notifyVerificationStarted( + List listeners, MockingDetails originalMockingDetails) { if (listeners.isEmpty()) { return originalMockingDetails.getMock(); } @@ -39,14 +40,20 @@ public Event(MockingDetails originalMockingDetails) { public void setMock(Object mock) { if (mock == null) { - throw Reporter.methodDoesNotAcceptParameter("VerificationStartedEvent.setMock", "null parameter."); + throw Reporter.methodDoesNotAcceptParameter( + "VerificationStartedEvent.setMock", "null parameter."); } MockingDetails mockingDetails = Mockito.mockingDetails(mock); if (!mockingDetails.isMock()) { - throw Reporter.methodDoesNotAcceptParameter("VerificationStartedEvent.setMock", "parameter which is not a Mockito mock.\n" + - " Received parameter: " + ValuePrinter.print(mock) + ".\n "); + throw Reporter.methodDoesNotAcceptParameter( + "VerificationStartedEvent.setMock", + "parameter which is not a Mockito mock.\n" + + " Received parameter: " + + ValuePrinter.print(mock) + + ".\n "); } - MockCreationSettings originalMockSettings = this.originalMockingDetails.getMockCreationSettings(); + MockCreationSettings originalMockSettings = + this.originalMockingDetails.getMockCreationSettings(); assertCompatibleTypes(mock, originalMockSettings); this.mock = mock; } @@ -59,20 +66,31 @@ public Object getMock() { static void assertCompatibleTypes(Object mock, MockCreationSettings originalSettings) { Class originalType = originalSettings.getTypeToMock(); if (!originalType.isInstance(mock)) { - throw Reporter.methodDoesNotAcceptParameter("VerificationStartedEvent.setMock", - "parameter which is not the same type as the original mock.\n" + - " Required type: " + originalType.getName() + "\n" + - " Received parameter: " + ValuePrinter.print(mock) + ".\n "); + throw Reporter.methodDoesNotAcceptParameter( + "VerificationStartedEvent.setMock", + "parameter which is not the same type as the original mock.\n" + + " Required type: " + + originalType.getName() + + "\n" + + " Received parameter: " + + ValuePrinter.print(mock) + + ".\n "); } for (Class iface : (Set) originalSettings.getExtraInterfaces()) { if (!iface.isInstance(mock)) { - throw Reporter.methodDoesNotAcceptParameter("VerificationStartedEvent.setMock", - "parameter which does not implement all extra interfaces of the original mock.\n" + - " Required type: " + originalType.getName() + "\n" + - " Required extra interface: " + iface.getName() + "\n" + - " Received parameter: " + ValuePrinter.print(mock) + ".\n "); - + throw Reporter.methodDoesNotAcceptParameter( + "VerificationStartedEvent.setMock", + "parameter which does not implement all extra interfaces of the original mock.\n" + + " Required type: " + + originalType.getName() + + "\n" + + " Required extra interface: " + + iface.getName() + + "\n" + + " Received parameter: " + + ValuePrinter.print(mock) + + ".\n "); } } } diff --git a/src/main/java/org/mockito/internal/matchers/And.java b/src/main/java/org/mockito/internal/matchers/And.java index c27543edb0..bd339adcc4 100644 --- a/src/main/java/org/mockito/internal/matchers/And.java +++ b/src/main/java/org/mockito/internal/matchers/And.java @@ -8,7 +8,7 @@ import org.mockito.ArgumentMatcher; -@SuppressWarnings({ "unchecked", "serial","rawtypes" }) +@SuppressWarnings({"unchecked", "serial", "rawtypes"}) public class And implements ArgumentMatcher, Serializable { private ArgumentMatcher m1; private ArgumentMatcher m2; @@ -23,6 +23,6 @@ public boolean matches(Object actual) { } public String toString() { - return "and("+m1+", "+m2+")"; + return "and(" + m1 + ", " + m2 + ")"; } } diff --git a/src/main/java/org/mockito/internal/matchers/ArrayEquals.java b/src/main/java/org/mockito/internal/matchers/ArrayEquals.java index 87a9588ecf..9ba1c3f37c 100644 --- a/src/main/java/org/mockito/internal/matchers/ArrayEquals.java +++ b/src/main/java/org/mockito/internal/matchers/ArrayEquals.java @@ -48,7 +48,7 @@ public String toString() { } private String appendArray(Object[] array) { - //TODO SF overlap with ValuePrinter + // TODO SF overlap with ValuePrinter StringBuilder out = new StringBuilder("["); for (int i = 0; i < array.length; i++) { out.append(new Equals(array[i]).toString()); diff --git a/src/main/java/org/mockito/internal/matchers/CapturesArguments.java b/src/main/java/org/mockito/internal/matchers/CapturesArguments.java index 0c13853ff7..2e1981c47b 100644 --- a/src/main/java/org/mockito/internal/matchers/CapturesArguments.java +++ b/src/main/java/org/mockito/internal/matchers/CapturesArguments.java @@ -4,9 +4,7 @@ */ package org.mockito.internal.matchers; - public interface CapturesArguments { void captureFrom(Object argument); - } diff --git a/src/main/java/org/mockito/internal/matchers/CapturingMatcher.java b/src/main/java/org/mockito/internal/matchers/CapturingMatcher.java index cb7d7d1cac..6f1dbdd5f8 100644 --- a/src/main/java/org/mockito/internal/matchers/CapturingMatcher.java +++ b/src/main/java/org/mockito/internal/matchers/CapturingMatcher.java @@ -16,7 +16,8 @@ import org.mockito.ArgumentMatcher; @SuppressWarnings("unchecked") -public class CapturingMatcher implements ArgumentMatcher, CapturesArguments, VarargMatcher, Serializable { +public class CapturingMatcher + implements ArgumentMatcher, CapturesArguments, VarargMatcher, Serializable { private final List arguments = new ArrayList(); diff --git a/src/main/java/org/mockito/internal/matchers/CompareTo.java b/src/main/java/org/mockito/internal/matchers/CompareTo.java index e3acafdcda..587bdc501c 100644 --- a/src/main/java/org/mockito/internal/matchers/CompareTo.java +++ b/src/main/java/org/mockito/internal/matchers/CompareTo.java @@ -8,7 +8,8 @@ import org.mockito.ArgumentMatcher; -public abstract class CompareTo> implements ArgumentMatcher, Serializable { +public abstract class CompareTo> + implements ArgumentMatcher, Serializable { private final T wanted; public CompareTo(T value) { @@ -20,7 +21,7 @@ public final boolean matches(T actual) { if (actual == null) { return false; } - if (!actual.getClass().isInstance(wanted)){ + if (!actual.getClass().isInstance(wanted)) { return false; } diff --git a/src/main/java/org/mockito/internal/matchers/Contains.java b/src/main/java/org/mockito/internal/matchers/Contains.java index 5ece3ccd31..ac83ff6de9 100644 --- a/src/main/java/org/mockito/internal/matchers/Contains.java +++ b/src/main/java/org/mockito/internal/matchers/Contains.java @@ -8,7 +8,6 @@ import org.mockito.ArgumentMatcher; - public class Contains implements ArgumentMatcher, Serializable { private final String substring; diff --git a/src/main/java/org/mockito/internal/matchers/Equality.java b/src/main/java/org/mockito/internal/matchers/Equality.java index 9702550bf6..f3dfc117e1 100644 --- a/src/main/java/org/mockito/internal/matchers/Equality.java +++ b/src/main/java/org/mockito/internal/matchers/Equality.java @@ -6,13 +6,13 @@ import java.lang.reflect.Array; -//stolen from hamcrest because I didn't want to have more dependency than Matcher class +// stolen from hamcrest because I didn't want to have more dependency than Matcher class public class Equality { public static boolean areEqual(Object o1, Object o2) { - if (o1 == o2 ) { + if (o1 == o2) { return true; - } else if (o1 == null || o2 == null) { + } else if (o1 == null || o2 == null) { return false; } else if (isArray(o1)) { return isArray(o2) && areArraysEqual(o1, o2); @@ -22,8 +22,7 @@ public static boolean areEqual(Object o1, Object o2) { } static boolean areArraysEqual(Object o1, Object o2) { - return areArrayLengthsEqual(o1, o2) - && areArrayElementsEqual(o1, o2); + return areArrayLengthsEqual(o1, o2) && areArrayElementsEqual(o1, o2); } static boolean areArrayLengthsEqual(Object o1, Object o2) { diff --git a/src/main/java/org/mockito/internal/matchers/Equals.java b/src/main/java/org/mockito/internal/matchers/Equals.java index 5b364784c2..d89fc493b7 100644 --- a/src/main/java/org/mockito/internal/matchers/Equals.java +++ b/src/main/java/org/mockito/internal/matchers/Equals.java @@ -39,7 +39,8 @@ public boolean equals(Object o) { return false; } Equals other = (Equals) o; - return this.wanted == null && other.wanted == null || this.wanted != null && this.wanted.equals(other.wanted); + return this.wanted == null && other.wanted == null + || this.wanted != null && this.wanted.equals(other.wanted); } @Override @@ -48,7 +49,7 @@ public int hashCode() { } public String toStringWithType() { - return "("+ wanted.getClass().getSimpleName() +") " + describe(wanted); + return "(" + wanted.getClass().getSimpleName() + ") " + describe(wanted); } public boolean typeMatches(Object target) { diff --git a/src/main/java/org/mockito/internal/matchers/EqualsWithDelta.java b/src/main/java/org/mockito/internal/matchers/EqualsWithDelta.java index d7f062d60e..82c37bbd49 100644 --- a/src/main/java/org/mockito/internal/matchers/EqualsWithDelta.java +++ b/src/main/java/org/mockito/internal/matchers/EqualsWithDelta.java @@ -28,8 +28,7 @@ public boolean matches(Number actual) { } return wanted.doubleValue() - delta.doubleValue() <= actual.doubleValue() - && actual.doubleValue() <= wanted.doubleValue() - + delta.doubleValue(); + && actual.doubleValue() <= wanted.doubleValue() + delta.doubleValue(); } public String toString() { diff --git a/src/main/java/org/mockito/internal/matchers/InstanceOf.java b/src/main/java/org/mockito/internal/matchers/InstanceOf.java index 1b25507564..706d51b851 100644 --- a/src/main/java/org/mockito/internal/matchers/InstanceOf.java +++ b/src/main/java/org/mockito/internal/matchers/InstanceOf.java @@ -9,7 +9,6 @@ import org.mockito.ArgumentMatcher; import org.mockito.internal.util.Primitives; - public class InstanceOf implements ArgumentMatcher, Serializable { private final Class clazz; @@ -25,8 +24,8 @@ public InstanceOf(Class clazz, String describedAs) { } public boolean matches(Object actual) { - return (actual != null) && - (Primitives.isAssignableFromWrapper(actual.getClass(), clazz) + return (actual != null) + && (Primitives.isAssignableFromWrapper(actual.getClass(), clazz) || clazz.isAssignableFrom(actual.getClass())); } @@ -44,6 +43,4 @@ public VarArgAware(Class clazz, String describedAs) { super(clazz, describedAs); } } - - } diff --git a/src/main/java/org/mockito/internal/matchers/Not.java b/src/main/java/org/mockito/internal/matchers/Not.java index f81315e89a..67e481a7d5 100644 --- a/src/main/java/org/mockito/internal/matchers/Not.java +++ b/src/main/java/org/mockito/internal/matchers/Not.java @@ -8,7 +8,7 @@ import org.mockito.ArgumentMatcher; -@SuppressWarnings({ "unchecked", "serial","rawtypes" }) +@SuppressWarnings({"unchecked", "serial", "rawtypes"}) public class Not implements ArgumentMatcher, Serializable { private final ArgumentMatcher matcher; diff --git a/src/main/java/org/mockito/internal/matchers/NotNull.java b/src/main/java/org/mockito/internal/matchers/NotNull.java index 9c41b3e16e..ff9321156c 100644 --- a/src/main/java/org/mockito/internal/matchers/NotNull.java +++ b/src/main/java/org/mockito/internal/matchers/NotNull.java @@ -12,8 +12,7 @@ public class NotNull implements ArgumentMatcher, Serializable { public static final NotNull NOT_NULL = new NotNull(); - private NotNull() { - } + private NotNull() {} public boolean matches(Object actual) { return actual != null; diff --git a/src/main/java/org/mockito/internal/matchers/Null.java b/src/main/java/org/mockito/internal/matchers/Null.java index 0d6918513c..bb19d17dcb 100644 --- a/src/main/java/org/mockito/internal/matchers/Null.java +++ b/src/main/java/org/mockito/internal/matchers/Null.java @@ -12,8 +12,7 @@ public class Null implements ArgumentMatcher, Serializable { public static final Null NULL = new Null(); - private Null() { - } + private Null() {} public boolean matches(Object actual) { return actual == null; diff --git a/src/main/java/org/mockito/internal/matchers/Or.java b/src/main/java/org/mockito/internal/matchers/Or.java index 71f5574faa..9bba55f133 100644 --- a/src/main/java/org/mockito/internal/matchers/Or.java +++ b/src/main/java/org/mockito/internal/matchers/Or.java @@ -8,7 +8,7 @@ import org.mockito.ArgumentMatcher; -@SuppressWarnings({ "unchecked", "serial","rawtypes" }) +@SuppressWarnings({"unchecked", "serial", "rawtypes"}) public class Or implements ArgumentMatcher, Serializable { private final ArgumentMatcher m1; private final ArgumentMatcher m2; @@ -23,6 +23,6 @@ public boolean matches(Object actual) { } public String toString() { - return "or("+m1+", "+m2+")"; + return "or(" + m1 + ", " + m2 + ")"; } } diff --git a/src/main/java/org/mockito/internal/matchers/VarargMatcher.java b/src/main/java/org/mockito/internal/matchers/VarargMatcher.java index fc843f63b2..43a27596f8 100644 --- a/src/main/java/org/mockito/internal/matchers/VarargMatcher.java +++ b/src/main/java/org/mockito/internal/matchers/VarargMatcher.java @@ -10,5 +10,4 @@ * Internal interface that informs Mockito that the matcher is intended to capture varargs. * This information is needed when mockito collects the arguments. */ -public interface VarargMatcher extends Serializable { -} +public interface VarargMatcher extends Serializable {} diff --git a/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java b/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java index c044ccfe37..9a43040e34 100644 --- a/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java +++ b/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java @@ -90,7 +90,7 @@ public EqualsBuilder() { // do nothing for now. } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- /** *

This method uses reflection to determine if the two Objects @@ -186,7 +186,8 @@ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTrans * @return true if the two Objects have tested equals. * @since 2.1.0 */ - public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass) { + public static boolean reflectionEquals( + Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass) { return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, null); } @@ -216,7 +217,11 @@ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTrans * @return true if the two Objects have tested equals. * @since 2.1.0 */ - public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass, + public static boolean reflectionEquals( + Object lhs, + Object rhs, + boolean testTransients, + Class reflectUpToClass, String[] excludeFields) { if (lhs == rhs) { return true; @@ -277,33 +282,36 @@ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTrans * @param excludeFields array of field names to exclude from testing */ private static void reflectionAppend( - Object lhs, - Object rhs, - Class clazz, - EqualsBuilder builder, - boolean useTransients, - String[] excludeFields) { + Object lhs, + Object rhs, + Class clazz, + EqualsBuilder builder, + boolean useTransients, + String[] excludeFields) { Field[] fields = clazz.getDeclaredFields(); - List excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.emptyList(); + List excludedFieldList = + excludeFields != null + ? Arrays.asList(excludeFields) + : Collections.emptyList(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.isEquals; i++) { Field f = fields[i]; if (!excludedFieldList.contains(f.getName()) - && (f.getName().indexOf('$') == -1) - && (useTransients || !Modifier.isTransient(f.getModifiers())) - && (!Modifier.isStatic(f.getModifiers()))) { + && (f.getName().indexOf('$') == -1) + && (useTransients || !Modifier.isTransient(f.getModifiers())) + && (!Modifier.isStatic(f.getModifiers()))) { try { builder.append(f.get(lhs), f.get(rhs)); } catch (IllegalAccessException e) { - //this can't happen. Would get a Security exception instead - //throw a runtime exception in case the impossible happens. + // this can't happen. Would get a Security exception instead + // throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- /** *

Adds the result of super.equals() to this builder.

@@ -317,7 +325,7 @@ public EqualsBuilder appendSuper(boolean superEquals) { return this; } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- /** *

Test if two Objects are equal using their @@ -341,7 +349,8 @@ public EqualsBuilder append(Object lhs, Object rhs) { Class lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { if (lhs instanceof java.math.BigDecimal && rhs instanceof java.math.BigDecimal) { - isEquals = (((java.math.BigDecimal) lhs).compareTo((java.math.BigDecimal) rhs) == 0); + isEquals = + (((java.math.BigDecimal) lhs).compareTo((java.math.BigDecimal) rhs) == 0); } else { // The simple case, not an array, just test the element isEquals = lhs.equals(rhs); @@ -350,8 +359,8 @@ public EqualsBuilder append(Object lhs, Object rhs) { // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] this.setEquals(false); - // 'Switch' on type of array, to dispatch to the correct handler - // This handles multi dimensional arrays of the same depth + // 'Switch' on type of array, to dispatch to the correct handler + // This handles multi dimensional arrays of the same depth } else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { @@ -485,7 +494,7 @@ public EqualsBuilder append(float lhs, float rhs) { * @param lhs the left hand boolean * @param rhs the right hand boolean * @return EqualsBuilder - used to chain calls. - */ + */ public EqualsBuilder append(boolean lhs, boolean rhs) { isEquals &= (lhs == rhs); return this; diff --git a/src/main/java/org/mockito/internal/matchers/text/MatcherToString.java b/src/main/java/org/mockito/internal/matchers/text/MatcherToString.java index 028059a6c9..3be972e7c5 100644 --- a/src/main/java/org/mockito/internal/matchers/text/MatcherToString.java +++ b/src/main/java/org/mockito/internal/matchers/text/MatcherToString.java @@ -28,10 +28,10 @@ class MatcherToString { */ static String toString(ArgumentMatcher matcher) { Class cls = matcher.getClass(); - while(cls != Object.class) { + while (cls != Object.class) { Method[] methods = cls.getDeclaredMethods(); for (Method m : methods) { - if(isToStringMethod(m)) { + if (isToStringMethod(m)) { return matcher.toString(); } } @@ -39,6 +39,4 @@ static String toString(ArgumentMatcher matcher) { } return decamelizeMatcher(matcher.getClass().getSimpleName()); } - - } diff --git a/src/main/java/org/mockito/internal/matchers/text/MatchersPrinter.java b/src/main/java/org/mockito/internal/matchers/text/MatchersPrinter.java index 044871b013..c770a5bd53 100644 --- a/src/main/java/org/mockito/internal/matchers/text/MatchersPrinter.java +++ b/src/main/java/org/mockito/internal/matchers/text/MatchersPrinter.java @@ -25,7 +25,8 @@ public String getArgumentsBlock(List matchers, PrintSettings pr return ValuePrinter.printValues("(\n ", ",\n ", "\n);", args); } - private Iterator applyPrintSettings(List matchers, PrintSettings printSettings) { + private Iterator applyPrintSettings( + List matchers, PrintSettings printSettings) { List out = new LinkedList(); int i = 0; for (final ArgumentMatcher matcher : matchers) { diff --git a/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java b/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java index 059968e6cb..a5a202782f 100644 --- a/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java +++ b/src/main/java/org/mockito/internal/matchers/text/ValuePrinter.java @@ -16,7 +16,7 @@ */ public class ValuePrinter { - private ValuePrinter(){} + private ValuePrinter() {} /** * Prints given value so that it is neatly readable by humans. @@ -51,21 +51,26 @@ public static String print(final Object value) { return printMap((Map) value); } if (value.getClass().isArray()) { - return printValues("[", ", ", "]", new Iterator() { - private int currentIndex = 0; + return printValues( + "[", + ", ", + "]", + new Iterator() { + private int currentIndex = 0; - public boolean hasNext() { - return currentIndex < Array.getLength(value); - } + public boolean hasNext() { + return currentIndex < Array.getLength(value); + } - public Object next() { - return Array.get(value, currentIndex++); - } + public Object next() { + return Array.get(value, currentIndex++); + } - public void remove() { - throw new UnsupportedOperationException("cannot remove items from an array"); - } - }); + public void remove() { + throw new UnsupportedOperationException( + "cannot remove items from an array"); + } + }); } if (value instanceof FormattedText) { return (((FormattedText) value).getText()); @@ -74,7 +79,7 @@ public void remove() { return descriptionOf(value); } - private static String printMap(Map map) { + private static String printMap(Map map) { StringBuilder result = new StringBuilder(); Iterator> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { @@ -97,19 +102,20 @@ private static String printMap(Map map) { * * @return neatly formatted value list */ - public static String printValues(String start, String separator, String end, Iterator values) { - if(start == null){ + public static String printValues( + String start, String separator, String end, Iterator values) { + if (start == null) { start = "("; } - if (separator == null){ + if (separator == null) { separator = ","; } - if (end == null){ + if (end == null) { end = ")"; } StringBuilder sb = new StringBuilder(start); - while(values.hasNext()) { + while (values.hasNext()) { sb.append(print(values.next())); if (values.hasNext()) { sb.append(separator); @@ -144,8 +150,7 @@ private static String printChar(char value) { private static String descriptionOf(Object value) { try { return valueOf(value); - } - catch (Exception e) { + } catch (Exception e) { return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode()); } } diff --git a/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorage.java b/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorage.java index 4352bda0b0..24bb8a4e21 100644 --- a/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorage.java +++ b/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorage.java @@ -25,5 +25,4 @@ public interface ArgumentMatcherStorage { void validateState(); void reset(); - } diff --git a/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java b/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java index b0dfd0232f..8f903f4ec8 100644 --- a/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java +++ b/src/main/java/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java @@ -80,7 +80,8 @@ private void assertStateFor(String additionalMatcherName, int subMatchersCount) } if (matcherStack.size() < subMatchersCount) { List lastMatchers = resetStack(); - throw incorrectUseOfAdditionalMatchers(additionalMatcherName, subMatchersCount, lastMatchers); + throw incorrectUseOfAdditionalMatchers( + additionalMatcherName, subMatchersCount, lastMatchers); } } @@ -93,5 +94,4 @@ private List resetStack() { reset(); return lastMatchers; } - } diff --git a/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java b/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java index 6e9ac2933f..58c126f842 100644 --- a/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java +++ b/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java @@ -61,7 +61,8 @@ public OngoingStubbing pullOngoingStubbing() { @Override public Set verificationListeners() { - final LinkedHashSet verificationListeners = new LinkedHashSet(); + final LinkedHashSet verificationListeners = + new LinkedHashSet(); for (MockitoListener listener : listeners) { if (listener instanceof VerificationListener) { @@ -72,7 +73,6 @@ public Set verificationListeners() { return verificationListeners; } - public void verificationStarted(VerificationMode verify) { validateState(); resetOngoingStubbing(); @@ -104,7 +104,7 @@ public void stubbingStarted() { public void validateState() { validateMostStuff(); - //validate stubbing: + // validate stubbing: if (stubbingInProgress != null) { Location temp = stubbingInProgress; stubbingInProgress = null; @@ -113,8 +113,9 @@ public void validateState() { } private void validateMostStuff() { - //State is cool when GlobalConfiguration is already loaded - //this cannot really be tested functionally because I cannot dynamically mess up org.mockito.configuration.MockitoConfiguration class + // State is cool when GlobalConfiguration is already loaded + // this cannot really be tested functionally because I cannot dynamically mess up + // org.mockito.configuration.MockitoConfiguration class GlobalConfiguration.validate(); if (verificationMode != null) { @@ -131,9 +132,12 @@ public void stubbingCompleted() { } public String toString() { - return "ongoingStubbing: " + ongoingStubbing + - ", verificationMode: " + verificationMode + - ", stubbingInProgress: " + stubbingInProgress; + return "ongoingStubbing: " + + ongoingStubbing + + ", verificationMode: " + + verificationMode + + ", stubbingInProgress: " + + stubbingInProgress; } public void reset() { @@ -163,17 +167,19 @@ static void addListener(MockitoListener listener, Set listeners List delete = new LinkedList(); for (MockitoListener existing : listeners) { if (existing.getClass().equals(listener.getClass())) { - if (existing instanceof AutoCleanableListener && ((AutoCleanableListener) existing).isListenerDirty()) { - //dirty listener means that there was an exception even before the test started - //if we fail here with redundant mockito listener exception there will be multiple failures causing confusion - //so we simply remove the existing listener and move on + if (existing instanceof AutoCleanableListener + && ((AutoCleanableListener) existing).isListenerDirty()) { + // dirty listener means that there was an exception even before the test started + // if we fail here with redundant mockito listener exception there will be + // multiple failures causing confusion + // so we simply remove the existing listener and move on delete.add(existing); } else { Reporter.redundantMockitoListener(listener.getClass().getSimpleName()); } } } - //delete dirty listeners so they don't occupy state/memory and don't receive notifications + // delete dirty listeners so they don't occupy state/memory and don't receive notifications for (MockitoListener toDelete : delete) { listeners.remove(toDelete); } @@ -196,14 +202,14 @@ public void clearListeners() { listeners.clear(); } - /* + /* - //TODO 545 thread safety of all mockito + //TODO 545 thread safety of all mockito - use cases: - - single threaded execution throughout - - single threaded mock creation, stubbing & verification, multi-threaded interaction with mock - - thread per test case + use cases: + - single threaded execution throughout + - single threaded mock creation, stubbing & verification, multi-threaded interaction with mock + - thread per test case - */ + */ } diff --git a/src/main/java/org/mockito/internal/progress/ThreadSafeMockingProgress.java b/src/main/java/org/mockito/internal/progress/ThreadSafeMockingProgress.java index 4735a118be..adb9b99a2e 100644 --- a/src/main/java/org/mockito/internal/progress/ThreadSafeMockingProgress.java +++ b/src/main/java/org/mockito/internal/progress/ThreadSafeMockingProgress.java @@ -9,15 +9,15 @@ */ public class ThreadSafeMockingProgress { - private static final ThreadLocal MOCKING_PROGRESS_PROVIDER = new ThreadLocal() { - @Override - protected MockingProgress initialValue() { - return new MockingProgressImpl(); - } - }; + private static final ThreadLocal MOCKING_PROGRESS_PROVIDER = + new ThreadLocal() { + @Override + protected MockingProgress initialValue() { + return new MockingProgressImpl(); + } + }; - private ThreadSafeMockingProgress() { - } + private ThreadSafeMockingProgress() {} /** * Returns the {@link MockingProgress} for the current Thread. @@ -26,7 +26,7 @@ private ThreadSafeMockingProgress() { * * @return never null */ - public final static MockingProgress mockingProgress() { + public static final MockingProgress mockingProgress() { return MOCKING_PROGRESS_PROVIDER.get(); } } diff --git a/src/main/java/org/mockito/internal/reporting/PrintSettings.java b/src/main/java/org/mockito/internal/reporting/PrintSettings.java index c6fa92b425..0d1d197df6 100644 --- a/src/main/java/org/mockito/internal/reporting/PrintSettings.java +++ b/src/main/java/org/mockito/internal/reporting/PrintSettings.java @@ -28,7 +28,7 @@ public boolean isMultiline() { return multiline; } - public static PrintSettings verboseMatchers(Integer ... indexesOfMatchers) { + public static PrintSettings verboseMatchers(Integer... indexesOfMatchers) { PrintSettings settings = new PrintSettings(); settings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchers); return settings; @@ -44,7 +44,8 @@ public void setMatchersToBeDescribedWithExtraTypeInfo(Integer[] indexesOfMatcher public String print(List matchers, Invocation invocation) { MatchersPrinter matchersPrinter = new MatchersPrinter(); - String qualifiedName = MockUtil.getMockName(invocation.getMock()) + "." + invocation.getMethod().getName(); + String qualifiedName = + MockUtil.getMockName(invocation.getMock()) + "." + invocation.getMethod().getName(); String invocationString = qualifiedName + matchersPrinter.getArgumentsLine(matchers, this); if (isMultiline() || (!matchers.isEmpty() && invocationString.length() > MAX_LINE_LENGTH)) { return qualifiedName + matchersPrinter.getArgumentsBlock(matchers, this); diff --git a/src/main/java/org/mockito/internal/reporting/SmartPrinter.java b/src/main/java/org/mockito/internal/reporting/SmartPrinter.java index 400133fa5d..7696beefa0 100644 --- a/src/main/java/org/mockito/internal/reporting/SmartPrinter.java +++ b/src/main/java/org/mockito/internal/reporting/SmartPrinter.java @@ -4,7 +4,6 @@ */ package org.mockito.internal.reporting; - import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -22,14 +21,24 @@ public class SmartPrinter { private final String wanted; private final List actuals; - public SmartPrinter(MatchableInvocation wanted, Invocation actual, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) { - this(wanted, Collections.singletonList(actual), indexesOfMatchersToBeDescribedWithExtraTypeInfo); + public SmartPrinter( + MatchableInvocation wanted, + Invocation actual, + Integer... indexesOfMatchersToBeDescribedWithExtraTypeInfo) { + this( + wanted, + Collections.singletonList(actual), + indexesOfMatchersToBeDescribedWithExtraTypeInfo); } - public SmartPrinter(MatchableInvocation wanted, List allActualInvocations, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) { + public SmartPrinter( + MatchableInvocation wanted, + List allActualInvocations, + Integer... indexesOfMatchersToBeDescribedWithExtraTypeInfo) { PrintSettings printSettings = new PrintSettings(); printSettings.setMultiline(isMultiLine(wanted, allActualInvocations)); - printSettings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchersToBeDescribedWithExtraTypeInfo); + printSettings.setMatchersToBeDescribedWithExtraTypeInfo( + indexesOfMatchersToBeDescribedWithExtraTypeInfo); this.wanted = printSettings.print(wanted); @@ -48,7 +57,8 @@ public List getActuals() { return actuals; } - private static boolean isMultiLine(MatchableInvocation wanted, List allActualInvocations) { + private static boolean isMultiLine( + MatchableInvocation wanted, List allActualInvocations) { boolean isWantedMultiline = wanted.toString().contains("\n"); boolean isAnyActualMultiline = false; for (Invocation invocation : allActualInvocations) { diff --git a/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java b/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java index ad115f09b6..f81b01560b 100644 --- a/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java +++ b/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java @@ -24,59 +24,72 @@ public class DefaultInternalRunner implements InternalRunner { private final BlockJUnit4ClassRunner runner; - public DefaultInternalRunner(Class testClass, final Supplier listenerSupplier) throws InitializationError { - runner = new BlockJUnit4ClassRunner(testClass) { + public DefaultInternalRunner( + Class testClass, final Supplier listenerSupplier) + throws InitializationError { + runner = + new BlockJUnit4ClassRunner(testClass) { - public Object target; - private MockitoTestListener mockitoTestListener; + public Object target; + private MockitoTestListener mockitoTestListener; - protected Statement withBefores(FrameworkMethod method, final Object target, Statement statement) { - this.target = target; - final Statement base = super.withBefores(method, target, statement); - return new Statement() { - @Override - public void evaluate() throws Throwable { - if (mockitoTestListener == null) { - // get new test listener and add it to the framework - mockitoTestListener = listenerSupplier.get(); - Mockito.framework().addListener(mockitoTestListener); - // init annotated mocks before tests - MockitoAnnotations.initMocks(target); - } - base.evaluate(); + protected Statement withBefores( + FrameworkMethod method, final Object target, Statement statement) { + this.target = target; + final Statement base = super.withBefores(method, target, statement); + return new Statement() { + @Override + public void evaluate() throws Throwable { + if (mockitoTestListener == null) { + // get new test listener and add it to the framework + mockitoTestListener = listenerSupplier.get(); + Mockito.framework().addListener(mockitoTestListener); + // init annotated mocks before tests + MockitoAnnotations.initMocks(target); + } + base.evaluate(); + } + }; } - }; - } - public void run(final RunNotifier notifier) { - RunListener listener = new RunListener() { - Throwable failure; + public void run(final RunNotifier notifier) { + RunListener listener = + new RunListener() { + Throwable failure; - @Override - public void testFailure(Failure failure) throws Exception { - this.failure = failure.getException(); - } + @Override + public void testFailure(Failure failure) throws Exception { + this.failure = failure.getException(); + } - @Override - public void testFinished(Description description) throws Exception { - try { - if (mockitoTestListener != null) { - Mockito.framework().removeListener(mockitoTestListener); - mockitoTestListener.testFinished(new DefaultTestFinishedEvent(target, description.getMethodName(), failure)); - mockitoTestListener = null; - } - Mockito.validateMockitoUsage(); - } catch (Throwable t) { - //In order to produce clean exception to the user we need to fire test failure with the right description - //Otherwise JUnit framework will report failure with some generic test name - notifier.fireTestFailure(new Failure(description, t)); - } + @Override + public void testFinished(Description description) + throws Exception { + try { + if (mockitoTestListener != null) { + Mockito.framework() + .removeListener(mockitoTestListener); + mockitoTestListener.testFinished( + new DefaultTestFinishedEvent( + target, + description.getMethodName(), + failure)); + mockitoTestListener = null; + } + Mockito.validateMockitoUsage(); + } catch (Throwable t) { + // In order to produce clean exception to the user we + // need to fire test failure with the right description + // Otherwise JUnit framework will report failure with + // some generic test name + notifier.fireTestFailure(new Failure(description, t)); + } + } + }; + notifier.addListener(listener); + super.run(notifier); } }; - notifier.addListener(listener); - super.run(notifier); - } - }; } public void run(final RunNotifier notifier) { diff --git a/src/main/java/org/mockito/internal/runners/InternalRunner.java b/src/main/java/org/mockito/internal/runners/InternalRunner.java index 85b2f3ccb8..d06d005c32 100644 --- a/src/main/java/org/mockito/internal/runners/InternalRunner.java +++ b/src/main/java/org/mockito/internal/runners/InternalRunner.java @@ -17,5 +17,4 @@ public interface InternalRunner extends Filterable { void run(RunNotifier notifier); Description getDescription(); - } diff --git a/src/main/java/org/mockito/internal/runners/RunnerFactory.java b/src/main/java/org/mockito/internal/runners/RunnerFactory.java index e2446b58fb..1af9b8ca8f 100644 --- a/src/main/java/org/mockito/internal/runners/RunnerFactory.java +++ b/src/main/java/org/mockito/internal/runners/RunnerFactory.java @@ -26,22 +26,26 @@ public class RunnerFactory { * Creates silent runner implementation */ public InternalRunner create(Class klass) throws InvocationTargetException { - return create(klass, new Supplier() { - public MockitoTestListener get() { - return new NoOpTestListener(); - } - }); + return create( + klass, + new Supplier() { + public MockitoTestListener get() { + return new NoOpTestListener(); + } + }); } /** * Creates strict runner implementation */ public InternalRunner createStrict(Class klass) throws InvocationTargetException { - return create(klass, new Supplier() { - public MockitoTestListener get() { - return new MismatchReportingTestListener(Plugins.getMockitoLogger()); - } - }); + return create( + klass, + new Supplier() { + public MockitoTestListener get() { + return new MismatchReportingTestListener(Plugins.getMockitoLogger()); + } + }); } /** @@ -50,43 +54,49 @@ public MockitoTestListener get() { * TODO, let's try to apply Brice suggestion and use switch + Strictness */ public InternalRunner createStrictStubs(Class klass) throws InvocationTargetException { - return create(klass, new Supplier() { - public MockitoTestListener get() { - return new StrictStubsRunnerTestListener(); - } - }); + return create( + klass, + new Supplier() { + public MockitoTestListener get() { + return new StrictStubsRunnerTestListener(); + } + }); } /** * Creates runner implementation with provided listener supplier */ - public InternalRunner create(Class klass, Supplier listenerSupplier) throws InvocationTargetException { + public InternalRunner create(Class klass, Supplier listenerSupplier) + throws InvocationTargetException { try { String runnerClassName = "org.mockito.internal.runners.DefaultInternalRunner"; - //Warning: I'm using String literal on purpose! - //When JUnit is not on classpath, we want the code to throw exception here so that we can catch it - //If we statically link the class, we will get Error when class is loaded + // Warning: I'm using String literal on purpose! + // When JUnit is not on classpath, we want the code to throw exception here so that we + // can catch it + // If we statically link the class, we will get Error when class is loaded return new RunnerProvider().newInstance(runnerClassName, klass, listenerSupplier); } catch (InvocationTargetException e) { if (!hasTestMethods(klass)) { throw new MockitoException( - "\n" + - "\n" + - "No tests found in " + klass.getSimpleName() + "\n" + - "Is the method annotated with @Test?\n" + - "Is the method public?\n" - , e); + "\n" + + "\n" + + "No tests found in " + + klass.getSimpleName() + + "\n" + + "Is the method annotated with @Test?\n" + + "Is the method public?\n", + e); } throw e; } catch (Throwable t) { throw new MockitoException( - "\n" + - "\n" + - "MockitoRunner can only be used with JUnit 4.5 or higher.\n" + - "You can upgrade your JUnit version or write your own Runner (please consider contributing your runner to the Mockito community).\n" + - "Bear in mind that you can still enjoy all features of the framework without using runners (they are completely optional).\n" + - "If you get this error despite using JUnit 4.5 or higher then please report this error to the mockito mailing list.\n" - , t); + "\n" + + "\n" + + "MockitoRunner can only be used with JUnit 4.5 or higher.\n" + + "You can upgrade your JUnit version or write your own Runner (please consider contributing your runner to the Mockito community).\n" + + "Bear in mind that you can still enjoy all features of the framework without using runners (they are completely optional).\n" + + "If you get this error despite using JUnit 4.5 or higher then please report this error to the mockito mailing list.\n", + t); } } } diff --git a/src/main/java/org/mockito/internal/runners/StrictRunner.java b/src/main/java/org/mockito/internal/runners/StrictRunner.java index d87289fc5c..5508e0d093 100644 --- a/src/main/java/org/mockito/internal/runners/StrictRunner.java +++ b/src/main/java/org/mockito/internal/runners/StrictRunner.java @@ -28,7 +28,8 @@ public StrictRunner(InternalRunner runner, Class testClass) { } public void run(RunNotifier notifier) { - //TODO need to be able to opt in for full stack trace instead of just relying on the stack trace filter + // TODO need to be able to opt in for full stack trace instead of just relying on the stack + // trace filter UnnecessaryStubbingsReporter reporter = new UnnecessaryStubbingsReporter(); FailureDetector listener = new FailureDetector(); @@ -42,10 +43,12 @@ public void run(RunNotifier notifier) { } if (!filterRequested && listener.isSuccessful()) { - //only report when: - //1. if all tests from given test have ran (filter requested is false) - // Otherwise we would report unnecessary stubs even if the user runs just single test from the class - //2. tests are successful (we don't want to add an extra failure on top of any existing failure, to avoid confusion) + // only report when: + // 1. if all tests from given test have ran (filter requested is false) + // Otherwise we would report unnecessary stubs even if the user runs just single test + // from the class + // 2. tests are successful (we don't want to add an extra failure on top of any existing + // failure, to avoid confusion) reporter.validateUnusedStubs(testClass, notifier); } } diff --git a/src/main/java/org/mockito/internal/runners/util/RunnerProvider.java b/src/main/java/org/mockito/internal/runners/util/RunnerProvider.java index 3bc36fde8e..30c6c4c8c6 100644 --- a/src/main/java/org/mockito/internal/runners/util/RunnerProvider.java +++ b/src/main/java/org/mockito/internal/runners/util/RunnerProvider.java @@ -11,12 +11,14 @@ public class RunnerProvider { - public InternalRunner newInstance(String runnerClassName, Object ... constructorArgs) throws Exception { + public InternalRunner newInstance(String runnerClassName, Object... constructorArgs) + throws Exception { Constructor constructor; try { Class runnerClass = Class.forName(runnerClassName); if (runnerClass.getConstructors().length != 1) { - throw new IllegalArgumentException("Expected " + runnerClassName + " to have exactly one constructor."); + throw new IllegalArgumentException( + "Expected " + runnerClassName + " to have exactly one constructor."); } constructor = runnerClass.getConstructors()[0]; } catch (Exception e) { diff --git a/src/main/java/org/mockito/internal/runners/util/TestMethodsFinder.java b/src/main/java/org/mockito/internal/runners/util/TestMethodsFinder.java index 6d9ea76380..40d71eaa6f 100644 --- a/src/main/java/org/mockito/internal/runners/util/TestMethodsFinder.java +++ b/src/main/java/org/mockito/internal/runners/util/TestMethodsFinder.java @@ -14,7 +14,7 @@ private TestMethodsFinder() {} public static boolean hasTestMethods(Class klass) { Method[] methods = klass.getMethods(); - for(Method m:methods) { + for (Method m : methods) { if (m.isAnnotationPresent(Test.class)) { return true; } diff --git a/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java b/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java index 983e056ef1..b25e85de66 100644 --- a/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java +++ b/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java @@ -62,7 +62,7 @@ public MockitoSessionBuilder logger(MockitoSessionLogger logger) { @Override public MockitoSession startMocking() { - //Configure default values + // Configure default values List effectiveTestClassInstances; String effectiveName; if (testClassInstances.isEmpty()) { @@ -71,10 +71,16 @@ public MockitoSession startMocking() { } else { effectiveTestClassInstances = new ArrayList(testClassInstances); Object lastTestClassInstance = testClassInstances.get(testClassInstances.size() - 1); - effectiveName = this.name == null ? lastTestClassInstance.getClass().getName() : this.name; + effectiveName = + this.name == null ? lastTestClassInstance.getClass().getName() : this.name; } - Strictness effectiveStrictness = this.strictness == null ? Strictness.STRICT_STUBS : this.strictness; - MockitoLogger logger = this.logger == null ? Plugins.getMockitoLogger() : new MockitoLoggerAdapter(this.logger); - return new DefaultMockitoSession(effectiveTestClassInstances, effectiveName, effectiveStrictness, logger); + Strictness effectiveStrictness = + this.strictness == null ? Strictness.STRICT_STUBS : this.strictness; + MockitoLogger logger = + this.logger == null + ? Plugins.getMockitoLogger() + : new MockitoLoggerAdapter(this.logger); + return new DefaultMockitoSession( + effectiveTestClassInstances, effectiveName, effectiveStrictness, logger); } } diff --git a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java index b3bd074428..7a59cf1571 100644 --- a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java +++ b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java @@ -16,8 +16,8 @@ public abstract class BaseStubbing implements OngoingStubbing { - - // Keep strong ref to mock preventing premature garbage collection when using 'One-liner stubs'. See #1541. + // Keep strong ref to mock preventing premature garbage collection when using 'One-liner stubs'. + // See #1541. private final Object strongMockRef; BaseStubbing(Object mock) { @@ -39,7 +39,8 @@ public OngoingStubbing thenReturn(T value, T... values) { OngoingStubbing stubbing = thenReturn(value); if (values == null) { // For no good reason we're configuring null answer here - // This has been like that since forever, so let's keep it for compatibility (unless users complain) + // This has been like that since forever, so let's keep it for compatibility (unless + // users complain) return stubbing.thenReturn(null); } for (T v : values) { @@ -78,7 +79,8 @@ public OngoingStubbing thenThrow(Class throwableType) { } @Override - public OngoingStubbing thenThrow(Class toBeThrown, Class... nextToBeThrown) { + public OngoingStubbing thenThrow( + Class toBeThrown, Class... nextToBeThrown) { if (nextToBeThrown == null) { return thenThrow((Class) null); } diff --git a/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java b/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java index 32ef8eedfd..e6953ea06f 100644 --- a/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java +++ b/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java @@ -20,5 +20,4 @@ public OngoingStubbing thenAnswer(Answer answer) { invocationContainer.addConsecutiveAnswer(answer); return this; } - } diff --git a/src/main/java/org/mockito/internal/stubbing/DefaultLenientStubber.java b/src/main/java/org/mockito/internal/stubbing/DefaultLenientStubber.java index 0f3fe073a1..6986c20e3e 100644 --- a/src/main/java/org/mockito/internal/stubbing/DefaultLenientStubber.java +++ b/src/main/java/org/mockito/internal/stubbing/DefaultLenientStubber.java @@ -13,7 +13,7 @@ public class DefaultLenientStubber implements LenientStubber { - private final static MockitoCore MOCKITO_CORE = new MockitoCore(); + private static final MockitoCore MOCKITO_CORE = new MockitoCore(); @Override public Stubber doThrow(Throwable... toBeThrown) { @@ -26,7 +26,8 @@ public Stubber doThrow(Class toBeThrown) { } @Override - public Stubber doThrow(Class toBeThrown, Class... nextToBeThrown) { + public Stubber doThrow( + Class toBeThrown, Class... nextToBeThrown) { return stubber().doThrow(toBeThrown, nextToBeThrown); } @@ -57,7 +58,8 @@ public Stubber doCallRealMethod() { @Override public OngoingStubbing when(T methodCall) { - OngoingStubbingImpl ongoingStubbing = (OngoingStubbingImpl) MOCKITO_CORE.when(methodCall); + OngoingStubbingImpl ongoingStubbing = + (OngoingStubbingImpl) MOCKITO_CORE.when(methodCall); ongoingStubbing.setStrictness(Strictness.LENIENT); return ongoingStubbing; } diff --git a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java index 07c5a5e41c..fff71000b1 100644 --- a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java +++ b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java @@ -29,7 +29,8 @@ public class InvocationContainerImpl implements InvocationContainer, Serializable { private static final long serialVersionUID = -5334301962749537177L; - private final LinkedList stubbed = new LinkedList(); + private final LinkedList stubbed = + new LinkedList(); private final DoAnswerStyleStubbing doAnswerStyleStubbing; private final RegisteredInvocations registeredInvocations; private final Strictness mockStrictness; @@ -63,7 +64,8 @@ public void addConsecutiveAnswer(Answer answer) { /** * Adds new stubbed answer and returns the invocation matcher the answer was added to. */ - public StubbedInvocationMatcher addAnswer(Answer answer, boolean isConsecutive, Strictness stubbingStrictness) { + public StubbedInvocationMatcher addAnswer( + Answer answer, boolean isConsecutive, Strictness stubbingStrictness) { Invocation invocation = invocationForStubbing.getInvocation(); mockingProgress().stubbingCompleted(); if (answer instanceof ValidableAnswer) { @@ -74,8 +76,11 @@ public StubbedInvocationMatcher addAnswer(Answer answer, boolean isConsecutive, if (isConsecutive) { stubbed.getFirst().addAnswer(answer); } else { - Strictness effectiveStrictness = stubbingStrictness != null ? stubbingStrictness : this.mockStrictness; - stubbed.addFirst(new StubbedInvocationMatcher(answer, invocationForStubbing, effectiveStrictness)); + Strictness effectiveStrictness = + stubbingStrictness != null ? stubbingStrictness : this.mockStrictness; + stubbed.addFirst( + new StubbedInvocationMatcher( + answer, invocationForStubbing, effectiveStrictness)); } return stubbed.getFirst(); } @@ -90,7 +95,8 @@ public StubbedInvocationMatcher findAnswerFor(Invocation invocation) { for (StubbedInvocationMatcher s : stubbed) { if (s.matches(invocation)) { s.markStubUsed(invocation); - //TODO we should mark stubbed at the point of stubbing, not at the point where the stub is being used + // TODO we should mark stubbed at the point of stubbing, not at the point where + // the stub is being used invocation.markStubbed(new StubInfoImpl(s)); return s; } @@ -119,7 +125,10 @@ public void setMethodForStubbing(MatchableInvocation invocation) { invocationForStubbing = invocation; assert hasAnswersForStubbing(); for (int i = 0; i < doAnswerStyleStubbing.getAnswers().size(); i++) { - addAnswer(doAnswerStyleStubbing.getAnswers().get(i), i != 0, doAnswerStyleStubbing.getStubbingStrictness()); + addAnswer( + doAnswerStyleStubbing.getAnswers().get(i), + i != 0, + doAnswerStyleStubbing.getStubbingStrictness()); } doAnswerStyleStubbing.clear(); } @@ -163,7 +172,7 @@ public MatchableInvocation getInvocationForStubbing() { private RegisteredInvocations createRegisteredInvocations(MockCreationSettings mockSettings) { return mockSettings.isStubOnly() - ? new SingleRegisteredInvocation() - : new DefaultRegisteredInvocations(); + ? new SingleRegisteredInvocation() + : new DefaultRegisteredInvocations(); } } diff --git a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java index 3de23b23ff..a5bb0869f0 100644 --- a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java +++ b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java @@ -25,7 +25,7 @@ public OngoingStubbingImpl(InvocationContainerImpl invocationContainer) { @Override public OngoingStubbing thenAnswer(Answer answer) { - if(!invocationContainer.hasInvocationForPotentialStubbing()) { + if (!invocationContainer.hasInvocationForPotentialStubbing()) { throw incorrectUseOfApi(); } @@ -34,7 +34,7 @@ public OngoingStubbing thenAnswer(Answer answer) { } public List getRegisteredInvocations() { - //TODO interface for tests + // TODO interface for tests return invocationContainer.getInvocations(); } diff --git a/src/main/java/org/mockito/internal/stubbing/StrictnessSelector.java b/src/main/java/org/mockito/internal/stubbing/StrictnessSelector.java index 6009e9340e..2509b6de22 100644 --- a/src/main/java/org/mockito/internal/stubbing/StrictnessSelector.java +++ b/src/main/java/org/mockito/internal/stubbing/StrictnessSelector.java @@ -25,7 +25,8 @@ public class StrictnessSelector { * * @return actual strictness, can be null. */ - public static Strictness determineStrictness(Stubbing stubbing, MockCreationSettings mockSettings, Strictness testLevelStrictness) { + public static Strictness determineStrictness( + Stubbing stubbing, MockCreationSettings mockSettings, Strictness testLevelStrictness) { if (stubbing != null && stubbing.getStrictness() != null) { return stubbing.getStrictness(); } diff --git a/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java b/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java index e88c85b2d1..441a4d0e03 100644 --- a/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java +++ b/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java @@ -24,16 +24,17 @@ public class StubbedInvocationMatcher extends InvocationMatcher implements Seria private final Strictness strictness; private DescribedInvocation usedAt; - public StubbedInvocationMatcher(Answer answer, MatchableInvocation invocation, Strictness strictness) { + public StubbedInvocationMatcher( + Answer answer, MatchableInvocation invocation, Strictness strictness) { super(invocation.getInvocation(), invocation.getMatchers()); this.strictness = strictness; this.answers.add(answer); } public Object answer(InvocationOnMock invocation) throws Throwable { - //see ThreadsShareGenerouslyStubbedMockTest + // see ThreadsShareGenerouslyStubbedMockTest Answer a; - synchronized(answers) { + synchronized (answers) { a = answers.size() == 1 ? answers.peek() : answers.poll(); } return a.answer(invocation); diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java index 3f37af64b3..327d0476e2 100644 --- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java +++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java @@ -93,7 +93,8 @@ public Stubber doThrow(Class toBeThrown) { } @Override - public Stubber doThrow(Class toBeThrown, Class... nextToBeThrown) { + public Stubber doThrow( + Class toBeThrown, Class... nextToBeThrown) { Stubber stubber = doThrow(toBeThrown); if (nextToBeThrown == null) { @@ -105,7 +106,6 @@ public Stubber doThrow(Class toBeThrown, Class, Validab public Object answer(InvocationOnMock invocation) throws Throwable { Throwable throwable = getThrowable(); if (throwable == null) { - throw new IllegalStateException("throwable is null: " + - "you shall not call #answer if #validateFor fails!"); + throw new IllegalStateException( + "throwable is null: " + "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; @@ -31,7 +31,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { Throwable t = throwable.fillInStackTrace(); if (t == null) { - //Custom exceptions sometimes return null, see #866 + // Custom exceptions sometimes return null, see #866 throw throwable; } filter.filter(t); diff --git a/src/main/java/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java b/src/main/java/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java index 6aaf520fae..9284716496 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java @@ -28,8 +28,7 @@ public class AnswerFunctionalInterfaces { /** * Hide constructor to avoid instantiation of class with only static methods */ - private AnswerFunctionalInterfaces() { - } + private AnswerFunctionalInterfaces() {} /** * Construct an answer from a two parameter answer interface @@ -42,7 +41,7 @@ public static Answer toAnswer(final Answer1 answer) { return new Answer() { @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { - return answer.answer((A)invocation.getArgument(0)); + return answer.answer((A) invocation.getArgument(0)); } }; } @@ -57,7 +56,7 @@ public static Answer toAnswer(final VoidAnswer1 answer) { return new Answer() { @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) throws Throwable { - answer.answer((A)invocation.getArgument(0)); + answer.answer((A) invocation.getArgument(0)); return null; } }; @@ -75,9 +74,7 @@ public static Answer toAnswer(final Answer2 answer) { return new Answer() { @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { - return answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1)); + return answer.answer((A) invocation.getArgument(0), (B) invocation.getArgument(1)); } }; } @@ -93,9 +90,7 @@ public static Answer toAnswer(final VoidAnswer2 answer) { return new Answer() { @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) throws Throwable { - answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1)); + answer.answer((A) invocation.getArgument(0), (B) invocation.getArgument(1)); return null; } }; @@ -115,9 +110,9 @@ public static Answer toAnswer(final Answer3 answer) @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { return answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1), - (C)invocation.getArgument(2)); + (A) invocation.getArgument(0), + (B) invocation.getArgument(1), + (C) invocation.getArgument(2)); } }; } @@ -135,9 +130,9 @@ public static Answer toAnswer(final VoidAnswer3 answer) @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) throws Throwable { answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1), - (C)invocation.getArgument(2)); + (A) invocation.getArgument(0), + (B) invocation.getArgument(1), + (C) invocation.getArgument(2)); return null; } }; @@ -158,10 +153,10 @@ public static Answer toAnswer(final Answer4 an @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { return answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1), - (C)invocation.getArgument(2), - (D)invocation.getArgument(3)); + (A) invocation.getArgument(0), + (B) invocation.getArgument(1), + (C) invocation.getArgument(2), + (D) invocation.getArgument(3)); } }; } @@ -180,10 +175,10 @@ public static Answer toAnswer(final VoidAnswer4 a @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) throws Throwable { answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1), - (C)invocation.getArgument(2), - (D)invocation.getArgument(3)); + (A) invocation.getArgument(0), + (B) invocation.getArgument(1), + (C) invocation.getArgument(2), + (D) invocation.getArgument(3)); return null; } }; @@ -205,11 +200,11 @@ public static Answer toAnswer(final Answer5 Answer toAnswer(final VoidAnswer5 input parameter 6 type * @return a new answer object */ - public static Answer toAnswer(final Answer6 answer) { + public static Answer toAnswer( + final Answer6 answer) { return new Answer() { @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { return answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1), - (C)invocation.getArgument(2), - (D)invocation.getArgument(3), - (E)invocation.getArgument(4), - (F)invocation.getArgument(5)); + (A) invocation.getArgument(0), + (B) invocation.getArgument(1), + (C) invocation.getArgument(2), + (D) invocation.getArgument(3), + (E) invocation.getArgument(4), + (F) invocation.getArgument(5)); } }; } /** * Construct an answer from a five parameter answer interface - + * * @param answer answer interface * @param input parameter 1 type * @param input parameter 2 type @@ -279,17 +275,18 @@ public T answer(InvocationOnMock invocation) throws Throwable { * @param input parameter 6 type * @return a new answer object */ - public static Answer toAnswer(final VoidAnswer6 answer) { + public static Answer toAnswer( + final VoidAnswer6 answer) { return new Answer() { @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) throws Throwable { answer.answer( - (A)invocation.getArgument(0), - (B)invocation.getArgument(1), - (C)invocation.getArgument(2), - (D)invocation.getArgument(3), - (E)invocation.getArgument(4), - (F)invocation.getArgument(5)); + (A) invocation.getArgument(0), + (B) invocation.getArgument(1), + (C) invocation.getArgument(2), + (D) invocation.getArgument(3), + (E) invocation.getArgument(4), + (F) invocation.getArgument(5)); return null; } }; diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ClonesArguments.java b/src/main/java/org/mockito/internal/stubbing/answers/ClonesArguments.java index 32c4c04757..5861a37dba 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/ClonesArguments.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/ClonesArguments.java @@ -13,8 +13,8 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -//TODO this needs documentation and further analysis - what if someone changes the answer? -//we might think about implementing it straight on MockSettings +// TODO this needs documentation and further analysis - what if someone changes the answer? +// we might think about implementing it straight on MockSettings public class ClonesArguments implements Answer { public Object answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); @@ -24,12 +24,13 @@ public Object answer(InvocationOnMock invocation) throws Throwable { if (from.getClass().isArray()) { int len = Array.getLength(from); Object newInstance = Array.newInstance(from.getClass().getComponentType(), len); - for (int j=0; j, ValidableAnswer, Serializabl private DoesNothing() {} - public static DoesNothing doesNothing(){ + public static DoesNothing doesNothing() { return SINGLETON; } @Override - public Object answer(InvocationOnMock invocation){ + public Object answer(InvocationOnMock invocation) { return null; } diff --git a/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java b/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java index af243ccb81..8bfffca2fe 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java @@ -38,7 +38,8 @@ public boolean isValidException(Throwable throwable) { public boolean isValidReturnType(Class clazz) { if (method.getReturnType().isPrimitive() || clazz.isPrimitive()) { - return Primitives.primitiveTypeOf(clazz) == Primitives.primitiveTypeOf(method.getReturnType()); + return Primitives.primitiveTypeOf(clazz) + == Primitives.primitiveTypeOf(method.getReturnType()); } else { return method.getReturnType().isAssignableFrom(clazz); } @@ -49,11 +50,12 @@ public boolean isValidReturnType(Class clazz) { * E.g: {@code void foo()} or {@code Void bar()} */ public boolean isVoid() { - final MockCreationSettings mockSettings = MockUtil.getMockHandler(invocation.getMock()) - .getMockSettings(); - Class returnType = GenericMetadataSupport.inferFrom(mockSettings.getTypeToMock()) - .resolveGenericReturnType(this.method) - .rawType(); + final MockCreationSettings mockSettings = + MockUtil.getMockHandler(invocation.getMock()).getMockSettings(); + Class returnType = + GenericMetadataSupport.inferFrom(mockSettings.getTypeToMock()) + .resolveGenericReturnType(this.method) + .rawType(); return returnType == Void.TYPE || returnType == Void.class; } diff --git a/src/main/java/org/mockito/internal/stubbing/answers/Returns.java b/src/main/java/org/mockito/internal/stubbing/answers/Returns.java index 145f24516e..184f879204 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/Returns.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/Returns.java @@ -34,11 +34,15 @@ public void validateFor(InvocationOnMock invocation) { } if (returnsNull() && invocationInfo.returnsPrimitive()) { - throw wrongTypeOfReturnValue(invocationInfo.printMethodReturnType(), "null", invocationInfo.getMethodName()); + throw wrongTypeOfReturnValue( + invocationInfo.printMethodReturnType(), "null", invocationInfo.getMethodName()); } if (!returnsNull() && !invocationInfo.isValidReturnType(returnType())) { - throw wrongTypeOfReturnValue(invocationInfo.printMethodReturnType(), printReturnType(), invocationInfo.getMethodName()); + throw wrongTypeOfReturnValue( + invocationInfo.printMethodReturnType(), + printReturnType(), + invocationInfo.getMethodName()); } } diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java index 38c9eec5c2..ce3f2efe67 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java @@ -55,14 +55,14 @@ public Object answer(InvocationOnMock invocation) throws Throwable { int argumentPosition = inferWantedArgumentPosition(invocation); validateIndexWithinInvocationRange(invocation, argumentPosition); - if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentPosition)) { + if (wantedArgIndexIsVarargAndSameTypeAsReturnType( + invocation.getMethod(), argumentPosition)) { // answer raw vararg array argument return ((Invocation) invocation).getRawArguments()[argumentPosition]; } // answer expanded argument at wanted position return invocation.getArgument(argumentPosition); - } @Override @@ -73,17 +73,16 @@ public void validateFor(InvocationOnMock invocation) { } private int inferWantedArgumentPosition(InvocationOnMock invocation) { - if (wantedArgumentPosition == LAST_ARGUMENT) - return invocation.getArguments().length - 1; + if (wantedArgumentPosition == LAST_ARGUMENT) return invocation.getArguments().length - 1; return wantedArgumentPosition; } - private void validateIndexWithinInvocationRange(InvocationOnMock invocation, int argumentPosition) { + private void validateIndexWithinInvocationRange( + InvocationOnMock invocation, int argumentPosition) { if (!wantedArgumentPositionIsValidForInvocation(invocation, argumentPosition)) { - throw invalidArgumentPositionRangeAtInvocationTime(invocation, - wantedArgumentPosition == LAST_ARGUMENT, - wantedArgumentPosition); + throw invalidArgumentPositionRangeAtInvocationTime( + invocation, wantedArgumentPosition == LAST_ARGUMENT, wantedArgumentPosition); } } @@ -92,22 +91,25 @@ private void validateArgumentTypeCompatibility(Invocation invocation, int argume Class inferredArgumentType = inferArgumentType(invocation, argumentPosition); - if (!invocationInfo.isValidReturnType(inferredArgumentType)){ - throw wrongTypeOfArgumentToReturn(invocation, - invocationInfo.printMethodReturnType(), - inferredArgumentType, - wantedArgumentPosition); + if (!invocationInfo.isValidReturnType(inferredArgumentType)) { + throw wrongTypeOfArgumentToReturn( + invocation, + invocationInfo.printMethodReturnType(), + inferredArgumentType, + wantedArgumentPosition); } } - private boolean wantedArgIndexIsVarargAndSameTypeAsReturnType(Method method, int argumentPosition) { + private boolean wantedArgIndexIsVarargAndSameTypeAsReturnType( + Method method, int argumentPosition) { Class[] parameterTypes = method.getParameterTypes(); - return method.isVarArgs() && - argumentPosition == /* vararg index */ parameterTypes.length - 1 && - method.getReturnType().isAssignableFrom(parameterTypes[argumentPosition]); + return method.isVarArgs() + && argumentPosition == /* vararg index */ parameterTypes.length - 1 + && method.getReturnType().isAssignableFrom(parameterTypes[argumentPosition]); } - private boolean wantedArgumentPositionIsValidForInvocation(InvocationOnMock invocation, int argumentPosition) { + private boolean wantedArgumentPositionIsValidForInvocation( + InvocationOnMock invocation, int argumentPosition) { if (argumentPosition < 0) { return false; } @@ -143,11 +145,11 @@ private Class inferArgumentType(Invocation invocation, int argumentIndex) { // if wanted argument is vararg if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentIndex)) { // return the vararg array if return type is compatible - // because the user probably want to return the array itself if the return type is compatible + // because the user probably want to return the array itself if the return type is + // compatible return parameterTypes[argumentIndex]; // move to MethodInfo ? } // return the type in this vararg array return parameterTypes[varargIndex].getComponentType(); - } } diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java index 433c7d2f07..cf7c83a941 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java @@ -36,16 +36,15 @@ public class ReturnsElementsOf implements Answer { public ReturnsElementsOf(Collection elements) { if (elements == null) { - throw new MockitoException("ReturnsElementsOf does not accept null as constructor argument.\n" + - "Please pass a collection instance"); + throw new MockitoException( + "ReturnsElementsOf does not accept null as constructor argument.\n" + + "Please pass a collection instance"); } this.elements = new LinkedList(elements); } public Object answer(InvocationOnMock invocation) throws Throwable { - if (elements.size() == 1) - return elements.get(0); - else - return elements.poll(); + if (elements.size() == 1) return elements.get(0); + else return elements.poll(); } } diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java index 1250a88882..a971201bb8 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java @@ -4,7 +4,6 @@ */ package org.mockito.internal.stubbing.answers; - import java.io.Serializable; import org.mockito.invocation.InvocationOnMock; @@ -31,5 +30,4 @@ public ThrowsException(Throwable throwable) { protected Throwable getThrowable() { return throwable; } - } diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java index 7ef283ccbe..0df0f6c3ef 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java @@ -23,10 +23,10 @@ public class ForwardsInvocations implements Answer, Serializable { private static final long serialVersionUID = -8343690268123254910L; - private Object delegatedObject = null ; + private Object delegatedObject = null; public ForwardsInvocations(Object delegatedObject) { - this.delegatedObject = delegatedObject ; + this.delegatedObject = delegatedObject; } public Object answer(InvocationOnMock invocation) throws Throwable { @@ -35,8 +35,10 @@ public Object answer(InvocationOnMock invocation) throws Throwable { try { Method delegateMethod = getDelegateMethod(mockMethod); - if (!compatibleReturnTypes(mockMethod.getReturnType(), delegateMethod.getReturnType())) { - throw delegatedMethodHasWrongReturnType(mockMethod, delegateMethod, invocation.getMock(), delegatedObject); + if (!compatibleReturnTypes( + mockMethod.getReturnType(), delegateMethod.getReturnType())) { + throw delegatedMethodHasWrongReturnType( + mockMethod, delegateMethod, invocation.getMock(), delegatedObject); } Object[] rawArguments = ((Invocation) invocation).getRawArguments(); @@ -47,7 +49,8 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } return delegateMethod.invoke(delegatedObject, rawArguments); } catch (NoSuchMethodException e) { - throw delegatedMethodDoesNotExistOnDelegate(mockMethod, invocation.getMock(), delegatedObject); + throw delegatedMethodDoesNotExistOnDelegate( + mockMethod, invocation.getMock(), delegatedObject); } catch (InvocationTargetException e) { // propagate the original exception from the delegate throw e.getCause(); @@ -60,7 +63,9 @@ private Method getDelegateMethod(Method mockMethod) throws NoSuchMethodException return mockMethod; } else { // Return method of delegate object with the same signature as mockMethod. - return delegatedObject.getClass().getMethod(mockMethod.getName(), mockMethod.getParameterTypes()); + return delegatedObject + .getClass() + .getMethod(mockMethod.getName(), mockMethod.getParameterTypes()); } } diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java index 515ba5d5f9..3ad69986a1 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java @@ -19,7 +19,7 @@ class RetrieveGenericsForDefaultAnswers { private static final MockitoCore MOCKITO_CORE = new MockitoCore(); static Object returnTypeForMockWithCorrectGenerics( - InvocationOnMock invocation, AnswerCallback answerCallback) { + InvocationOnMock invocation, AnswerCallback answerCallback) { Class type = invocation.getMethod().getReturnType(); final Type returnType = invocation.getMethod().getGenericReturnType(); @@ -88,12 +88,14 @@ private static Object delegateChains(final Class type) { * @param returnType the expected return type * @return the type or null if not found */ - private static Class findTypeFromGeneric(final InvocationOnMock invocation, final TypeVariable returnType) { + private static Class findTypeFromGeneric( + final InvocationOnMock invocation, final TypeVariable returnType) { // Class level - final MockCreationSettings mockSettings = MockUtil.getMockHandler(invocation.getMock()).getMockSettings(); - final GenericMetadataSupport returnTypeSupport = GenericMetadataSupport - .inferFrom(mockSettings.getTypeToMock()) - .resolveGenericReturnType(invocation.getMethod()); + final MockCreationSettings mockSettings = + MockUtil.getMockHandler(invocation.getMock()).getMockSettings(); + final GenericMetadataSupport returnTypeSupport = + GenericMetadataSupport.inferFrom(mockSettings.getTypeToMock()) + .resolveGenericReturnType(invocation.getMethod()); final Class rawType = returnTypeSupport.rawType(); // Method level @@ -110,7 +112,8 @@ private static Class findTypeFromGeneric(final InvocationOnMock invocation, f * @param returnType the expected return type * @return the return type or null if the return type cannot be found */ - private static Class findTypeFromGenericInArguments(final InvocationOnMock invocation, final TypeVariable returnType) { + private static Class findTypeFromGenericInArguments( + final InvocationOnMock invocation, final TypeVariable returnType) { final Type[] parameterTypes = invocation.getMethod().getGenericParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { Type argType = parameterTypes[i]; diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java index a0c537fe79..9a4469f11a 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java @@ -48,7 +48,8 @@ public class ReturnsDeepStubs implements Answer, Serializable { public Object answer(InvocationOnMock invocation) throws Throwable { GenericMetadataSupport returnTypeGenericMetadata = - actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod()); + actualParameterizedType(invocation.getMock()) + .resolveGenericReturnType(invocation.getMethod()); Class rawType = returnTypeGenericMetadata.rawType(); if (!mockitoCore().isTypeMockable(rawType)) { @@ -60,9 +61,11 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } // When dealing with erased generics, we only receive the Object type as rawType. At this - // point, there is nothing to salvage for Mockito. Instead of trying to be smart and generate + // point, there is nothing to salvage for Mockito. Instead of trying to be smart and + // generate // a mock that would potentially match the return signature, instead return `null`. This - // is valid per the CheckCast JVM instruction and is better than causing a ClassCastException + // is valid per the CheckCast JVM instruction and is better than causing a + // ClassCastException // on runtime. if (rawType.equals(Object.class) && !returnTypeGenericMetadata.hasRawExtraInterfaces()) { return null; @@ -71,7 +74,9 @@ public Object answer(InvocationOnMock invocation) throws Throwable { return deepStub(invocation, returnTypeGenericMetadata); } - private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable { + private Object deepStub( + InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) + throws Throwable { InvocationContainerImpl container = MockUtil.getInvocationContainer(invocation.getMock()); // matches invocation for verification @@ -83,10 +88,10 @@ private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport retu } // record deep stub answer - StubbedInvocationMatcher stubbing = recordDeepStubAnswer( - newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()), - container - ); + StubbedInvocationMatcher stubbing = + recordDeepStubAnswer( + newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()), + container); // deep stubbing creates a stubbing and immediately uses it // so the stubbing is actually used by the same invocation @@ -106,47 +111,57 @@ private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport retu * @param parentMock The parent of the current deep stub mock. * @return The mock */ - private Object newDeepStubMock(GenericMetadataSupport returnTypeGenericMetadata, Object parentMock) { + private Object newDeepStubMock( + GenericMetadataSupport returnTypeGenericMetadata, Object parentMock) { MockCreationSettings parentMockSettings = MockUtil.getMockSettings(parentMock); - return mockitoCore().mock( - returnTypeGenericMetadata.rawType(), - withSettingsUsing(returnTypeGenericMetadata, parentMockSettings) - ); + return mockitoCore() + .mock( + returnTypeGenericMetadata.rawType(), + withSettingsUsing(returnTypeGenericMetadata, parentMockSettings)); } - private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) { - MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ? - withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces()) - : withSettings(); + private MockSettings withSettingsUsing( + GenericMetadataSupport returnTypeGenericMetadata, + MockCreationSettings parentMockSettings) { + MockSettings mockSettings = + returnTypeGenericMetadata.hasRawExtraInterfaces() + ? withSettings() + .extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces()) + : withSettings(); return propagateSerializationSettings(mockSettings, parentMockSettings) - .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata)); + .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata)); } - private MockSettings propagateSerializationSettings(MockSettings mockSettings, MockCreationSettings parentMockSettings) { + private MockSettings propagateSerializationSettings( + MockSettings mockSettings, MockCreationSettings parentMockSettings) { return mockSettings.serializable(parentMockSettings.getSerializableMode()); } - private ReturnsDeepStubs returnsDeepStubsAnswerUsing(final GenericMetadataSupport returnTypeGenericMetadata) { + private ReturnsDeepStubs returnsDeepStubsAnswerUsing( + final GenericMetadataSupport returnTypeGenericMetadata) { return new ReturnsDeepStubsSerializationFallback(returnTypeGenericMetadata); } - private StubbedInvocationMatcher recordDeepStubAnswer(final Object mock, InvocationContainerImpl container) { + private StubbedInvocationMatcher recordDeepStubAnswer( + final Object mock, InvocationContainerImpl container) { DeeplyStubbedAnswer answer = new DeeplyStubbedAnswer(mock); return container.addAnswer(answer, false, null); } protected GenericMetadataSupport actualParameterizedType(Object mock) { - CreationSettings mockSettings = (CreationSettings) MockUtil.getMockHandler(mock).getMockSettings(); + CreationSettings mockSettings = + (CreationSettings) MockUtil.getMockHandler(mock).getMockSettings(); return GenericMetadataSupport.inferFrom(mockSettings.getTypeToMock()); } - - private static class ReturnsDeepStubsSerializationFallback extends ReturnsDeepStubs implements Serializable { + private static class ReturnsDeepStubsSerializationFallback extends ReturnsDeepStubs + implements Serializable { @SuppressWarnings("serial") // not gonna be serialized private final GenericMetadataSupport returnTypeGenericMetadata; - public ReturnsDeepStubsSerializationFallback(GenericMetadataSupport returnTypeGenericMetadata) { + public ReturnsDeepStubsSerializationFallback( + GenericMetadataSupport returnTypeGenericMetadata) { this.returnTypeGenericMetadata = returnTypeGenericMetadata; } @@ -168,9 +183,9 @@ private Object writeReplace() throws IOException { } } - private static class DeeplyStubbedAnswer implements Answer, Serializable { - @SuppressWarnings("serial") // serialization will fail with a nice message if mock not serializable + @SuppressWarnings( + "serial") // serialization will fail with a nice message if mock not serializable private final Object mock; DeeplyStubbedAnswer(Object mock) { @@ -182,7 +197,6 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } } - private static MockitoCore mockitoCore() { return LazyHolder.MOCKITO_CORE; } diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java index 7e2ed1b829..13de3390ba 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java @@ -53,7 +53,6 @@ public class ReturnsEmptyValues implements Answer, Serializable { private static final long serialVersionUID = 1998191268711234347L; - /* (non-Javadoc) * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock) */ @@ -62,14 +61,18 @@ public Object answer(InvocationOnMock invocation) { Object mock = invocation.getMock(); MockName name = MockUtil.getMockName(mock); if (name.isDefault()) { - return "Mock for " + MockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode(); + return "Mock for " + + MockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + + ", hashCode: " + + mock.hashCode(); } else { return name.toString(); } } else if (isCompareToMethod(invocation.getMethod())) { - //see issue 184. - //mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good). - //Only for compareTo() method by the Comparable interface + // see issue 184. + // mocks by default should return 0 if references are the same, otherwise some other + // value because they are not the same. Hence we return 1 (anything but 0 is good). + // Only for compareTo() method by the Comparable interface return invocation.getMock() == invocation.getArgument(0) ? 0 : 1; } @@ -80,8 +83,9 @@ public Object answer(InvocationOnMock invocation) { Object returnValueFor(Class type) { if (Primitives.isPrimitiveOrWrapper(type)) { return Primitives.defaultValue(type); - //new instances are used instead of Collections.emptyList(), etc. - //to avoid UnsupportedOperationException if code under test modifies returned collection + // new instances are used instead of Collections.emptyList(), etc. + // to avoid UnsupportedOperationException if code under test modifies returned + // collection } else if (type == Iterable.class) { return new ArrayList(0); } else if (type == Collection.class) { @@ -134,7 +138,7 @@ Object returnValueFor(Class type) { return JavaEightUtil.emptyPeriod(); } - //Let's not care about the rest of collections. + // Let's not care about the rest of collections. return null; } } diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java index 867c8794d8..0ef6f0d954 100755 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java @@ -24,17 +24,19 @@ public Object answer(final InvocationOnMock invocation) throws Throwable { return defaultReturnValue; } - return RetrieveGenericsForDefaultAnswers.returnTypeForMockWithCorrectGenerics(invocation, - new RetrieveGenericsForDefaultAnswers.AnswerCallback() { - @Override - public Object apply(Class type) { - if (type == null) { - return null; + return RetrieveGenericsForDefaultAnswers.returnTypeForMockWithCorrectGenerics( + invocation, + new RetrieveGenericsForDefaultAnswers.AnswerCallback() { + @Override + public Object apply(Class type) { + if (type == null) { + return null; + } + + return Mockito.mock( + type, + new MockSettingsImpl().defaultAnswer(ReturnsMocks.this)); } - - return Mockito - .mock(type, new MockSettingsImpl().defaultAnswer(ReturnsMocks.this)); - } - }); + }); } } diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java index 2de1c70245..76383231a7 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java @@ -65,7 +65,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { Object returnValueFor(Class type) { if (type == String.class) { return ""; - } else if (type.isArray()) { + } else if (type.isArray()) { Class componentType = type.getComponentType(); return Array.newInstance(componentType, 0); } diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java index ae5c01d03d..bbf77060e4 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java @@ -47,17 +47,19 @@ public Object answer(final InvocationOnMock invocation) throws Throwable { return defaultReturnValue; } - return RetrieveGenericsForDefaultAnswers.returnTypeForMockWithCorrectGenerics(invocation, - new RetrieveGenericsForDefaultAnswers.AnswerCallback() { - @Override - public Object apply(Class type) { - if (type == null) { - return null; + return RetrieveGenericsForDefaultAnswers.returnTypeForMockWithCorrectGenerics( + invocation, + new RetrieveGenericsForDefaultAnswers.AnswerCallback() { + @Override + public Object apply(Class type) { + if (type == null) { + return null; + } + + return Mockito.mock( + type, new ThrowsSmartNullPointer(invocation, new LocationImpl())); } - - return Mockito.mock(type, new ThrowsSmartNullPointer(invocation, new LocationImpl())); - } - }); + }); } private static class ThrowsSmartNullPointer implements Answer { @@ -73,8 +75,8 @@ private static class ThrowsSmartNullPointer implements Answer { public Object answer(InvocationOnMock currentInvocation) throws Throwable { if (isToStringMethod(currentInvocation.getMethod())) { - return "SmartNull returned by this unstubbed method call on a mock:\n" + - unstubbedInvocation.toString(); + return "SmartNull returned by this unstubbed method call on a mock:\n" + + unstubbedInvocation.toString(); } throw smartNullPointerException(unstubbedInvocation.toString(), location); diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java index bb2389f9cd..bd08c03670 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java @@ -10,7 +10,7 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -public class TriesToReturnSelf implements Answer, Serializable{ +public class TriesToReturnSelf implements Answer, Serializable { private final ReturnsEmptyValues defaultReturn = new ReturnsEmptyValues(); @@ -25,5 +25,4 @@ public Object answer(InvocationOnMock invocation) throws Throwable { return defaultReturn.returnValueFor(methodReturnType); } - } diff --git a/src/main/java/org/mockito/internal/util/Checks.java b/src/main/java/org/mockito/internal/util/Checks.java index 9aa2a00cff..ba21e132bb 100644 --- a/src/main/java/org/mockito/internal/util/Checks.java +++ b/src/main/java/org/mockito/internal/util/Checks.java @@ -14,7 +14,7 @@ public static T checkNotNull(T value, String checkedValue) { } public static T checkNotNull(T value, String checkedValue, String additionalMessage) { - if(value == null) { + if (value == null) { String message = checkedValue + " should not be null"; if (additionalMessage != null) { message += ". " + additionalMessage; diff --git a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java index 6d4ded34f0..e9887a57b5 100644 --- a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java +++ b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java @@ -23,17 +23,17 @@ public class DefaultMockingDetails implements MockingDetails { private final Object toInspect; - public DefaultMockingDetails(Object toInspect){ + public DefaultMockingDetails(Object toInspect) { this.toInspect = toInspect; } @Override - public boolean isMock(){ + public boolean isMock() { return MockUtil.isMock(toInspect); } @Override - public boolean isSpy(){ + public boolean isSpy() { return MockUtil.isSpy(toInspect); } @@ -80,9 +80,13 @@ private MockHandler mockHandler() { private void assertGoodMock() { if (toInspect == null) { - throw new NotAMockException("Argument passed to Mockito.mockingDetails() should be a mock, but is null!"); + throw new NotAMockException( + "Argument passed to Mockito.mockingDetails() should be a mock, but is null!"); } else if (!isMock()) { - throw new NotAMockException("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of " + toInspect.getClass() + "!"); + throw new NotAMockException( + "Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of " + + toInspect.getClass() + + "!"); } } } diff --git a/src/main/java/org/mockito/internal/util/JavaEightUtil.java b/src/main/java/org/mockito/internal/util/JavaEightUtil.java index 5b2ffc3fb7..bc39d44b68 100644 --- a/src/main/java/org/mockito/internal/util/JavaEightUtil.java +++ b/src/main/java/org/mockito/internal/util/JavaEightUtil.java @@ -41,7 +41,6 @@ public static Object emptyOptional() { return emptyOptional = invokeNullaryFactoryMethod("java.util.Optional", "empty"); } - /** * Creates an empty OptionalDouble using reflection to stay backwards-compatible with older JDKs. * @@ -53,7 +52,8 @@ public static Object emptyOptionalDouble() { return emptyOptionalDouble; } - return emptyOptionalDouble = invokeNullaryFactoryMethod("java.util.OptionalDouble", "empty"); + return emptyOptionalDouble = + invokeNullaryFactoryMethod("java.util.OptionalDouble", "empty"); } /** @@ -124,7 +124,6 @@ public static Object emptyLongStream() { return invokeNullaryFactoryMethod("java.util.stream.LongStream", "empty"); } - /** * Creates an empty Duration using reflection to stay backwards-compatible with older JDKs. * @@ -168,11 +167,10 @@ private static Object invokeNullaryFactoryMethod(final String fqcn, final String // already been verified } catch (final Exception e) { throw new InstantiationException( - String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e); + String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e); } } - /** * Gets a value of the classes' field using reflection to stay backwards-compatible with older JDKs. * @@ -189,7 +187,7 @@ private static Object getStaticFieldValue(final String fqcn, final String fieldN // already been verified } catch (Exception e) { throw new InstantiationException( - String.format("Could not get %s#%s(): %s", fqcn, fieldName, e), e); + String.format("Could not get %s#%s(): %s", fqcn, fieldName, e), e); } } @@ -205,8 +203,7 @@ private static Class getClass(String fqcn) { // any exception is really unexpected since the type name has // already been verified } catch (ClassNotFoundException e) { - throw new InstantiationException( - String.format("Could not find %s: %s", fqcn, e), e); + throw new InstantiationException(String.format("Could not find %s: %s", fqcn, e), e); } } @@ -218,13 +215,14 @@ private static Class getClass(String fqcn) { * @param parameterClasses The list of parameters. * @return The Method object that matches the specified name and parameterTypes. */ - private static Method getMethod(final String fqcn, final String methodName, final Class... parameterClasses) { + private static Method getMethod( + final String fqcn, final String methodName, final Class... parameterClasses) { try { final Class type = getClass(fqcn); return type.getMethod(methodName, parameterClasses); } catch (Exception e) { throw new InstantiationException( - String.format("Could not find %s#%s(): %s", fqcn, methodName, e), e); + String.format("Could not find %s#%s(): %s", fqcn, methodName, e), e); } } } diff --git a/src/main/java/org/mockito/internal/util/MockCreationValidator.java b/src/main/java/org/mockito/internal/util/MockCreationValidator.java index 5dba3467f1..7baa4e252f 100644 --- a/src/main/java/org/mockito/internal/util/MockCreationValidator.java +++ b/src/main/java/org/mockito/internal/util/MockCreationValidator.java @@ -25,7 +25,8 @@ public void validateType(Class classToMock) { } } - public void validateExtraInterfaces(Class classToMock, Collection> extraInterfaces) { + public void validateExtraInterfaces( + Class classToMock, Collection> extraInterfaces) { if (extraInterfaces == null) { return; } diff --git a/src/main/java/org/mockito/internal/util/MockNameImpl.java b/src/main/java/org/mockito/internal/util/MockNameImpl.java index 6a1459145f..a06975871d 100644 --- a/src/main/java/org/mockito/internal/util/MockNameImpl.java +++ b/src/main/java/org/mockito/internal/util/MockNameImpl.java @@ -31,10 +31,10 @@ public MockNameImpl(String mockName) { private static String toInstanceName(Class clazz) { String className = clazz.getSimpleName(); if (className.length() == 0) { - //it's an anonymous class, let's get name from the parent + // it's an anonymous class, let's get name from the parent className = clazz.getSuperclass().getSimpleName(); } - //lower case first letter + // lower case first letter return className.substring(0, 1).toLowerCase() + className.substring(1); } diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java index ec5e7a1f7a..7dec584f4e 100644 --- a/src/main/java/org/mockito/internal/util/MockUtil.java +++ b/src/main/java/org/mockito/internal/util/MockUtil.java @@ -26,11 +26,11 @@ public class MockUtil { private MockUtil() {} public static TypeMockability typeMockabilityOf(Class type) { - return mockMaker.isTypeMockable(type); + return mockMaker.isTypeMockable(type); } public static T createMock(MockCreationSettings settings) { - MockHandler mockHandler = createMockHandler(settings); + MockHandler mockHandler = createMockHandler(settings); T mock = mockMaker.createMock(settings, mockHandler); @@ -67,16 +67,21 @@ public static InvocationContainerImpl getInvocationContainer(Object mock) { } public static boolean isSpy(Object mock) { - return isMock(mock) && getMockSettings(mock).getDefaultAnswer() == Mockito.CALLS_REAL_METHODS; + return isMock(mock) + && getMockSettings(mock).getDefaultAnswer() == Mockito.CALLS_REAL_METHODS; } public static boolean isMock(Object mock) { - // TODO SF (perf tweak) in our codebase we call mockMaker.getHandler() multiple times unnecessarily - // This is not ideal because getHandler() can be expensive (reflective calls inside mock maker) - // The frequent pattern in the codebase are separate calls to: 1) isMock(mock) then 2) getMockHandler(mock) + // TODO SF (perf tweak) in our codebase we call mockMaker.getHandler() multiple times + // unnecessarily + // This is not ideal because getHandler() can be expensive (reflective calls inside mock + // maker) + // The frequent pattern in the codebase are separate calls to: 1) isMock(mock) then 2) + // getMockHandler(mock) // We could replace it with using mockingDetails().isMock() // Let's refactor the codebase and use new mockingDetails() in all relevant places. - // Potentially we could also move other methods to MockitoMock, some other candidates: getInvocationContainer, isSpy, etc. + // Potentially we could also move other methods to MockitoMock, some other candidates: + // getInvocationContainer, isSpy, etc. // This also allows us to reuse our public API MockingDetails return mock != null && mockMaker.getHandler(mock) != null; } @@ -87,7 +92,7 @@ public static MockName getMockName(Object mock) { public static void maybeRedefineMockName(Object mock, String newName) { MockName mockName = getMockName(mock); - //TODO SF hacky... + // TODO SF hacky... MockCreationSettings mockSettings = getMockHandler(mock).getMockSettings(); if (mockName.isDefault() && mockSettings instanceof CreationSettings) { ((CreationSettings) mockSettings).setMockName(new MockNameImpl(newName)); diff --git a/src/main/java/org/mockito/internal/util/ObjectMethodsGuru.java b/src/main/java/org/mockito/internal/util/ObjectMethodsGuru.java index 8fab11e23b..b46f29a090 100644 --- a/src/main/java/org/mockito/internal/util/ObjectMethodsGuru.java +++ b/src/main/java/org/mockito/internal/util/ObjectMethodsGuru.java @@ -9,16 +9,15 @@ import org.mockito.internal.creation.DelegatingMethod; import org.mockito.internal.invocation.MockitoMethod; -public class ObjectMethodsGuru{ +public class ObjectMethodsGuru { - private ObjectMethodsGuru() { - } + private ObjectMethodsGuru() {} public static boolean isToStringMethod(Method method) { MockitoMethod m = new DelegatingMethod(method); - return m.getReturnType() == String.class && - m.getParameterTypes().length == 0 && - "toString".equals(m.getName()); + return m.getReturnType() == String.class + && m.getParameterTypes().length == 0 + && "toString".equals(m.getName()); } public static boolean isCompareToMethod(Method method) { diff --git a/src/main/java/org/mockito/internal/util/Platform.java b/src/main/java/org/mockito/internal/util/Platform.java index 48ae3ab282..200fc511d6 100644 --- a/src/main/java/org/mockito/internal/util/Platform.java +++ b/src/main/java/org/mockito/internal/util/Platform.java @@ -12,8 +12,10 @@ public abstract class Platform { - private static final Pattern JAVA_8_RELEASE_VERSION_SCHEME = Pattern.compile("1\\.8\\.0_(\\d+)(?:-ea)?(?:-b\\d+)?"); - private static final Pattern JAVA_8_DEV_VERSION_SCHEME = Pattern.compile("1\\.8\\.0b\\d+_u(\\d+)"); + private static final Pattern JAVA_8_RELEASE_VERSION_SCHEME = + Pattern.compile("1\\.8\\.0_(\\d+)(?:-ea)?(?:-b\\d+)?"); + private static final Pattern JAVA_8_DEV_VERSION_SCHEME = + Pattern.compile("1\\.8\\.0b\\d+_u(\\d+)"); public static final String JAVA_VERSION = System.getProperty("java.specification.version"); public static final String JVM_VERSION = System.getProperty("java.runtime.version"); public static final String JVM_VENDOR = System.getProperty("java.vm.vendor"); @@ -23,8 +25,7 @@ public abstract class Platform { public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_VERSION = System.getProperty("os.version"); - private Platform() { - } + private Platform() {} public static boolean isAndroid() { return System.getProperty("java.vendor", "").toLowerCase(Locale.US).contains("android"); @@ -35,32 +36,34 @@ public static boolean isAndroidMockMakerRequired() { } public static String describe() { - String description = String.format("Java : %s\n" + - "JVM vendor name : %s\n" + - "JVM vendor version : %s\n" + - "JVM name : %s\n" + - "JVM version : %s\n" + - "JVM info : %s\n" + - "OS name : %s\n" + - "OS version : %s\n", - JAVA_VERSION, - JVM_VENDOR, - JVM_VENDOR_VERSION, - JVM_NAME, - JVM_VERSION, - JVM_INFO, - OS_NAME, - OS_VERSION); + String description = + String.format( + "Java : %s\n" + + "JVM vendor name : %s\n" + + "JVM vendor version : %s\n" + + "JVM name : %s\n" + + "JVM version : %s\n" + + "JVM info : %s\n" + + "OS name : %s\n" + + "OS version : %s\n", + JAVA_VERSION, + JVM_VENDOR, + JVM_VENDOR_VERSION, + JVM_NAME, + JVM_VERSION, + JVM_INFO, + OS_NAME, + OS_VERSION); if (isAndroid()) { - description = join( - "IMPORTANT INFORMATION FOR ANDROID USERS:", - "", - "The regular Byte Buddy mock makers cannot generate code on an Android VM!", - "To resolve this, please use the 'mockito-android' dependency for your application:", - "http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22", - "", - description - ); + description = + join( + "IMPORTANT INFORMATION FOR ANDROID USERS:", + "", + "The regular Byte Buddy mock makers cannot generate code on an Android VM!", + "To resolve this, please use the 'mockito-android' dependency for your application:", + "http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22", + "", + description); } return description; } @@ -84,19 +87,19 @@ static boolean isJava8BelowUpdate45(String jvmVersion) { matcher = Pattern.compile("1\\.8\\.0-b\\d+").matcher(jvmVersion); return matcher.matches(); - } - public static String warnForVM(String vmName1, String warnMessage1, - String vmName2, String warnMessage2) { - return warnForVM(JVM_NAME, - vmName1, warnMessage1, - vmName2, warnMessage2); + public static String warnForVM( + String vmName1, String warnMessage1, String vmName2, String warnMessage2) { + return warnForVM(JVM_NAME, vmName1, warnMessage1, vmName2, warnMessage2); } - static String warnForVM(String current, - String vmName1, String warnMessage1, - String vmName2, String warnMessage2) { + static String warnForVM( + String current, + String vmName1, + String warnMessage1, + String vmName2, + String warnMessage2) { if (vmName1 != null && current.contains(vmName1)) { return warnMessage1; } diff --git a/src/main/java/org/mockito/internal/util/Primitives.java b/src/main/java/org/mockito/internal/util/Primitives.java index 80dd0af7d3..c094cc1d6b 100644 --- a/src/main/java/org/mockito/internal/util/Primitives.java +++ b/src/main/java/org/mockito/internal/util/Primitives.java @@ -10,9 +10,10 @@ @SuppressWarnings("unchecked") public class Primitives { - private static final Map, Class> PRIMITIVE_TYPES = new HashMap, Class>(); - private static final Map, Object> PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES = new HashMap, Object>(); - + private static final Map, Class> PRIMITIVE_TYPES = + new HashMap, Class>(); + private static final Map, Object> PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES = + new HashMap, Object>(); /** * Returns the primitive type of the given class. @@ -43,8 +44,9 @@ public static boolean isPrimitiveOrWrapper(Class type) { } public static boolean isAssignableFromWrapper(Class valueClass, Class referenceType) { - if(isPrimitiveOrWrapper(valueClass) && isPrimitiveOrWrapper(referenceType)) { - return Primitives.primitiveTypeOf(valueClass).isAssignableFrom(Primitives.primitiveTypeOf(referenceType)); + if (isPrimitiveOrWrapper(valueClass) && isPrimitiveOrWrapper(referenceType)) { + return Primitives.primitiveTypeOf(valueClass) + .isAssignableFrom(Primitives.primitiveTypeOf(referenceType)); } return false; } @@ -60,7 +62,6 @@ public static T defaultValue(Class primitiveOrWrapperType) { return (T) PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.get(primitiveOrWrapperType); } - static { PRIMITIVE_TYPES.put(Boolean.class, Boolean.TYPE); PRIMITIVE_TYPES.put(Character.class, Character.TYPE); diff --git a/src/main/java/org/mockito/internal/util/StringUtil.java b/src/main/java/org/mockito/internal/util/StringUtil.java index 3070fe622f..b58a36fce5 100644 --- a/src/main/java/org/mockito/internal/util/StringUtil.java +++ b/src/main/java/org/mockito/internal/util/StringUtil.java @@ -28,7 +28,7 @@ public static String removeFirstLine(String text) { * Joins Strings with line break character. It adds line break in front, too. * This makes it something like 'format' no really 'join'. */ - public static String join(Object ... linesToBreak) { + public static String join(Object... linesToBreak) { return join("\n", asList(linesToBreak)); } @@ -57,7 +57,7 @@ public static String join(String start, String linePrefix, Collection lines) for (Object line : lines) { out.append(linePrefix).append(line).append("\n"); } - return out.substring(0, out.length() - 1); //lose last EOL + return out.substring(0, out.length() - 1); // lose last EOL } public static String decamelizeMatcher(String className) { diff --git a/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java b/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java index d8b581c070..263205941c 100644 --- a/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java +++ b/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java @@ -55,13 +55,20 @@ public static HashCodeAndEqualsMockWrapper of(Object mock) { return new HashCodeAndEqualsMockWrapper(mock); } - @Override public String toString() { - return "HashCodeAndEqualsMockWrapper{" + - "mockInstance=" + (MockUtil.isMock(mockInstance) ? MockUtil.getMockName(mockInstance) : typeInstanceString()) + - '}'; + @Override + public String toString() { + return "HashCodeAndEqualsMockWrapper{" + + "mockInstance=" + + (MockUtil.isMock(mockInstance) + ? MockUtil.getMockName(mockInstance) + : typeInstanceString()) + + '}'; } private String typeInstanceString() { - return mockInstance.getClass().getSimpleName() + "(" + System.identityHashCode(mockInstance) + ")"; + return mockInstance.getClass().getSimpleName() + + "(" + + System.identityHashCode(mockInstance) + + ")"; } } diff --git a/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java b/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java index e35e212ea8..ab0989bb26 100644 --- a/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java +++ b/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java @@ -31,11 +31,13 @@ */ public class HashCodeAndEqualsSafeSet implements Set { - private final HashSet backingHashSet = new HashSet(); + private final HashSet backingHashSet = + new HashSet(); public Iterator iterator() { return new Iterator() { - private final Iterator iterator = backingHashSet.iterator(); + private final Iterator iterator = + backingHashSet.iterator(); public boolean hasNext() { return iterator.hasNext(); @@ -75,11 +77,13 @@ public void clear() { backingHashSet.clear(); } - @Override public Object clone() throws CloneNotSupportedException { + @Override + public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { if (!(o instanceof HashCodeAndEqualsSafeSet)) { return false; } @@ -87,7 +91,8 @@ public void clear() { return backingHashSet.equals(that.backingHashSet); } - @Override public int hashCode() { + @Override + public int hashCode() { return backingHashSet.hashCode(); } @@ -108,7 +113,10 @@ private T[] unwrapTo(T[] array) { @SuppressWarnings("unchecked") public T[] toArray(T[] typedArray) { - T[] array = typedArray.length >= size() ? typedArray : (T[]) newInstance(typedArray.getClass().getComponentType(), size()); + T[] array = + typedArray.length >= size() + ? typedArray + : (T[]) newInstance(typedArray.getClass().getComponentType(), size()); return unwrapTo(array); } @@ -132,13 +140,14 @@ private HashSet asWrappedMocks(Collection mocks Checks.checkNotNull(mocks, "Passed collection should notify() be null"); HashSet hashSet = new HashSet(); for (Object mock : mocks) { - assert ! (mock instanceof HashCodeAndEqualsMockWrapper) : "WRONG"; + assert !(mock instanceof HashCodeAndEqualsMockWrapper) : "WRONG"; hashSet.add(HashCodeAndEqualsMockWrapper.of(mock)); } return hashSet; } - @Override public String toString() { + @Override + public String toString() { return backingHashSet.toString(); } diff --git a/src/main/java/org/mockito/internal/util/collections/IdentitySet.java b/src/main/java/org/mockito/internal/util/collections/IdentitySet.java index 76c6178f45..e0b2359867 100644 --- a/src/main/java/org/mockito/internal/util/collections/IdentitySet.java +++ b/src/main/java/org/mockito/internal/util/collections/IdentitySet.java @@ -12,7 +12,7 @@ public class IdentitySet { private final LinkedList list = new LinkedList(); public boolean contains(Object o) { - for(Object existing:list) { + for (Object existing : list) { if (existing == o) { return true; } diff --git a/src/main/java/org/mockito/internal/util/collections/Iterables.java b/src/main/java/org/mockito/internal/util/collections/Iterables.java index 933ce893d4..8befb656aa 100644 --- a/src/main/java/org/mockito/internal/util/collections/Iterables.java +++ b/src/main/java/org/mockito/internal/util/collections/Iterables.java @@ -19,7 +19,7 @@ public class Iterables { */ public static Iterable toIterable(Enumeration in) { List out = new LinkedList(); - while(in.hasMoreElements()) { + while (in.hasMoreElements()) { out.add(in.nextElement()); } return out; @@ -35,7 +35,8 @@ public static Iterable toIterable(Enumeration in) { public static T firstOf(Iterable iterable) { Iterator iterator = iterable.iterator(); if (!iterator.hasNext()) { - throw new IllegalArgumentException("Cannot provide 1st element from empty iterable: " + iterable); + throw new IllegalArgumentException( + "Cannot provide 1st element from empty iterable: " + iterable); } return iterator.next(); } diff --git a/src/main/java/org/mockito/internal/util/collections/ListUtil.java b/src/main/java/org/mockito/internal/util/collections/ListUtil.java index ecad009f48..8ed5b56b7f 100644 --- a/src/main/java/org/mockito/internal/util/collections/ListUtil.java +++ b/src/main/java/org/mockito/internal/util/collections/ListUtil.java @@ -25,9 +25,10 @@ public static LinkedList filter(Collection collection, Filter filte return filtered; } - public static LinkedList convert(Collection collection, Converter converter) { + public static LinkedList convert( + Collection collection, Converter converter) { LinkedList converted = new LinkedList(); - for (From f: collection) { + for (From f : collection) { converted.add(converter.convert(f)); } return converted; diff --git a/src/main/java/org/mockito/internal/util/collections/Sets.java b/src/main/java/org/mockito/internal/util/collections/Sets.java index 2a71e00ae8..f42f76ac36 100644 --- a/src/main/java/org/mockito/internal/util/collections/Sets.java +++ b/src/main/java/org/mockito/internal/util/collections/Sets.java @@ -18,9 +18,10 @@ public static Set newMockSafeHashSet(Object... mocks) { return HashCodeAndEqualsSafeSet.of(mocks); } - public static Set newSet(T ... elements) { + public static Set newSet(T... elements) { if (elements == null) { - throw new IllegalArgumentException("Expected an array of elements (or empty array) but received a null."); + throw new IllegalArgumentException( + "Expected an array of elements (or empty array) but received a null."); } return new LinkedHashSet(asList(elements)); } diff --git a/src/main/java/org/mockito/internal/util/concurrent/DetachedThreadLocal.java b/src/main/java/org/mockito/internal/util/concurrent/DetachedThreadLocal.java index 3768a03d61..efe0d0d59e 100644 --- a/src/main/java/org/mockito/internal/util/concurrent/DetachedThreadLocal.java +++ b/src/main/java/org/mockito/internal/util/concurrent/DetachedThreadLocal.java @@ -19,20 +19,22 @@ public DetachedThreadLocal(Cleaner cleaner) { switch (cleaner) { case THREAD: case MANUAL: - map = new WeakConcurrentMap(cleaner == Cleaner.THREAD) { - @Override - protected T defaultValue(Thread key) { - return DetachedThreadLocal.this.initialValue(key); - } - }; + map = + new WeakConcurrentMap(cleaner == Cleaner.THREAD) { + @Override + protected T defaultValue(Thread key) { + return DetachedThreadLocal.this.initialValue(key); + } + }; break; case INLINE: - map = new WeakConcurrentMap.WithInlinedExpunction() { - @Override - protected T defaultValue(Thread key) { - return DetachedThreadLocal.this.initialValue(key); - } - }; + map = + new WeakConcurrentMap.WithInlinedExpunction() { + @Override + protected T defaultValue(Thread key) { + return DetachedThreadLocal.this.initialValue(key); + } + }; break; default: throw new AssertionError(); @@ -133,6 +135,8 @@ public void run() { * ({@link Cleaner#MANUAL}). */ public enum Cleaner { - THREAD, INLINE, MANUAL + THREAD, + INLINE, + MANUAL } } diff --git a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java index 487d223a8f..6abe6d8f81 100644 --- a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java +++ b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java @@ -22,7 +22,8 @@ * This class does not implement the {@link java.util.Map} interface because this implementation is incompatible * with the map contract. While iterating over a map's entries, any key that has not passed iteration is referenced non-weakly. */ -public class WeakConcurrentMap extends ReferenceQueue implements Runnable, Iterable> { +public class WeakConcurrentMap extends ReferenceQueue + implements Runnable, Iterable> { private static final AtomicLong ID = new AtomicLong(); diff --git a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java index 0f1cde638d..e9bc1cea2d 100644 --- a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java +++ b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java @@ -84,7 +84,9 @@ public void run() { * ({@link Cleaner#MANUAL}). */ public enum Cleaner { - THREAD, INLINE, MANUAL + THREAD, + INLINE, + MANUAL } /** diff --git a/src/main/java/org/mockito/internal/util/io/IOUtil.java b/src/main/java/org/mockito/internal/util/io/IOUtil.java index 2752a2c834..33a950f3b0 100644 --- a/src/main/java/org/mockito/internal/util/io/IOUtil.java +++ b/src/main/java/org/mockito/internal/util/io/IOUtil.java @@ -36,7 +36,7 @@ public static Collection readLines(InputStream is) { BufferedReader r = new BufferedReader(new InputStreamReader(is)); String line; try { - while((line = r.readLine()) != null) { + while ((line = r.readLine()) != null) { out.add(line); } } catch (IOException e) { @@ -54,7 +54,7 @@ public static void closeQuietly(Closeable closeable) { try { close(closeable); } catch (MockitoException ignored) { - //ignore, for backwards compatibility + // ignore, for backwards compatibility } } diff --git a/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java b/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java index f02acbebfb..33725e0137 100644 --- a/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java +++ b/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java @@ -18,7 +18,7 @@ public void safelyDisableAccess(AccessibleObject accessibleObject) { try { accessibleObject.setAccessible(wasAccessible); } catch (Throwable t) { - //ignore + // ignore } } diff --git a/src/main/java/org/mockito/internal/util/reflection/BeanPropertySetter.java b/src/main/java/org/mockito/internal/util/reflection/BeanPropertySetter.java index 9ef9481b80..f91a35c202 100644 --- a/src/main/java/org/mockito/internal/util/reflection/BeanPropertySetter.java +++ b/src/main/java/org/mockito/internal/util/reflection/BeanPropertySetter.java @@ -26,7 +26,8 @@ public class BeanPropertySetter { * @param propertyField The field that should be accessed with the setter * @param reportNoSetterFound Allow the set method to raise an Exception if the setter cannot be found */ - public BeanPropertySetter(final Object target, final Field propertyField, boolean reportNoSetterFound) { + public BeanPropertySetter( + final Object target, final Field propertyField, boolean reportNoSetterFound) { this.field = propertyField; this.target = target; this.reportNoSetterFound = reportNoSetterFound; @@ -59,13 +60,31 @@ public boolean set(final Object value) { writeMethod.invoke(target, value); return true; } catch (InvocationTargetException e) { - throw new RuntimeException("Setter '" + writeMethod + "' of '" + target + "' with value '" + value + "' threw exception : '" + e.getTargetException() + "'", e); + throw new RuntimeException( + "Setter '" + + writeMethod + + "' of '" + + target + + "' with value '" + + value + + "' threw exception : '" + + e.getTargetException() + + "'", + e); } catch (IllegalAccessException e) { - throw new RuntimeException("Access not authorized on field '" + field + "' of object '" + target + "' with value: '" + value + "'", e); + throw new RuntimeException( + "Access not authorized on field '" + + field + + "' of object '" + + target + + "' with value: '" + + value + + "'", + e); } catch (NoSuchMethodException e) { reportNoSetterFound(); } finally { - if(writeMethod != null) { + if (writeMethod != null) { changer.safelyDisableAccess(writeMethod); } } @@ -90,9 +109,13 @@ private String setterName(String fieldName) { } private void reportNoSetterFound() { - if(reportNoSetterFound) { - throw new RuntimeException("Problems setting value on object: [" + target + "] for property : [" + field.getName() + "], setter not found"); + if (reportNoSetterFound) { + throw new RuntimeException( + "Problems setting value on object: [" + + target + + "] for property : [" + + field.getName() + + "], setter not found"); } } - } diff --git a/src/main/java/org/mockito/internal/util/reflection/FieldInitializationReport.java b/src/main/java/org/mockito/internal/util/reflection/FieldInitializationReport.java index 957832ee00..13d9c5d7ef 100644 --- a/src/main/java/org/mockito/internal/util/reflection/FieldInitializationReport.java +++ b/src/main/java/org/mockito/internal/util/reflection/FieldInitializationReport.java @@ -12,7 +12,10 @@ public class FieldInitializationReport { private final boolean wasInitialized; private final boolean wasInitializedUsingConstructorArgs; - public FieldInitializationReport(Object fieldInstance, boolean wasInitialized, boolean wasInitializedUsingConstructorArgs) { + public FieldInitializationReport( + Object fieldInstance, + boolean wasInitialized, + boolean wasInitializedUsingConstructorArgs) { this.fieldInstance = fieldInstance; this.wasInitialized = wasInitialized; this.wasInitializedUsingConstructorArgs = wasInitializedUsingConstructorArgs; diff --git a/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java b/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java index e247d18c13..a5c5d708b5 100644 --- a/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java +++ b/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java @@ -35,7 +35,6 @@ public class FieldInitializer { private final Field field; private final ConstructorInstantiator instantiator; - /** * Prepare initializer with the given field on the given instance. * @@ -61,18 +60,21 @@ public FieldInitializer(Object fieldOwner, Field field) { * @param field Field to be initialize. * @param argResolver Constructor parameters resolver */ - public FieldInitializer(Object fieldOwner, Field field, ConstructorArgumentResolver argResolver) { - this(fieldOwner, field, new ParameterizedConstructorInstantiator(fieldOwner, field, argResolver)); + public FieldInitializer( + Object fieldOwner, Field field, ConstructorArgumentResolver argResolver) { + this( + fieldOwner, + field, + new ParameterizedConstructorInstantiator(fieldOwner, field, argResolver)); } private FieldInitializer(Object fieldOwner, Field field, ConstructorInstantiator instantiator) { - if(new FieldReader(fieldOwner, field).isNull()) { + if (new FieldReader(fieldOwner, field).isNull()) { checkNotLocal(field); checkNotInner(field); checkNotInterface(field); checkNotEnum(field); checkNotAbstract(field); - } this.fieldOwner = fieldOwner; this.field = field; @@ -90,48 +92,58 @@ public FieldInitializationReport initialize() { try { return acquireFieldInstance(); - } catch(IllegalAccessException e) { - throw new MockitoException("Problems initializing field '" + field.getName() + "' of type '" + field.getType().getSimpleName() + "'", e); + } catch (IllegalAccessException e) { + throw new MockitoException( + "Problems initializing field '" + + field.getName() + + "' of type '" + + field.getType().getSimpleName() + + "'", + e); } finally { changer.safelyDisableAccess(field); } } private void checkNotLocal(Field field) { - if(field.getType().isLocalClass()) { - throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is a local class."); + if (field.getType().isLocalClass()) { + throw new MockitoException( + "the type '" + field.getType().getSimpleName() + "' is a local class."); } } private void checkNotInner(Field field) { Class type = field.getType(); - if(type.isMemberClass() && !isStatic(type.getModifiers())) { - throw new MockitoException("the type '" + type.getSimpleName() + "' is an inner non static class."); + if (type.isMemberClass() && !isStatic(type.getModifiers())) { + throw new MockitoException( + "the type '" + type.getSimpleName() + "' is an inner non static class."); } } private void checkNotInterface(Field field) { - if(field.getType().isInterface()) { - throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an interface."); + if (field.getType().isInterface()) { + throw new MockitoException( + "the type '" + field.getType().getSimpleName() + "' is an interface."); } } private void checkNotAbstract(Field field) { - if(Modifier.isAbstract(field.getType().getModifiers())) { - throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an abstract class."); + if (Modifier.isAbstract(field.getType().getModifiers())) { + throw new MockitoException( + "the type '" + field.getType().getSimpleName() + "' is an abstract class."); } } private void checkNotEnum(Field field) { - if(field.getType().isEnum()) { - throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an enum."); + if (field.getType().isEnum()) { + throw new MockitoException( + "the type '" + field.getType().getSimpleName() + "' is an enum."); } } - private FieldInitializationReport acquireFieldInstance() throws IllegalAccessException { Object fieldInstance = field.get(fieldOwner); - if(fieldInstance != null) { + if (fieldInstance != null) { return new FieldInitializationReport(fieldInstance, false, false); } @@ -194,19 +206,32 @@ public FieldInitializationReport instantiate() { final Object[] noArg = new Object[0]; Object newFieldInstance = constructor.newInstance(noArg); - setField(testClass, field,newFieldInstance); + setField(testClass, field, newFieldInstance); return new FieldInitializationReport(field.get(testClass), true, false); } catch (NoSuchMethodException e) { - throw new MockitoException("the type '" + field.getType().getSimpleName() + "' has no default constructor", e); + throw new MockitoException( + "the type '" + + field.getType().getSimpleName() + + "' has no default constructor", + e); } catch (InvocationTargetException e) { - throw new MockitoException("the default constructor of type '" + field.getType().getSimpleName() + "' has raised an exception (see the stack trace for cause): " + e.getTargetException().toString(), e); + throw new MockitoException( + "the default constructor of type '" + + field.getType().getSimpleName() + + "' has raised an exception (see the stack trace for cause): " + + e.getTargetException().toString(), + e); } catch (InstantiationException e) { - throw new MockitoException("InstantiationException (see the stack trace for cause): " + e.toString(), e); + throw new MockitoException( + "InstantiationException (see the stack trace for cause): " + e.toString(), + e); } catch (IllegalAccessException e) { - throw new MockitoException("IllegalAccessException (see the stack trace for cause): " + e.toString(), e); + throw new MockitoException( + "IllegalAccessException (see the stack trace for cause): " + e.toString(), + e); } finally { - if(constructor != null) { + if (constructor != null) { changer.safelyDisableAccess(constructor); } } @@ -227,33 +252,37 @@ static class ParameterizedConstructorInstantiator implements ConstructorInstanti private final Object testClass; private final Field field; private final ConstructorArgumentResolver argResolver; - private final Comparator> byParameterNumber = new Comparator>() { - public int compare(Constructor constructorA, Constructor constructorB) { - int argLengths = constructorB.getParameterTypes().length - constructorA.getParameterTypes().length; - if (argLengths == 0) { - int constructorAMockableParamsSize = countMockableParams(constructorA); - int constructorBMockableParamsSize = countMockableParams(constructorB); - return constructorBMockableParamsSize - constructorAMockableParamsSize; - } - return argLengths; - } + private final Comparator> byParameterNumber = + new Comparator>() { + public int compare(Constructor constructorA, Constructor constructorB) { + int argLengths = + constructorB.getParameterTypes().length + - constructorA.getParameterTypes().length; + if (argLengths == 0) { + int constructorAMockableParamsSize = countMockableParams(constructorA); + int constructorBMockableParamsSize = countMockableParams(constructorB); + return constructorBMockableParamsSize - constructorAMockableParamsSize; + } + return argLengths; + } - private int countMockableParams(Constructor constructor) { - int constructorMockableParamsSize = 0; - for (Class aClass : constructor.getParameterTypes()) { - if(MockUtil.typeMockabilityOf(aClass).mockable()){ - constructorMockableParamsSize++; + private int countMockableParams(Constructor constructor) { + int constructorMockableParamsSize = 0; + for (Class aClass : constructor.getParameterTypes()) { + if (MockUtil.typeMockabilityOf(aClass).mockable()) { + constructorMockableParamsSize++; + } + } + return constructorMockableParamsSize; } - } - return constructorMockableParamsSize; - } - }; + }; /** * Internal, checks are done by FieldInitializer. * Fields are assumed to be accessible. */ - ParameterizedConstructorInstantiator(Object testClass, Field field, ConstructorArgumentResolver argumentResolver) { + ParameterizedConstructorInstantiator( + Object testClass, Field field, ConstructorArgumentResolver argumentResolver) { this.testClass = testClass; this.field = field; this.argResolver = argumentResolver; @@ -266,34 +295,55 @@ public FieldInitializationReport instantiate() { constructor = biggestConstructor(field.getType()); changer.enableAccess(constructor); - final Object[] args = argResolver.resolveTypeInstances(constructor.getParameterTypes()); + final Object[] args = + argResolver.resolveTypeInstances(constructor.getParameterTypes()); Object newFieldInstance = constructor.newInstance(args); - setField(testClass, field,newFieldInstance); + setField(testClass, field, newFieldInstance); return new FieldInitializationReport(field.get(testClass), false, true); } catch (IllegalArgumentException e) { - throw new MockitoException("internal error : argResolver provided incorrect types for constructor " + constructor + " of type " + field.getType().getSimpleName(), e); + throw new MockitoException( + "internal error : argResolver provided incorrect types for constructor " + + constructor + + " of type " + + field.getType().getSimpleName(), + e); } catch (InvocationTargetException e) { - throw new MockitoException("the constructor of type '" + field.getType().getSimpleName() + "' has raised an exception (see the stack trace for cause): " + e.getTargetException().toString(), e); + throw new MockitoException( + "the constructor of type '" + + field.getType().getSimpleName() + + "' has raised an exception (see the stack trace for cause): " + + e.getTargetException().toString(), + e); } catch (InstantiationException e) { - throw new MockitoException("InstantiationException (see the stack trace for cause): " + e.toString(), e); + throw new MockitoException( + "InstantiationException (see the stack trace for cause): " + e.toString(), + e); } catch (IllegalAccessException e) { - throw new MockitoException("IllegalAccessException (see the stack trace for cause): " + e.toString(), e); + throw new MockitoException( + "IllegalAccessException (see the stack trace for cause): " + e.toString(), + e); } finally { - if(constructor != null) { + if (constructor != null) { changer.safelyDisableAccess(constructor); } } } private void checkParameterized(Constructor constructor, Field field) { - if(constructor.getParameterTypes().length == 0) { - throw new MockitoException("the field " + field.getName() + " of type " + field.getType() + " has no parameterized constructor"); + if (constructor.getParameterTypes().length == 0) { + throw new MockitoException( + "the field " + + field.getName() + + " of type " + + field.getType() + + " has no parameterized constructor"); } } private Constructor biggestConstructor(Class clazz) { - final List> constructors = Arrays.asList(clazz.getDeclaredConstructors()); + final List> constructors = + Arrays.asList(clazz.getDeclaredConstructors()); Collections.sort(constructors, byParameterNumber); Constructor constructor = constructors.get(0); diff --git a/src/main/java/org/mockito/internal/util/reflection/FieldReader.java b/src/main/java/org/mockito/internal/util/reflection/FieldReader.java index 5d0bb59ca6..707eee6515 100644 --- a/src/main/java/org/mockito/internal/util/reflection/FieldReader.java +++ b/src/main/java/org/mockito/internal/util/reflection/FieldReader.java @@ -21,14 +21,15 @@ public FieldReader(Object target, Field field) { } public boolean isNull() { - return read() == null; + return read() == null; } public Object read() { try { return field.get(target); } catch (Exception e) { - throw new MockitoException("Cannot read state from field: " + field + ", on instance: " + target); + throw new MockitoException( + "Cannot read state from field: " + field + ", on instance: " + target); } } } diff --git a/src/main/java/org/mockito/internal/util/reflection/FieldSetter.java b/src/main/java/org/mockito/internal/util/reflection/FieldSetter.java index 69b5b161a6..46f906d9bf 100644 --- a/src/main/java/org/mockito/internal/util/reflection/FieldSetter.java +++ b/src/main/java/org/mockito/internal/util/reflection/FieldSetter.java @@ -8,18 +8,35 @@ public class FieldSetter { - private FieldSetter(){} + private FieldSetter() {} - public static void setField(Object target, Field field,Object value) { + public static void setField(Object target, Field field, Object value) { AccessibilityChanger changer = new AccessibilityChanger(); changer.enableAccess(field); try { field.set(target, value); } catch (IllegalAccessException e) { - throw new RuntimeException("Access not authorized on field '" + field + "' of object '" + target + "' with value: '" + value + "'", e); + throw new RuntimeException( + "Access not authorized on field '" + + field + + "' of object '" + + target + + "' with value: '" + + value + + "'", + e); } catch (IllegalArgumentException e) { - throw new RuntimeException("Wrong argument on field '" + field + "' of object '" + target + "' with value: '" + value + "', \n" + - "reason : " + e.getMessage(), e); + throw new RuntimeException( + "Wrong argument on field '" + + field + + "' of object '" + + target + + "' with value: '" + + value + + "', \n" + + "reason : " + + e.getMessage(), + e); } changer.safelyDisableAccess(field); } diff --git a/src/main/java/org/mockito/internal/util/reflection/Fields.java b/src/main/java/org/mockito/internal/util/reflection/Fields.java index 3d3fb9c3dc..9e88079307 100644 --- a/src/main/java/org/mockito/internal/util/reflection/Fields.java +++ b/src/main/java/org/mockito/internal/util/reflection/Fields.java @@ -28,7 +28,9 @@ public abstract class Fields { */ public static InstanceFields allDeclaredFieldsOf(Object instance) { List instanceFields = new ArrayList(); - for (Class clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { + for (Class clazz = instance.getClass(); + clazz != Object.class; + clazz = clazz.getSuperclass()) { instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields())); } return new InstanceFields(instance, instanceFields); @@ -62,13 +64,14 @@ private static List instanceFieldsIn(Object instance, Field[] fie * @return The filter. */ @SuppressWarnings({"unchecked", "vararg"}) - public static Filter annotatedBy(final Class... annotations) { + public static Filter annotatedBy( + final Class... annotations) { return new Filter() { public boolean isOut(InstanceField instanceField) { Checks.checkNotNull(annotations, "Provide at least one annotation class"); for (Class annotation : annotations) { - if(instanceField.isAnnotatedBy(annotation)) { + if (instanceField.isAnnotatedBy(annotation)) { return false; } } diff --git a/src/main/java/org/mockito/internal/util/reflection/GenericMaster.java b/src/main/java/org/mockito/internal/util/reflection/GenericMaster.java index a477ba43dd..be3db7f979 100644 --- a/src/main/java/org/mockito/internal/util/reflection/GenericMaster.java +++ b/src/main/java/org/mockito/internal/util/reflection/GenericMaster.java @@ -22,12 +22,11 @@ public Class getGenericType(Field field) { if (actual instanceof Class) { return (Class) actual; } else if (actual instanceof ParameterizedType) { - //in case of nested generics we don't go deep + // in case of nested generics we don't go deep return (Class) ((ParameterizedType) actual).getRawType(); } } return Object.class; } - } diff --git a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java index 4499a4d7d4..17265c883a 100644 --- a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java +++ b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java @@ -4,7 +4,6 @@ */ package org.mockito.internal.util.reflection; - import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; @@ -26,7 +25,6 @@ import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.util.Checks; - /** * This class can retrieve generic meta-data that the compiler stores on classes * and accessible members. @@ -75,7 +73,8 @@ public abstract class GenericMetadataSupport { /** * Represents actual type variables resolved for current class. */ - protected Map, Type> contextualActualTypeParameters = new HashMap, Type>(); + protected Map, Type> contextualActualTypeParameters = + new HashMap, Type>(); /** * Registers the type variables for the given type and all of its superclasses and superinterfaces. @@ -126,7 +125,8 @@ protected void registerTypeVariablesOn(Type classType) { return; } ParameterizedType parameterizedType = (ParameterizedType) classType; - TypeVariable[] typeParameters = ((Class) parameterizedType.getRawType()).getTypeParameters(); + TypeVariable[] typeParameters = + ((Class) parameterizedType.getRawType()).getTypeParameters(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < actualTypeArguments.length; i++) { TypeVariable typeParameter = typeParameters[i]; @@ -142,19 +142,24 @@ protected void registerTypeVariablesOn(Type classType) { */ registerTypeVariableIfNotPresent((TypeVariable) actualTypeArgument); - // Prevent registration of a cycle of TypeVariables. This can happen when we are processing - // type parameters in a Method, while we already processed the type parameters of a class. + // Prevent registration of a cycle of TypeVariables. This can happen when we are + // processing + // type parameters in a Method, while we already processed the type parameters of a + // class. if (contextualActualTypeParameters.containsKey(typeParameter)) { continue; } } if (actualTypeArgument instanceof WildcardType) { - contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument)); + contextualActualTypeParameters.put( + typeParameter, boundsOf((WildcardType) actualTypeArgument)); } else if (typeParameter != actualTypeArgument) { contextualActualTypeParameters.put(typeParameter, actualTypeArgument); } - // logger.log("For '" + parameterizedType + "' found type variable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualTypeArgument + "(" + System.identityHashCode(typeParameter) + ")" + "' }"); + // logger.log("For '" + parameterizedType + "' found type variable : { '" + + // typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + + // actualTypeArgument + "(" + System.identityHashCode(typeParameter) + ")" + "' }"); } } @@ -167,7 +172,9 @@ protected void registerTypeParametersOn(TypeVariable[] typeParameters) { private void registerTypeVariableIfNotPresent(TypeVariable typeVariable) { if (!contextualActualTypeParameters.containsKey(typeVariable)) { contextualActualTypeParameters.put(typeVariable, boundsOf(typeVariable)); - // logger.log("For '" + typeVariable.getGenericDeclaration() + "' found type variable : { '" + typeVariable + "(" + System.identityHashCode(typeVariable) + ")" + "' : '" + boundsOf(typeVariable) + "' }"); + // logger.log("For '" + typeVariable.getGenericDeclaration() + "' found type variable : + // { '" + typeVariable + "(" + System.identityHashCode(typeVariable) + ")" + "' : '" + + // boundsOf(typeVariable) + "' }"); } } @@ -238,14 +245,17 @@ public boolean hasRawExtraInterfaces() { */ public Map, Type> actualTypeArguments() { TypeVariable[] typeParameters = rawType().getTypeParameters(); - LinkedHashMap, Type> actualTypeArguments = new LinkedHashMap, Type>(); + LinkedHashMap, Type> actualTypeArguments = + new LinkedHashMap, Type>(); for (TypeVariable typeParameter : typeParameters) { Type actualType = getActualTypeArgumentFor(typeParameter); actualTypeArguments.put(typeParameter, actualType); - // logger.log("For '" + rawType().getCanonicalName() + "' returning explicit TypeVariable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualType +"' }"); + // logger.log("For '" + rawType().getCanonicalName() + "' returning explicit + // TypeVariable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + + // ")" + "' : '" + actualType +"' }"); } return actualTypeArguments; @@ -269,7 +279,9 @@ protected Type getActualTypeArgumentFor(TypeVariable typeParameter) { */ public GenericMetadataSupport resolveGenericReturnType(Method method) { Type genericReturnType = method.getGenericReturnType(); - // logger.log("Method '" + method.toGenericString() + "' has return type : " + genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType); + // logger.log("Method '" + method.toGenericString() + "' has return type : " + + // genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + + // genericReturnType); int arity = 0; while (genericReturnType instanceof GenericArrayType) { @@ -277,7 +289,8 @@ public GenericMetadataSupport resolveGenericReturnType(Method method) { genericReturnType = ((GenericArrayType) genericReturnType).getGenericComponentType(); } - GenericMetadataSupport genericMetadataSupport = resolveGenericType(genericReturnType, method); + GenericMetadataSupport genericMetadataSupport = + resolveGenericType(genericReturnType, method); if (arity == 0) { return genericMetadataSupport; } else { @@ -291,13 +304,21 @@ private GenericMetadataSupport resolveGenericType(Type type, Method method) { return new NotGenericReturnTypeSupport(this, type); } if (type instanceof ParameterizedType) { - return new ParameterizedReturnType(this, method.getTypeParameters(), (ParameterizedType) type); + return new ParameterizedReturnType( + this, method.getTypeParameters(), (ParameterizedType) type); } if (type instanceof TypeVariable) { - return new TypeVariableReturnType(this, method.getTypeParameters(), (TypeVariable) type); + return new TypeVariableReturnType( + this, method.getTypeParameters(), (TypeVariable) type); } - throw new MockitoException("Ouch, it shouldn't happen, type '" + type.getClass().getCanonicalName() + "' on method : '" + method.toGenericString() + "' is not supported : " + type); + throw new MockitoException( + "Ouch, it shouldn't happen, type '" + + type.getClass().getCanonicalName() + + "' on method : '" + + method.toGenericString() + + "' is not supported : " + + type); } /** @@ -321,12 +342,16 @@ public static GenericMetadataSupport inferFrom(Type type) { return new FromParameterizedTypeGenericMetadataSupport((ParameterizedType) type); } - throw new MockitoException("Type meta-data for this Type (" + type.getClass().getCanonicalName() + ") is not supported : " + type); + throw new MockitoException( + "Type meta-data for this Type (" + + type.getClass().getCanonicalName() + + ") is not supported : " + + type); } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //// Below are specializations of GenericMetadataSupport that could handle retrieval of possible Types + //// Below are specializations of GenericMetadataSupport that could handle retrieval of possible + // Types //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @@ -362,7 +387,8 @@ public Class rawType() { * That's what meant the "standalone" word at the beginning of the Javadoc. * Instead use {@link ParameterizedReturnType}. */ - private static class FromParameterizedTypeGenericMetadataSupport extends GenericMetadataSupport { + private static class FromParameterizedTypeGenericMetadataSupport + extends GenericMetadataSupport { private final ParameterizedType parameterizedType; public FromParameterizedTypeGenericMetadataSupport(ParameterizedType parameterizedType) { @@ -387,7 +413,10 @@ private static class ParameterizedReturnType extends GenericMetadataSupport { private final ParameterizedType parameterizedType; private final TypeVariable[] typeParameters; - public ParameterizedReturnType(GenericMetadataSupport source, TypeVariable[] typeParameters, ParameterizedType parameterizedType) { + public ParameterizedReturnType( + GenericMetadataSupport source, + TypeVariable[] typeParameters, + ParameterizedType parameterizedType) { this.parameterizedType = parameterizedType; this.typeParameters = typeParameters; this.contextualActualTypeParameters = source.contextualActualTypeParameters; @@ -408,7 +437,6 @@ private void readTypeVariables() { public Class rawType() { return (Class) parameterizedType.getRawType(); } - } /** @@ -420,7 +448,10 @@ private static class TypeVariableReturnType extends GenericMetadataSupport { private Class rawType; private List extraInterfaces; - public TypeVariableReturnType(GenericMetadataSupport source, TypeVariable[] typeParameters, TypeVariable typeVariable) { + public TypeVariableReturnType( + GenericMetadataSupport source, + TypeVariable[] typeParameters, + TypeVariable typeVariable) { this.typeParameters = typeParameters; this.typeVariable = typeVariable; this.contextualActualTypeParameters = source.contextualActualTypeParameters; @@ -437,7 +468,7 @@ private void readTypeVariables() { for (Type type : typeVariable.getBounds()) { registerTypeVariablesOn(type); } - registerTypeParametersOn(new TypeVariable[]{typeVariable}); + registerTypeParametersOn(new TypeVariable[] {typeVariable}); registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable)); } @@ -464,7 +495,8 @@ public List extraInterfaces() { if (type instanceof Class) { return extraInterfaces = Collections.emptyList(); } - throw new MockitoException("Cannot extract extra-interfaces from '" + typeVariable + "' : '" + type + "'"); + throw new MockitoException( + "Cannot extract extra-interfaces from '" + typeVariable + "' : '" + type + "'"); } /** @@ -476,7 +508,8 @@ public Class[] rawExtraInterfaces() { List> rawExtraInterfaces = new ArrayList>(); for (Type extraInterface : extraInterfaces) { Class rawInterface = extractRawTypeOf(extraInterface); - // avoid interface collision with actual raw type (with typevariables, resolution ca be quite aggressive) + // avoid interface collision with actual raw type (with typevariables, resolution ca + // be quite aggressive) if (!rawType().equals(rawInterface)) { rawExtraInterfaces.add(rawInterface); } @@ -493,9 +526,11 @@ on the class definition, such as such as List. return extractActualBoundedTypeOf(contextualActualTypeParameters.get(type)); } if (type instanceof BoundedType) { - Type actualFirstBound = extractActualBoundedTypeOf(((BoundedType) type).firstBound()); + Type actualFirstBound = + extractActualBoundedTypeOf(((BoundedType) type).firstBound()); if (!(actualFirstBound instanceof BoundedType)) { - return type; // avoid going one step further, ie avoid : O(TypeVar) -> K(TypeVar) -> Some ParamType + return type; // avoid going one step further, ie avoid : O(TypeVar) -> + // K(TypeVar) -> Some ParamType } return actualFirstBound; } @@ -522,7 +557,14 @@ public Class rawType() { stringBuilder.append("["); } try { - return Class.forName(stringBuilder.append("L").append(rawComponentType.getName()).append(";").toString(), false, rawComponentType.getClassLoader()); + return Class.forName( + stringBuilder + .append("L") + .append(rawComponentType.getName()) + .append(";") + .toString(), + false, + rawComponentType.getClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalStateException("This was not supposed to happen.", e); } @@ -548,7 +590,6 @@ public Class rawType() { } } - /** * Type representing bounds of a type * @@ -606,7 +647,12 @@ public Type firstBound() { */ public Type[] interfaceBounds() { Type[] interfaceBounds = new Type[typeVariable.getBounds().length - 1]; - System.arraycopy(typeVariable.getBounds(), 1, interfaceBounds, 0, typeVariable.getBounds().length - 1); + System.arraycopy( + typeVariable.getBounds(), + 1, + interfaceBounds, + 0, + typeVariable.getBounds().length - 1); return interfaceBounds; } @@ -616,7 +662,6 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; return typeVariable.equals(((TypeVarBoundedType) o).typeVariable); - } @Override @@ -626,7 +671,11 @@ public int hashCode() { @Override public String toString() { - return "{firstBound=" + firstBound() + ", interfaceBounds=" + Arrays.deepToString(interfaceBounds()) + '}'; + return "{firstBound=" + + firstBound() + + ", interfaceBounds=" + + Arrays.deepToString(interfaceBounds()) + + '}'; } public TypeVariable typeVariable() { @@ -645,7 +694,6 @@ public TypeVariable typeVariable() { public static class WildCardBoundedType implements BoundedType { private final WildcardType wildcard; - public WildCardBoundedType(WildcardType wildcard) { this.wildcard = wildcard; } @@ -673,7 +721,6 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; return wildcard.equals(((TypeVarBoundedType) o).typeVariable); - } @Override @@ -690,5 +737,4 @@ public WildcardType wildCard() { return wildcard; } } - } diff --git a/src/main/java/org/mockito/internal/util/reflection/GenericTypeExtractor.java b/src/main/java/org/mockito/internal/util/reflection/GenericTypeExtractor.java index 01fc1de50a..093159cc8e 100644 --- a/src/main/java/org/mockito/internal/util/reflection/GenericTypeExtractor.java +++ b/src/main/java/org/mockito/internal/util/reflection/GenericTypeExtractor.java @@ -34,20 +34,21 @@ public class GenericTypeExtractor { * it will be used for generic type extraction * @return generic interface if found, Object.class if not found. */ - public static Class genericTypeOf(Class rootClass, Class targetBaseClass, Class targetBaseInterface) { - //looking for candidates in the hierarchy of rootClass + public static Class genericTypeOf( + Class rootClass, Class targetBaseClass, Class targetBaseInterface) { + // looking for candidates in the hierarchy of rootClass Class match = rootClass; - while(match != Object.class) { - //check the super class first + while (match != Object.class) { + // check the super class first if (match.getSuperclass() == targetBaseClass) { return extractGeneric(match.getGenericSuperclass()); } - //check the interfaces (recursively) + // check the interfaces (recursively) Type genericInterface = findGenericInterface(match, targetBaseInterface); if (genericInterface != null) { return extractGeneric(genericInterface); } - //recurse the hierarchy + // recurse the hierarchy match = match.getSuperclass(); } return Object.class; diff --git a/src/main/java/org/mockito/internal/util/reflection/InstanceField.java b/src/main/java/org/mockito/internal/util/reflection/InstanceField.java index 6e4080db75..5585874f46 100644 --- a/src/main/java/org/mockito/internal/util/reflection/InstanceField.java +++ b/src/main/java/org/mockito/internal/util/reflection/InstanceField.java @@ -50,7 +50,7 @@ public Object read() { * @see FieldSetter */ public void set(Object value) { - setField(instance, field,value); + setField(instance, field, value); } /** diff --git a/src/main/java/org/mockito/internal/util/reflection/LenientCopyTool.java b/src/main/java/org/mockito/internal/util/reflection/LenientCopyTool.java index c6b9919206..ccdd923835 100644 --- a/src/main/java/org/mockito/internal/util/reflection/LenientCopyTool.java +++ b/src/main/java/org/mockito/internal/util/reflection/LenientCopyTool.java @@ -40,7 +40,7 @@ private void copyValues(T from, T mock, Class classFrom) { accessibilityChanger.enableAccess(field); fieldCopier.copyValue(from, mock, field); } catch (Throwable t) { - //Ignore - be lenient - if some field cannot be copied then let's be it + // Ignore - be lenient - if some field cannot be copied then let's be it } finally { accessibilityChanger.safelyDisableAccess(field); } diff --git a/src/main/java/org/mockito/internal/util/reflection/SuperTypesLastSorter.java b/src/main/java/org/mockito/internal/util/reflection/SuperTypesLastSorter.java index 86127f14a1..5c04af0410 100644 --- a/src/main/java/org/mockito/internal/util/reflection/SuperTypesLastSorter.java +++ b/src/main/java/org/mockito/internal/util/reflection/SuperTypesLastSorter.java @@ -17,8 +17,7 @@ */ public class SuperTypesLastSorter { - private SuperTypesLastSorter() { - } + private SuperTypesLastSorter() {} /** * Return a new collection with the fields sorted first by name, @@ -54,11 +53,11 @@ public static List sortSuperTypesLast(Collection unsorte return fields; } - - private static final Comparator compareFieldsByName = new Comparator() { - @Override - public int compare(Field o1, Field o2) { - return o1.getName().compareTo(o2.getName()); - } - }; + private static final Comparator compareFieldsByName = + new Comparator() { + @Override + public int compare(Field o1, Field o2) { + return o1.getName().compareTo(o2.getName()); + } + }; } diff --git a/src/main/java/org/mockito/internal/verification/AtLeast.java b/src/main/java/org/mockito/internal/verification/AtLeast.java index 4599e4e778..5f70649106 100644 --- a/src/main/java/org/mockito/internal/verification/AtLeast.java +++ b/src/main/java/org/mockito/internal/verification/AtLeast.java @@ -27,7 +27,7 @@ public AtLeast(int wantedNumberOfInvocations) { @Override public void verify(VerificationData data) { if (wantedCount == 1) { - checkMissingInvocation(data.getAllInvocations(), data.getTarget()); + checkMissingInvocation(data.getAllInvocations(), data.getTarget()); } checkAtLeastNumberOfInvocations(data.getAllInvocations(), data.getTarget(), wantedCount); } @@ -35,14 +35,15 @@ public void verify(VerificationData data) { @Override public void verifyInOrder(VerificationDataInOrder data) { if (wantedCount == 1) { - checkMissingInvocation(data.getAllInvocations(), data.getWanted(), data.getOrderingContext()); + checkMissingInvocation( + data.getAllInvocations(), data.getWanted(), data.getOrderingContext()); } - checkAtLeastNumberOfInvocations(data.getAllInvocations(), data.getWanted(), wantedCount, data.getOrderingContext()); + checkAtLeastNumberOfInvocations( + data.getAllInvocations(), data.getWanted(), wantedCount, data.getOrderingContext()); } @Override public String toString() { return "Wanted invocations count: at least " + wantedCount; } - } diff --git a/src/main/java/org/mockito/internal/verification/Calls.java b/src/main/java/org/mockito/internal/verification/Calls.java index 38e7316447..f52fd66971 100644 --- a/src/main/java/org/mockito/internal/verification/Calls.java +++ b/src/main/java/org/mockito/internal/verification/Calls.java @@ -22,15 +22,15 @@ public class Calls implements VerificationMode, VerificationInOrderMode { final int wantedCount; public Calls(int wantedNumberOfInvocations) { - if( wantedNumberOfInvocations <= 0 ) { - throw new MockitoException( "Negative and zero values are not allowed here" ); + if (wantedNumberOfInvocations <= 0) { + throw new MockitoException("Negative and zero values are not allowed here"); } this.wantedCount = wantedNumberOfInvocations; } @Override public void verify(VerificationData data) { - throw new MockitoException( "calls is only intended to work with InOrder" ); + throw new MockitoException("calls is only intended to work with InOrder"); } @Override @@ -38,13 +38,13 @@ public void verifyInOrder(VerificationDataInOrder data) { List allInvocations = data.getAllInvocations(); MatchableInvocation wanted = data.getWanted(); - checkMissingInvocation(allInvocations, wanted, data.getOrderingContext()); - checkNumberOfInvocationsNonGreedy(allInvocations, wanted, wantedCount, data.getOrderingContext()); + checkMissingInvocation(allInvocations, wanted, data.getOrderingContext()); + checkNumberOfInvocationsNonGreedy( + allInvocations, wanted, wantedCount, data.getOrderingContext()); } @Override public String toString() { return "Wanted invocations count (non-greedy): " + wantedCount; } - } diff --git a/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java b/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java index c69871e688..c614a3b983 100644 --- a/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java +++ b/src/main/java/org/mockito/internal/verification/DefaultRegisteredInvocations.java @@ -14,7 +14,6 @@ import org.mockito.internal.util.collections.ListUtil.Filter; import org.mockito.invocation.Invocation; - public class DefaultRegisteredInvocations implements RegisteredInvocations, Serializable { private static final long serialVersionUID = -2674402327380736290L; @@ -27,9 +26,10 @@ public void add(Invocation invocation) { } public void removeLast() { - //TODO: add specific test for synchronization of this block (it is tested by InvocationContainerImplTest at the moment) + // TODO: add specific test for synchronization of this block (it is tested by + // InvocationContainerImplTest at the moment) synchronized (invocations) { - if (! invocations.isEmpty()) { + if (!invocations.isEmpty()) { invocations.removeLast(); } } @@ -38,7 +38,7 @@ public void removeLast() { public List getAll() { List copiedList; synchronized (invocations) { - copiedList = new LinkedList(invocations) ; + copiedList = new LinkedList(invocations); } return ListUtil.filter(copiedList, new RemoveToString()); @@ -61,5 +61,4 @@ public boolean isOut(Invocation invocation) { return isToStringMethod(invocation.getMethod()); } } - } diff --git a/src/main/java/org/mockito/internal/verification/InOrderWrapper.java b/src/main/java/org/mockito/internal/verification/InOrderWrapper.java index 9cb82afc5b..5dd8b8c174 100644 --- a/src/main/java/org/mockito/internal/verification/InOrderWrapper.java +++ b/src/main/java/org/mockito/internal/verification/InOrderWrapper.java @@ -25,8 +25,10 @@ public InOrderWrapper(VerificationInOrderMode mode, InOrderImpl inOrder) { } public void verify(VerificationData data) { - List invocations = VerifiableInvocationsFinder.find(inOrder.getMocksToBeVerifiedInOrder()); - VerificationDataInOrderImpl dataInOrder = new VerificationDataInOrderImpl(inOrder, invocations, data.getTarget()); + List invocations = + VerifiableInvocationsFinder.find(inOrder.getMocksToBeVerifiedInOrder()); + VerificationDataInOrderImpl dataInOrder = + new VerificationDataInOrderImpl(inOrder, invocations, data.getTarget()); mode.verifyInOrder(dataInOrder); } } diff --git a/src/main/java/org/mockito/internal/verification/MockAwareVerificationMode.java b/src/main/java/org/mockito/internal/verification/MockAwareVerificationMode.java index 2a3ff2c571..df012d7488 100644 --- a/src/main/java/org/mockito/internal/verification/MockAwareVerificationMode.java +++ b/src/main/java/org/mockito/internal/verification/MockAwareVerificationMode.java @@ -17,7 +17,8 @@ public class MockAwareVerificationMode implements VerificationMode { private final VerificationMode mode; private final Set listeners; - public MockAwareVerificationMode(Object mock, VerificationMode mode, Set listeners) { + public MockAwareVerificationMode( + Object mock, VerificationMode mode, Set listeners) { this.mock = mock; this.mode = mode; this.listeners = listeners; @@ -36,7 +37,6 @@ public void verify(VerificationData data) { } } - private void notifyListeners(VerificationEvent event) { for (VerificationListener listener : listeners) { listener.onVerification(event); @@ -46,5 +46,4 @@ private void notifyListeners(VerificationEvent event) { public Object getMock() { return mock; } - } diff --git a/src/main/java/org/mockito/internal/verification/NoInteractions.java b/src/main/java/org/mockito/internal/verification/NoInteractions.java index 6c22793f9e..23fb07ba86 100644 --- a/src/main/java/org/mockito/internal/verification/NoInteractions.java +++ b/src/main/java/org/mockito/internal/verification/NoInteractions.java @@ -21,5 +21,4 @@ public void verify(VerificationData data) { throw noInteractionsWanted(invocations.get(0).getMock(), (List) invocations); } } - } diff --git a/src/main/java/org/mockito/internal/verification/Only.java b/src/main/java/org/mockito/internal/verification/Only.java index feb92dc7f8..ebb711ca3c 100644 --- a/src/main/java/org/mockito/internal/verification/Only.java +++ b/src/main/java/org/mockito/internal/verification/Only.java @@ -23,7 +23,7 @@ public class Only implements VerificationMode { public void verify(VerificationData data) { MatchableInvocation target = data.getTarget(); List invocations = data.getAllInvocations(); - List chunk = findInvocations(invocations,target); + List chunk = findInvocations(invocations, target); if (invocations.size() != 1 && !chunk.isEmpty()) { Invocation unverified = findFirstUnverified(invocations); throw noMoreInteractionsWanted(unverified, (List) invocations); diff --git a/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java b/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java index 51ea7ad9fc..8aa088efb9 100644 --- a/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java +++ b/src/main/java/org/mockito/internal/verification/RegisteredInvocations.java @@ -8,7 +8,6 @@ import org.mockito.invocation.Invocation; - public interface RegisteredInvocations { void add(Invocation invocation); @@ -20,5 +19,4 @@ public interface RegisteredInvocations { void clear(); boolean isEmpty(); - } diff --git a/src/main/java/org/mockito/internal/verification/Times.java b/src/main/java/org/mockito/internal/verification/Times.java index 0d4ec53c9e..122ba64f6b 100644 --- a/src/main/java/org/mockito/internal/verification/Times.java +++ b/src/main/java/org/mockito/internal/verification/Times.java @@ -34,10 +34,11 @@ public void verify(VerificationData data) { MatchableInvocation wanted = data.getTarget(); if (wantedCount > 0) { - checkMissingInvocation(data.getAllInvocations(), data.getTarget()); + checkMissingInvocation(data.getAllInvocations(), data.getTarget()); } checkNumberOfInvocations(invocations, wanted, wantedCount); } + @Override public void verifyInOrder(VerificationDataInOrder data) { List allInvocations = data.getAllInvocations(); diff --git a/src/main/java/org/mockito/internal/verification/VerificationEventImpl.java b/src/main/java/org/mockito/internal/verification/VerificationEventImpl.java index bf85055e73..97ff119f20 100644 --- a/src/main/java/org/mockito/internal/verification/VerificationEventImpl.java +++ b/src/main/java/org/mockito/internal/verification/VerificationEventImpl.java @@ -14,8 +14,8 @@ public class VerificationEventImpl implements VerificationEvent { private final VerificationData data; private final Throwable cause; - - public VerificationEventImpl(Object mock, VerificationMode mode, VerificationData data, Throwable cause) { + public VerificationEventImpl( + Object mock, VerificationMode mode, VerificationData data, Throwable cause) { this.mock = mock; this.mode = mode; this.data = data; diff --git a/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java b/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java index 6af6332399..f1d08cf143 100644 --- a/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java +++ b/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java @@ -17,7 +17,7 @@ public static VerificationMode atLeast(int minNumberOfInvocations) { } public static VerificationMode only() { - return new Only(); //TODO make exception message nicer + return new Only(); // TODO make exception message nicer } public static Times times(int wantedNumberOfInvocations) { @@ -25,7 +25,7 @@ public static Times times(int wantedNumberOfInvocations) { } public static Calls calls(int wantedNumberOfInvocations) { - return new Calls( wantedNumberOfInvocations ); + return new Calls(wantedNumberOfInvocations); } public static NoMoreInteractions noMoreInteractions() { diff --git a/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java b/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java index 24ec61a90d..febafbdd3c 100644 --- a/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java +++ b/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java @@ -32,7 +32,11 @@ public class VerificationOverTimeImpl implements VerificationMode { * the delegate is satisfied and the full duration has passed (as in * {@link org.mockito.verification.VerificationAfterDelay}). */ - public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, VerificationMode delegate, boolean returnOnSuccess) { + public VerificationOverTimeImpl( + long pollingPeriodMillis, + long durationMillis, + VerificationMode delegate, + boolean returnOnSuccess) { this(pollingPeriodMillis, delegate, returnOnSuccess, new Timer(durationMillis)); } @@ -47,7 +51,11 @@ public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, V * {@link org.mockito.verification.VerificationAfterDelay}). * @param timer Checker of whether the duration of the verification is still acceptable */ - public VerificationOverTimeImpl(long pollingPeriodMillis, VerificationMode delegate, boolean returnOnSuccess, Timer timer) { + public VerificationOverTimeImpl( + long pollingPeriodMillis, + VerificationMode delegate, + boolean returnOnSuccess, + Timer timer) { this.pollingPeriodMillis = pollingPeriodMillis; this.delegate = delegate; this.returnOnSuccess = returnOnSuccess; @@ -84,8 +92,7 @@ public void verify(VerificationData data) { } } catch (MockitoAssertionError e) { error = handleVerifyException(e); - } - catch (AssertionError e) { + } catch (AssertionError e) { error = handleVerifyException(e); } } @@ -105,11 +112,13 @@ private AssertionError handleVerifyException(AssertionError e) { } protected boolean canRecoverFromFailure(VerificationMode verificationMode) { - return !(verificationMode instanceof AtMost || verificationMode instanceof NoMoreInteractions); + return !(verificationMode instanceof AtMost + || verificationMode instanceof NoMoreInteractions); } public VerificationOverTimeImpl copyWithVerificationMode(VerificationMode verificationMode) { - return new VerificationOverTimeImpl(pollingPeriodMillis, timer.duration(), verificationMode, returnOnSuccess); + return new VerificationOverTimeImpl( + pollingPeriodMillis, timer.duration(), verificationMode, returnOnSuccess); } private void sleep(long sleep) { diff --git a/src/main/java/org/mockito/internal/verification/VerificationWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapper.java index 66336a94f1..8c494affd9 100644 --- a/src/main/java/org/mockito/internal/verification/VerificationWrapper.java +++ b/src/main/java/org/mockito/internal/verification/VerificationWrapper.java @@ -7,7 +7,8 @@ import org.mockito.internal.verification.api.VerificationData; import org.mockito.verification.VerificationMode; -public abstract class VerificationWrapper implements VerificationMode { +public abstract class VerificationWrapper + implements VerificationMode { protected final WrapperType wrappedVerification; @@ -19,10 +20,12 @@ public void verify(VerificationData data) { wrappedVerification.verify(data); } - protected abstract VerificationMode copySelfWithNewVerificationMode(VerificationMode verificationMode); + protected abstract VerificationMode copySelfWithNewVerificationMode( + VerificationMode verificationMode); public VerificationMode times(int wantedNumberOfInvocations) { - return copySelfWithNewVerificationMode(VerificationModeFactory.times(wantedNumberOfInvocations)); + return copySelfWithNewVerificationMode( + VerificationModeFactory.times(wantedNumberOfInvocations)); } public VerificationMode never() { @@ -34,7 +37,8 @@ public VerificationMode atLeastOnce() { } public VerificationMode atLeast(int minNumberOfInvocations) { - return copySelfWithNewVerificationMode(VerificationModeFactory.atLeast(minNumberOfInvocations)); + return copySelfWithNewVerificationMode( + VerificationModeFactory.atLeast(minNumberOfInvocations)); } public VerificationMode atMostOnce() { @@ -42,11 +46,11 @@ public VerificationMode atMostOnce() { } public VerificationMode atMost(int maxNumberOfInvocations) { - return copySelfWithNewVerificationMode(VerificationModeFactory.atMost(maxNumberOfInvocations)); + return copySelfWithNewVerificationMode( + VerificationModeFactory.atMost(maxNumberOfInvocations)); } public VerificationMode only() { return copySelfWithNewVerificationMode(VerificationModeFactory.only()); } - } diff --git a/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java index 87d9076e00..16b8c3d3bb 100644 --- a/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java +++ b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java @@ -13,12 +13,15 @@ public class VerificationWrapperInOrderWrapper implements VerificationMode { private final VerificationMode delegate; - public VerificationWrapperInOrderWrapper(VerificationWrapper verificationWrapper, InOrderImpl inOrder) { + public VerificationWrapperInOrderWrapper( + VerificationWrapper verificationWrapper, InOrderImpl inOrder) { VerificationMode verificationMode = verificationWrapper.wrappedVerification; - VerificationMode inOrderWrappedVerificationMode = wrapInOrder(verificationWrapper, verificationMode, inOrder); + VerificationMode inOrderWrappedVerificationMode = + wrapInOrder(verificationWrapper, verificationMode, inOrder); - delegate = verificationWrapper.copySelfWithNewVerificationMode(inOrderWrappedVerificationMode); + delegate = + verificationWrapper.copySelfWithNewVerificationMode(inOrderWrappedVerificationMode); } @Override @@ -26,25 +29,33 @@ public void verify(VerificationData data) { delegate.verify(data); } - private VerificationMode wrapInOrder(VerificationWrapper verificationWrapper, VerificationMode verificationMode, InOrderImpl inOrder) { + private VerificationMode wrapInOrder( + VerificationWrapper verificationWrapper, + VerificationMode verificationMode, + InOrderImpl inOrder) { if (verificationMode instanceof VerificationInOrderMode) { - final VerificationInOrderMode verificationInOrderMode = (VerificationInOrderMode)verificationMode; + final VerificationInOrderMode verificationInOrderMode = + (VerificationInOrderMode) verificationMode; return new InOrderWrapper(verificationInOrderMode, inOrder); } if (verificationMode instanceof VerificationOverTimeImpl) { - final VerificationOverTimeImpl verificationOverTime = (VerificationOverTimeImpl)verificationMode; + final VerificationOverTimeImpl verificationOverTime = + (VerificationOverTimeImpl) verificationMode; if (verificationOverTime.isReturnOnSuccess()) { - return new VerificationOverTimeImpl(verificationOverTime.getPollingPeriodMillis(), + return new VerificationOverTimeImpl( + verificationOverTime.getPollingPeriodMillis(), verificationOverTime.getTimer().duration(), - wrapInOrder(verificationWrapper, verificationOverTime.getDelegate(), inOrder), + wrapInOrder( + verificationWrapper, verificationOverTime.getDelegate(), inOrder), verificationOverTime.isReturnOnSuccess()); } } - //TODO ugly exception message!!! - throw new MockitoException(verificationMode.getClass().getSimpleName() + - " is not implemented to work with InOrder wrapped inside a " + - verificationWrapper.getClass().getSimpleName()); + // TODO ugly exception message!!! + throw new MockitoException( + verificationMode.getClass().getSimpleName() + + " is not implemented to work with InOrder wrapped inside a " + + verificationWrapper.getClass().getSimpleName()); } } diff --git a/src/main/java/org/mockito/internal/verification/api/InOrderContext.java b/src/main/java/org/mockito/internal/verification/api/InOrderContext.java index c6953bebc0..9672d7eb81 100644 --- a/src/main/java/org/mockito/internal/verification/api/InOrderContext.java +++ b/src/main/java/org/mockito/internal/verification/api/InOrderContext.java @@ -11,5 +11,4 @@ public interface InOrderContext { boolean isVerified(Invocation invocation); void markVerified(Invocation i); - } diff --git a/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrder.java b/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrder.java index 0f46063fd4..6103f5716e 100644 --- a/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrder.java +++ b/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrder.java @@ -16,5 +16,4 @@ public interface VerificationDataInOrder { MatchableInvocation getWanted(); InOrderContext getOrderingContext(); - } diff --git a/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java b/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java index 4013b07d6a..85d3963993 100644 --- a/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java +++ b/src/main/java/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java @@ -15,7 +15,8 @@ public class VerificationDataInOrderImpl implements VerificationDataInOrder { private final List allInvocations; private final MatchableInvocation wanted; - public VerificationDataInOrderImpl(InOrderContext inOrder, List allInvocations, MatchableInvocation wanted) { + public VerificationDataInOrderImpl( + InOrderContext inOrder, List allInvocations, MatchableInvocation wanted) { this.inOrder = inOrder; this.allInvocations = allInvocations; this.wanted = wanted; diff --git a/src/main/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java b/src/main/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java index 17f9196a09..653dd71a88 100644 --- a/src/main/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java +++ b/src/main/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java @@ -13,11 +13,12 @@ @SuppressWarnings("unchecked") public class ArgumentMatchingTool { - private ArgumentMatchingTool(){} + private ArgumentMatchingTool() {} /** * Suspiciously not matching arguments are those that don't match, the toString() representation is the same but types are different. */ - public static Integer[] getSuspiciouslyNotMatchingArgsIndexes(List matchers, Object[] arguments) { + public static Integer[] getSuspiciouslyNotMatchingArgsIndexes( + List matchers, Object[] arguments) { if (matchers.size() != arguments.length) { return new Integer[0]; } diff --git a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java index 86a24f2003..c4b9525452 100644 --- a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java +++ b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java @@ -21,26 +21,34 @@ public class AtLeastXNumberOfInvocationsChecker { - public static void checkAtLeastNumberOfInvocations(List invocations, MatchableInvocation wanted, int wantedCount) { + public static void checkAtLeastNumberOfInvocations( + List invocations, MatchableInvocation wanted, int wantedCount) { List actualInvocations = findInvocations(invocations, wanted); int actualCount = actualInvocations.size(); if (wantedCount > actualCount) { List allLocations = getAllLocations(actualInvocations); - throw tooFewActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations); + throw tooFewActualInvocations( + new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations); } markVerified(actualInvocations, wanted); } - public static void checkAtLeastNumberOfInvocations(List invocations, MatchableInvocation wanted, int wantedCount,InOrderContext orderingContext) { - List chunk = findAllMatchingUnverifiedChunks(invocations, wanted, orderingContext); + public static void checkAtLeastNumberOfInvocations( + List invocations, + MatchableInvocation wanted, + int wantedCount, + InOrderContext orderingContext) { + List chunk = + findAllMatchingUnverifiedChunks(invocations, wanted, orderingContext); int actualCount = chunk.size(); if (wantedCount > actualCount) { List allLocations = getAllLocations(chunk); - throw tooFewActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations); + throw tooFewActualInvocationsInOrder( + new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations); } markVerifiedInOrder(chunk, wanted, orderingContext); diff --git a/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java b/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java index 73ad4879d0..e34555621d 100644 --- a/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java +++ b/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java @@ -24,13 +24,13 @@ public class MissingInvocationChecker { - private MissingInvocationChecker() { - } + private MissingInvocationChecker() {} - public static void checkMissingInvocation(List invocations, MatchableInvocation wanted) { + public static void checkMissingInvocation( + List invocations, MatchableInvocation wanted) { List actualInvocations = findInvocations(invocations, wanted); - if (!actualInvocations.isEmpty()){ + if (!actualInvocations.isEmpty()) { return; } @@ -39,20 +39,25 @@ public static void checkMissingInvocation(List invocations, Matchabl throw wantedButNotInvoked(wanted, invocations); } - Integer[] indexesOfSuspiciousArgs = getSuspiciouslyNotMatchingArgsIndexes(wanted.getMatchers(), similar.getArguments()); + Integer[] indexesOfSuspiciousArgs = + getSuspiciouslyNotMatchingArgsIndexes(wanted.getMatchers(), similar.getArguments()); SmartPrinter smartPrinter = new SmartPrinter(wanted, invocations, indexesOfSuspiciousArgs); - List actualLocations = ListUtil.convert(invocations, new ListUtil.Converter() { - @Override - public Location convert(Invocation invocation) { - return invocation.getLocation(); - } - }); - - throw argumentsAreDifferent(smartPrinter.getWanted(), smartPrinter.getActuals(), actualLocations); + List actualLocations = + ListUtil.convert( + invocations, + new ListUtil.Converter() { + @Override + public Location convert(Invocation invocation) { + return invocation.getLocation(); + } + }); + throw argumentsAreDifferent( + smartPrinter.getWanted(), smartPrinter.getActuals(), actualLocations); } - public static void checkMissingInvocation(List invocations, MatchableInvocation wanted, InOrderContext context) { + public static void checkMissingInvocation( + List invocations, MatchableInvocation wanted, InOrderContext context) { List chunk = findAllMatchingUnverifiedChunks(invocations, wanted, context); if (!chunk.isEmpty()) { diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java index 1b5ffc14ba..460710cc93 100644 --- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java +++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java @@ -27,53 +27,68 @@ public class NumberOfInvocationsChecker { - private NumberOfInvocationsChecker() { - } + private NumberOfInvocationsChecker() {} - public static void checkNumberOfInvocations(List invocations, MatchableInvocation wanted, int wantedCount) { + public static void checkNumberOfInvocations( + List invocations, MatchableInvocation wanted, int wantedCount) { List actualInvocations = findInvocations(invocations, wanted); int actualCount = actualInvocations.size(); if (wantedCount > actualCount) { List allLocations = getAllLocations(actualInvocations); - throw tooFewActualInvocations(new Discrepancy(wantedCount, actualCount), wanted, allLocations); + throw tooFewActualInvocations( + new Discrepancy(wantedCount, actualCount), wanted, allLocations); } if (wantedCount == 0 && actualCount > 0) { throw neverWantedButInvoked(wanted, getAllLocations(actualInvocations)); } if (wantedCount < actualCount) { - throw tooManyActualInvocations(wantedCount, actualCount, wanted, getAllLocations(actualInvocations)); + throw tooManyActualInvocations( + wantedCount, actualCount, wanted, getAllLocations(actualInvocations)); } markVerified(actualInvocations, wanted); } - public static void checkNumberOfInvocations(List invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) { + public static void checkNumberOfInvocations( + List invocations, + MatchableInvocation wanted, + int wantedCount, + InOrderContext context) { List chunk = findMatchingChunk(invocations, wanted, wantedCount, context); int actualCount = chunk.size(); if (wantedCount > actualCount) { List allLocations = getAllLocations(chunk); - throw tooFewActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, allLocations); + throw tooFewActualInvocationsInOrder( + new Discrepancy(wantedCount, actualCount), wanted, allLocations); } if (wantedCount < actualCount) { - throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, getAllLocations(chunk)); + throw tooManyActualInvocationsInOrder( + wantedCount, actualCount, wanted, getAllLocations(chunk)); } markVerifiedInOrder(chunk, wanted, context); } - public static void checkNumberOfInvocationsNonGreedy(List invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) { + public static void checkNumberOfInvocationsNonGreedy( + List invocations, + MatchableInvocation wanted, + int wantedCount, + InOrderContext context) { int actualCount = 0; Location lastLocation = null; - while( actualCount < wantedCount ){ - Invocation next = findFirstMatchingUnverifiedInvocation(invocations, wanted, context ); - if( next == null ){ - throw tooFewActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, Arrays.asList(lastLocation)); + while (actualCount < wantedCount) { + Invocation next = findFirstMatchingUnverifiedInvocation(invocations, wanted, context); + if (next == null) { + throw tooFewActualInvocationsInOrder( + new Discrepancy(wantedCount, actualCount), + wanted, + Arrays.asList(lastLocation)); } - markVerified( next, wanted ); - context.markVerified( next ); + markVerified(next, wanted); + context.markVerified(next); lastLocation = next.getLocation(); actualCount++; } diff --git a/src/main/java/org/mockito/invocation/DescribedInvocation.java b/src/main/java/org/mockito/invocation/DescribedInvocation.java index fc975aba44..7c1420d4a0 100644 --- a/src/main/java/org/mockito/invocation/DescribedInvocation.java +++ b/src/main/java/org/mockito/invocation/DescribedInvocation.java @@ -4,7 +4,6 @@ */ package org.mockito.invocation; - /** * Provides information about the invocation, specifically a human readable description and the location. */ diff --git a/src/main/java/org/mockito/invocation/InvocationFactory.java b/src/main/java/org/mockito/invocation/InvocationFactory.java index d3294bd3db..3b2ef4c0c2 100644 --- a/src/main/java/org/mockito/invocation/InvocationFactory.java +++ b/src/main/java/org/mockito/invocation/InvocationFactory.java @@ -47,7 +47,12 @@ public interface InvocationFactory { * @since 2.10.0 */ @Deprecated - Invocation createInvocation(Object target, MockCreationSettings settings, Method method, Callable realMethod, Object... args); + Invocation createInvocation( + Object target, + MockCreationSettings settings, + Method method, + Callable realMethod, + Object... args); /** * Behavior of the real method. @@ -73,5 +78,10 @@ interface RealMethodBehavior extends Serializable { * @since 2.14.0 */ @Incubating - Invocation createInvocation(Object target, MockCreationSettings settings, Method method, RealMethodBehavior realMethod, Object... args); + Invocation createInvocation( + Object target, + MockCreationSettings settings, + Method method, + RealMethodBehavior realMethod, + Object... args); } diff --git a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java index 52fca881fd..2c86bd0f15 100644 --- a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java +++ b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java @@ -23,7 +23,6 @@ import org.mockito.quality.MockitoHint; import org.mockito.quality.Strictness; - /** * Mockito JUnit Runner keeps tests clean and improves debugging experience. * Make sure to try out {@link MockitoJUnitRunner.StrictStubs} which automatically @@ -150,7 +149,8 @@ public StrictStubs(Class klass) throws InvocationTargetException { private final InternalRunner runner; public MockitoJUnitRunner(Class klass) throws InvocationTargetException { - //by default, StrictRunner is used. We can change that potentially based on feedback from users + // by default, StrictRunner is used. We can change that potentially based on feedback from + // users this(new StrictRunner(new RunnerFactory().createStrict(klass), klass)); } @@ -169,7 +169,7 @@ public Description getDescription() { } public void filter(Filter filter) throws NoTestsRemainException { - //filter is required because without it UnrootedTests show up in Eclipse + // filter is required because without it UnrootedTests show up in Eclipse runner.filter(filter); } } diff --git a/src/main/java/org/mockito/junit/MockitoTestRule.java b/src/main/java/org/mockito/junit/MockitoTestRule.java index d5332a1c66..33c15e498c 100644 --- a/src/main/java/org/mockito/junit/MockitoTestRule.java +++ b/src/main/java/org/mockito/junit/MockitoTestRule.java @@ -30,5 +30,4 @@ public interface MockitoTestRule extends TestRule { */ @Incubating MockitoTestRule strictness(Strictness strictness); - } diff --git a/src/main/java/org/mockito/listeners/MockitoListener.java b/src/main/java/org/mockito/listeners/MockitoListener.java index ea8dcb6db2..b5a4e5e883 100644 --- a/src/main/java/org/mockito/listeners/MockitoListener.java +++ b/src/main/java/org/mockito/listeners/MockitoListener.java @@ -8,5 +8,4 @@ * Marker interface for all types of Mockito listeners. * For more information, see {@link org.mockito.MockitoFramework#addListener(MockitoListener)}. */ -public interface MockitoListener { -} +public interface MockitoListener {} diff --git a/src/main/java/org/mockito/plugins/InlineMockMaker.java b/src/main/java/org/mockito/plugins/InlineMockMaker.java index 7acaf19b7b..f271d5203a 100644 --- a/src/main/java/org/mockito/plugins/InlineMockMaker.java +++ b/src/main/java/org/mockito/plugins/InlineMockMaker.java @@ -47,5 +47,4 @@ public interface InlineMockMaker extends MockMaker { */ @Incubating void clearAllMocks(); - } diff --git a/src/main/java/org/mockito/plugins/MockMaker.java b/src/main/java/org/mockito/plugins/MockMaker.java index e4b0ca8b49..f2798ed8bf 100644 --- a/src/main/java/org/mockito/plugins/MockMaker.java +++ b/src/main/java/org/mockito/plugins/MockMaker.java @@ -31,7 +31,7 @@ * A file "mockito-extensions/org.mockito.plugins.MockMaker". The content of this file is * exactly a one line with the qualified name: * org.awesome.mockito.AwesomeMockMaker. -* + * * *

* @@ -64,10 +64,7 @@ public interface MockMaker { * @return The mock instance. * @since 1.9.5 */ - T createMock( - MockCreationSettings settings, - MockHandler handler - ); + T createMock(MockCreationSettings settings, MockHandler handler); /** * Returns the handler for the {@code mock}. Do not provide your own implementations at this time @@ -95,11 +92,7 @@ T createMock( * @param settings The mock settings - should you need to access some of the mock creation details. * @since 1.9.5 */ - void resetMock( - Object mock, - MockHandler newHandler, - MockCreationSettings settings - ); + void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings); /** * Indicates if the given type can be mocked by this mockmaker. diff --git a/src/main/java/org/mockito/quality/MockitoHint.java b/src/main/java/org/mockito/quality/MockitoHint.java index f261ac1630..cf36a6cc81 100644 --- a/src/main/java/org/mockito/quality/MockitoHint.java +++ b/src/main/java/org/mockito/quality/MockitoHint.java @@ -75,5 +75,4 @@ * * @since 2.1.0 */ -public interface MockitoHint { -} +public interface MockitoHint {} diff --git a/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java b/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java index ede608bbad..b25fa24e43 100644 --- a/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java +++ b/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java @@ -43,18 +43,20 @@ public ConsoleSpammingMockitoJUnitRunner(Class klass) throws InvocationTarget @Override public void run(RunNotifier notifier) { - RunListener listener = new RunListener() { - WarningsCollector warningsCollector; + RunListener listener = + new RunListener() { + WarningsCollector warningsCollector; - @Override - public void testStarted(Description description) throws Exception { - warningsCollector = new WarningsCollector(); - } + @Override + public void testStarted(Description description) throws Exception { + warningsCollector = new WarningsCollector(); + } - @Override public void testFailure(Failure failure) throws Exception { - logger.log(warningsCollector.getWarnings()); - } - }; + @Override + public void testFailure(Failure failure) throws Exception { + logger.log(warningsCollector.getWarnings()); + } + }; notifier.addListener(listener); @@ -67,7 +69,7 @@ public Description getDescription() { } public void filter(Filter filter) throws NoTestsRemainException { - //filter is required because without it UnrootedTests show up in Eclipse + // filter is required because without it UnrootedTests show up in Eclipse runner.filter(filter); } } diff --git a/src/main/java/org/mockito/runners/MockitoJUnitRunner.java b/src/main/java/org/mockito/runners/MockitoJUnitRunner.java index 1c473c6863..913ba740ad 100644 --- a/src/main/java/org/mockito/runners/MockitoJUnitRunner.java +++ b/src/main/java/org/mockito/runners/MockitoJUnitRunner.java @@ -11,7 +11,6 @@ import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.notification.RunNotifier; - /** * Runner moved to a new place see {@link org.mockito.junit.MockitoJUnitRunner} * diff --git a/src/main/java/org/mockito/runners/VerboseMockitoJUnitRunner.java b/src/main/java/org/mockito/runners/VerboseMockitoJUnitRunner.java index 7a6f4d77e4..f3a656eadc 100644 --- a/src/main/java/org/mockito/runners/VerboseMockitoJUnitRunner.java +++ b/src/main/java/org/mockito/runners/VerboseMockitoJUnitRunner.java @@ -41,23 +41,24 @@ public VerboseMockitoJUnitRunner(Class klass) throws InvocationTargetExceptio @Override public void run(RunNotifier notifier) { - //a listener that changes the failure's exception in a very hacky way... - RunListener listener = new RunListener() { + // a listener that changes the failure's exception in a very hacky way... + RunListener listener = + new RunListener() { - WarningsCollector warningsCollector; + WarningsCollector warningsCollector; - @Override - public void testStarted(Description description) throws Exception { - warningsCollector = new WarningsCollector(); - } + @Override + public void testStarted(Description description) throws Exception { + warningsCollector = new WarningsCollector(); + } - @Override - @SuppressWarnings("deprecation") - public void testFailure(final Failure failure) throws Exception { - String warnings = warningsCollector.getWarnings(); - new JUnitFailureHacker().appendWarnings(failure, warnings); - } - }; + @Override + @SuppressWarnings("deprecation") + public void testFailure(final Failure failure) throws Exception { + String warnings = warningsCollector.getWarnings(); + new JUnitFailureHacker().appendWarnings(failure, warnings); + } + }; notifier.addFirstListener(listener); @@ -70,7 +71,7 @@ public Description getDescription() { } public void filter(Filter filter) throws NoTestsRemainException { - //filter is required because without it UnrootedTests show up in Eclipse + // filter is required because without it UnrootedTests show up in Eclipse runner.filter(filter); } } diff --git a/src/main/java/org/mockito/session/MockitoSessionLogger.java b/src/main/java/org/mockito/session/MockitoSessionLogger.java index f876433c57..bf365d5707 100644 --- a/src/main/java/org/mockito/session/MockitoSessionLogger.java +++ b/src/main/java/org/mockito/session/MockitoSessionLogger.java @@ -28,5 +28,4 @@ public interface MockitoSessionLogger { */ @Incubating void log(String hint); - } diff --git a/src/main/java/org/mockito/stubbing/Answer6.java b/src/main/java/org/mockito/stubbing/Answer6.java index bf668cf862..11a95c1977 100644 --- a/src/main/java/org/mockito/stubbing/Answer6.java +++ b/src/main/java/org/mockito/stubbing/Answer6.java @@ -50,5 +50,6 @@ public interface Answer6 { * * @throws Throwable the throwable to be thrown */ - T answer( A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4, A5 argument5 ) throws Throwable; + T answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4, A5 argument5) + throws Throwable; } diff --git a/src/main/java/org/mockito/stubbing/BaseStubber.java b/src/main/java/org/mockito/stubbing/BaseStubber.java index 8c3192815e..7ac714da65 100644 --- a/src/main/java/org/mockito/stubbing/BaseStubber.java +++ b/src/main/java/org/mockito/stubbing/BaseStubber.java @@ -61,9 +61,11 @@ public interface BaseStubber { * * @since 2.1.0 */ - // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation - @SuppressWarnings ({"unchecked", "varargs"}) - Stubber doThrow(Class toBeThrown, Class... nextToBeThrown); + // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array + // creation + @SuppressWarnings({"unchecked", "varargs"}) + Stubber doThrow( + Class toBeThrown, Class... nextToBeThrown); /** * Use it for stubbing consecutive calls in {@link Mockito#doAnswer(Answer)} style: diff --git a/src/main/java/org/mockito/stubbing/OngoingStubbing.java b/src/main/java/org/mockito/stubbing/OngoingStubbing.java index 4d370abba3..cb0429bec2 100644 --- a/src/main/java/org/mockito/stubbing/OngoingStubbing.java +++ b/src/main/java/org/mockito/stubbing/OngoingStubbing.java @@ -64,8 +64,9 @@ public interface OngoingStubbing { * * @return object that allows stubbing consecutive calls */ - // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation warnings (on call site) - @SuppressWarnings ({"unchecked", "varargs"}) + // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array + // creation warnings (on call site) + @SuppressWarnings({"unchecked", "varargs"}) OngoingStubbing thenReturn(T value, T... values); /** @@ -146,9 +147,11 @@ public interface OngoingStubbing { * @return object that allows stubbing consecutive calls * @since 2.1.0 */ - // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation warnings (on call site) - @SuppressWarnings ({"unchecked", "varargs"}) - OngoingStubbing thenThrow(Class toBeThrown, Class... nextToBeThrown); + // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array + // creation warnings (on call site) + @SuppressWarnings({"unchecked", "varargs"}) + OngoingStubbing thenThrow( + Class toBeThrown, Class... nextToBeThrown); /** * Sets the real implementation to be called when the method is called on a mock object. @@ -236,5 +239,4 @@ public interface OngoingStubbing { * @since 1.9.0 */ M getMock(); - } diff --git a/src/main/java/org/mockito/stubbing/ValidableAnswer.java b/src/main/java/org/mockito/stubbing/ValidableAnswer.java index 64c5e4189a..9d0bde1bd2 100644 --- a/src/main/java/org/mockito/stubbing/ValidableAnswer.java +++ b/src/main/java/org/mockito/stubbing/ValidableAnswer.java @@ -88,5 +88,4 @@ public interface ValidableAnswer { * @since 2.3.8 */ void validateFor(InvocationOnMock invocation); - } diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer5.java b/src/main/java/org/mockito/stubbing/VoidAnswer5.java index 1ac667c837..87db6136ad 100644 --- a/src/main/java/org/mockito/stubbing/VoidAnswer5.java +++ b/src/main/java/org/mockito/stubbing/VoidAnswer5.java @@ -45,5 +45,6 @@ public interface VoidAnswer5 { * * @throws Throwable the throwable to be thrown */ - void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4) throws Throwable; + void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4) + throws Throwable; } diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer6.java b/src/main/java/org/mockito/stubbing/VoidAnswer6.java index 5df66a355f..545ca3f591 100644 --- a/src/main/java/org/mockito/stubbing/VoidAnswer6.java +++ b/src/main/java/org/mockito/stubbing/VoidAnswer6.java @@ -47,5 +47,6 @@ public interface VoidAnswer6 { * * @throws Throwable the throwable to be thrown */ - void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4, A5 argument5) throws Throwable; + void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4, A5 argument5) + throws Throwable; } diff --git a/src/main/java/org/mockito/verification/After.java b/src/main/java/org/mockito/verification/After.java index 54d7453022..5e7a0b8eae 100644 --- a/src/main/java/org/mockito/verification/After.java +++ b/src/main/java/org/mockito/verification/After.java @@ -13,7 +13,8 @@ * Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class. * See javadoc for {@link VerificationWithTimeout} */ -public class After extends VerificationWrapper implements VerificationAfterDelay { +public class After extends VerificationWrapper + implements VerificationAfterDelay { /** * See the javadoc for {@link VerificationAfterDelay} diff --git a/src/main/java/org/mockito/verification/Timeout.java b/src/main/java/org/mockito/verification/Timeout.java index 99dcc45f53..9737f83ef6 100644 --- a/src/main/java/org/mockito/verification/Timeout.java +++ b/src/main/java/org/mockito/verification/Timeout.java @@ -16,7 +16,8 @@ * Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class. * See javadoc for {@link VerificationWithTimeout} */ -public class Timeout extends VerificationWrapper implements VerificationWithTimeout { +public class Timeout extends VerificationWrapper + implements VerificationWithTimeout { /** * See the javadoc for {@link VerificationWithTimeout} @@ -47,7 +48,8 @@ public Timeout(long millis, VerificationMode delegate) { } @Override - protected VerificationMode copySelfWithNewVerificationMode(VerificationMode newVerificationMode) { + protected VerificationMode copySelfWithNewVerificationMode( + VerificationMode newVerificationMode) { return new Timeout(wrappedVerification.copyWithVerificationMode(newVerificationMode)); } @@ -58,5 +60,4 @@ public VerificationMode atMost(int maxNumberOfInvocations) { public VerificationMode never() { throw atMostAndNeverShouldNotBeUsedWithTimeout(); } - } diff --git a/src/main/java/org/mockito/verification/VerificationAfterDelay.java b/src/main/java/org/mockito/verification/VerificationAfterDelay.java index 96b56f1f73..c99a34d2ee 100644 --- a/src/main/java/org/mockito/verification/VerificationAfterDelay.java +++ b/src/main/java/org/mockito/verification/VerificationAfterDelay.java @@ -6,7 +6,6 @@ import org.mockito.Mockito; - /** * VerificationAfterDelay is a {@link VerificationMode} that allows combining existing verification modes with an initial delay, e.g. *

@@ -65,5 +64,4 @@ public interface VerificationAfterDelay extends VerificationMode {
      * period given, unless another method is invoked (in which case there will be an immediate failure)
      */
     VerificationMode only();
-
 }
diff --git a/src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java b/src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java
index 55437f12f6..4e2d8b940a 100644
--- a/src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java
+++ b/src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java
@@ -12,14 +12,14 @@
 import org.mockitousage.IMethods;
 import org.mockitoutil.TestBase;
 
-//this test exposes the problem most of the time
+// this test exposes the problem most of the time
 public class ThreadVerifiesContinuouslyInteractingMockTest extends TestBase {
 
     @Mock private IMethods mock;
 
     @Test
     public void shouldAllowVerifyingInThreads() throws Exception {
-        for(int i = 0; i < 100; i++) {
+        for (int i = 0; i < 100; i++) {
             performTest();
         }
     }
@@ -29,17 +29,18 @@ private void performTest() throws InterruptedException {
         final Thread[] listeners = new Thread[2];
         for (int i = 0; i < listeners.length; i++) {
             final int x = i;
-            listeners[i] = new Thread() {
-                @Override
-                public void run() {
-                    try {
-                        Thread.sleep(x * 10);
-                    } catch (InterruptedException e) {
-                        throw new RuntimeException(e);
-                    }
-                    mock.simpleMethod();
-                }
-            };
+            listeners[i] =
+                    new Thread() {
+                        @Override
+                        public void run() {
+                            try {
+                                Thread.sleep(x * 10);
+                            } catch (InterruptedException e) {
+                                throw new RuntimeException(e);
+                            }
+                            mock.simpleMethod();
+                        }
+                    };
             listeners[i].start();
         }
 
diff --git a/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java b/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java
index 66ffaa33b2..aa15ca4c20 100644
--- a/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java
+++ b/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java
@@ -67,74 +67,74 @@ private static class AllTestsRunner extends Thread {
         private Set> failed = new HashSet>();
 
         public void run() {
-            Result result = JUnitCore.runClasses(
-                    EqualsTest.class,
-                    ListUtilTest.class,
-                    MockingProgressImplTest.class,
-                    TimesTest.class,
-                    MockHandlerImplTest.class,
-                    AllInvocationsFinderTest.class,
-                    ReturnsEmptyValuesTest.class,
-                    NumberOfInvocationsCheckerTest.class,
-                    DefaultRegisteredInvocationsTest.class,
-                    MissingInvocationCheckerTest.class,
-                    NumberOfInvocationsInOrderCheckerTest.class,
-                    MissingInvocationInOrderCheckerTest.class,
-                    TypeCachingMockBytecodeGeneratorTest.class,
-                    InvocationMatcherTest.class,
-                    InvocationsFinderTest.class,
-                    MockitoTest.class,
-                    MockUtilTest.class,
-                    ReporterTest.class,
-                    MockitoAssertionErrorTest.class,
-                    MockitoExceptionTest.class,
-                    StackTraceFilteringTest.class,
-                    BridgeMethodPuzzleTest.class,
-                    OverloadingPuzzleTest.class,
-                    InvalidUsageTest.class,
-                    UsingVarargsTest.class,
-                    CustomMatchersTest.class,
-                    ComparableMatchersTest.class,
-                    InvalidUseOfMatchersTest.class,
-                    MatchersTest.class,
-                    MatchersToStringTest.class,
-                    VerificationAndStubbingUsingMatchersTest.class,
-                    BasicStubbingTest.class,
-                    ReturningDefaultValuesTest.class,
-                    StubbingWithThrowablesTest.class,
-                    AtMostXVerificationTest.class,
-                    BasicVerificationTest.class,
-                    ExactNumberOfTimesVerificationTest.class,
-                    VerificationInOrderTest.class,
-                    NoMoreInteractionsVerificationTest.class,
-                    SelectedMocksInOrderVerificationTest.class,
-                    VerificationOnMultipleMocksUsingMatchersTest.class,
-                    VerificationUsingMatchersTest.class,
-                    RelaxedVerificationInOrderTest.class,
-                    DescriptiveMessagesWhenVerificationFailsTest.class,
-                    DescriptiveMessagesWhenTimesXVerificationFailsTest.class,
-                    BasicVerificationInOrderTest.class,
-                    VerificationInOrderMixedWithOrdiraryVerificationTest.class,
-                    DescriptiveMessagesOnVerificationInOrderErrorsTest.class,
-                    InvalidStateDetectionTest.class,
-                    ReplacingObjectMethodsTest.class,
-                    ClickableStackTracesTest.class,
-                    ExampleTest.class,
-                    PointingStackTraceToActualInvocationTest.class,
-                    VerificationInOrderFromMultipleThreadsTest.class,
-                    ResetTest.class,
-                    ReturnsGenericDeepStubsTest.class
-                );
+            Result result =
+                    JUnitCore.runClasses(
+                            EqualsTest.class,
+                            ListUtilTest.class,
+                            MockingProgressImplTest.class,
+                            TimesTest.class,
+                            MockHandlerImplTest.class,
+                            AllInvocationsFinderTest.class,
+                            ReturnsEmptyValuesTest.class,
+                            NumberOfInvocationsCheckerTest.class,
+                            DefaultRegisteredInvocationsTest.class,
+                            MissingInvocationCheckerTest.class,
+                            NumberOfInvocationsInOrderCheckerTest.class,
+                            MissingInvocationInOrderCheckerTest.class,
+                            TypeCachingMockBytecodeGeneratorTest.class,
+                            InvocationMatcherTest.class,
+                            InvocationsFinderTest.class,
+                            MockitoTest.class,
+                            MockUtilTest.class,
+                            ReporterTest.class,
+                            MockitoAssertionErrorTest.class,
+                            MockitoExceptionTest.class,
+                            StackTraceFilteringTest.class,
+                            BridgeMethodPuzzleTest.class,
+                            OverloadingPuzzleTest.class,
+                            InvalidUsageTest.class,
+                            UsingVarargsTest.class,
+                            CustomMatchersTest.class,
+                            ComparableMatchersTest.class,
+                            InvalidUseOfMatchersTest.class,
+                            MatchersTest.class,
+                            MatchersToStringTest.class,
+                            VerificationAndStubbingUsingMatchersTest.class,
+                            BasicStubbingTest.class,
+                            ReturningDefaultValuesTest.class,
+                            StubbingWithThrowablesTest.class,
+                            AtMostXVerificationTest.class,
+                            BasicVerificationTest.class,
+                            ExactNumberOfTimesVerificationTest.class,
+                            VerificationInOrderTest.class,
+                            NoMoreInteractionsVerificationTest.class,
+                            SelectedMocksInOrderVerificationTest.class,
+                            VerificationOnMultipleMocksUsingMatchersTest.class,
+                            VerificationUsingMatchersTest.class,
+                            RelaxedVerificationInOrderTest.class,
+                            DescriptiveMessagesWhenVerificationFailsTest.class,
+                            DescriptiveMessagesWhenTimesXVerificationFailsTest.class,
+                            BasicVerificationInOrderTest.class,
+                            VerificationInOrderMixedWithOrdiraryVerificationTest.class,
+                            DescriptiveMessagesOnVerificationInOrderErrorsTest.class,
+                            InvalidStateDetectionTest.class,
+                            ReplacingObjectMethodsTest.class,
+                            ClickableStackTracesTest.class,
+                            ExampleTest.class,
+                            PointingStackTraceToActualInvocationTest.class,
+                            VerificationInOrderFromMultipleThreadsTest.class,
+                            ResetTest.class,
+                            ReturnsGenericDeepStubsTest.class);
 
-                if (!result.wasSuccessful()) {
-                    System.err.println("Thread[" + Thread.currentThread().getId() + "]: error!");
-                    List failures = result.getFailures();
-                    System.err.println(failures.size());
-                    for (Failure failure : failures) {
-                        System.err.println(failure.getTrace());
-                        failed.add(failure.getDescription().getTestClass());
-                    }
+            if (!result.wasSuccessful()) {
+                System.err.println("Thread[" + Thread.currentThread().getId() + "]: error!");
+                List failures = result.getFailures();
+                System.err.println(failures.size());
+                for (Failure failure : failures) {
+                    System.err.println(failure.getTrace());
+                    failed.add(failure.getDescription().getTestClass());
                 }
+            }
         }
 
         public Set> getFailed() {
@@ -144,8 +144,11 @@ public Set> getFailed() {
 
     @Test
     public void shouldRunInMultipleThreads() throws Exception {
-        //this test ALWAYS fails if there is a single failing unit
-        assertEquals("Run in multiple thread failed for tests", Collections.emptySet(), runInMultipleThreads(3));
+        // this test ALWAYS fails if there is a single failing unit
+        assertEquals(
+                "Run in multiple thread failed for tests",
+                Collections.emptySet(),
+                runInMultipleThreads(3));
     }
 
     public static Set> runInMultipleThreads(int numberOfThreads) throws Exception {
@@ -172,7 +175,14 @@ public static void main(String[] args) throws Exception {
         long before = System.currentTimeMillis();
         Set> failed = runInMultipleThreads(numberOfThreads);
         long after = System.currentTimeMillis();
-        long executionTime = (after-before)/1000;
-        System.out.println("Finished tests in " + numberOfThreads + " threads in " + executionTime + " seconds. (" + failed.size() + " tests failed)");
+        long executionTime = (after - before) / 1000;
+        System.out.println(
+                "Finished tests in "
+                        + numberOfThreads
+                        + " threads in "
+                        + executionTime
+                        + " seconds. ("
+                        + failed.size()
+                        + " tests failed)");
     }
 }
diff --git a/src/test/java/org/concurrentmockito/ThreadsShareAMockTest.java b/src/test/java/org/concurrentmockito/ThreadsShareAMockTest.java
index 3e01433176..d27276a016 100644
--- a/src/test/java/org/concurrentmockito/ThreadsShareAMockTest.java
+++ b/src/test/java/org/concurrentmockito/ThreadsShareAMockTest.java
@@ -16,7 +16,7 @@ public class ThreadsShareAMockTest extends TestBase {
 
     @Test
     public void shouldAllowVerifyingInThreads() throws Exception {
-        for(int i = 0; i < 100; i++) {
+        for (int i = 0; i < 100; i++) {
             performTest();
         }
     }
@@ -25,12 +25,13 @@ private void performTest() throws InterruptedException {
         mock = mock(IMethods.class);
         final Thread[] listeners = new Thread[3];
         for (int i = 0; i < listeners.length; i++) {
-            listeners[i] = new Thread() {
-                @Override
-                public void run() {
-                    mock.simpleMethod("foo");
-                }
-            };
+            listeners[i] =
+                    new Thread() {
+                        @Override
+                        public void run() {
+                            mock.simpleMethod("foo");
+                        }
+                    };
             listeners[i].start();
         }
         for (Thread listener : listeners) {
diff --git a/src/test/java/org/concurrentmockito/ThreadsShareGenerouslyStubbedMockTest.java b/src/test/java/org/concurrentmockito/ThreadsShareGenerouslyStubbedMockTest.java
index 23ecdf129c..f937674e75 100644
--- a/src/test/java/org/concurrentmockito/ThreadsShareGenerouslyStubbedMockTest.java
+++ b/src/test/java/org/concurrentmockito/ThreadsShareGenerouslyStubbedMockTest.java
@@ -11,15 +11,15 @@
 import org.mockitousage.IMethods;
 import org.mockitoutil.TestBase;
 
-//this test always passes but please keep looking sys err
-//this test should be run 10 times, manually
+// this test always passes but please keep looking sys err
+// this test should be run 10 times, manually
 public class ThreadsShareGenerouslyStubbedMockTest extends TestBase {
 
     private IMethods mock;
 
     @Test
     public void shouldAllowVerifyingInThreads() throws Exception {
-        for(int i = 0; i < 50; i++) {
+        for (int i = 0; i < 50; i++) {
             performTest();
         }
     }
@@ -28,30 +28,31 @@ private void performTest() throws InterruptedException {
         mock = mock(IMethods.class);
 
         when(mock.simpleMethod("foo"))
-            .thenReturn("foo")
-            .thenReturn("bar")
-            .thenReturn("baz")
-            .thenReturn("foo")
-            .thenReturn("bar")
-            .thenReturn("baz");
+                .thenReturn("foo")
+                .thenReturn("bar")
+                .thenReturn("baz")
+                .thenReturn("foo")
+                .thenReturn("bar")
+                .thenReturn("baz");
 
         final Thread[] listeners = new Thread[100];
         for (int i = 0; i < listeners.length; i++) {
-            listeners[i] = new Thread() {
-                @Override
-                public void run() {
-                    try {
-                        mock.simpleMethod("foo");
-                        mock.simpleMethod("foo");
-                        mock.simpleMethod("foo");
-                        mock.simpleMethod("foo");
-                        mock.simpleMethod("foo");
-                        mock.simpleMethod("foo");
-                    } catch (Exception e) {
-                        throw new RuntimeException(e);
-                    }
-                }
-            };
+            listeners[i] =
+                    new Thread() {
+                        @Override
+                        public void run() {
+                            try {
+                                mock.simpleMethod("foo");
+                                mock.simpleMethod("foo");
+                                mock.simpleMethod("foo");
+                                mock.simpleMethod("foo");
+                                mock.simpleMethod("foo");
+                                mock.simpleMethod("foo");
+                            } catch (Exception e) {
+                                throw new RuntimeException(e);
+                            }
+                        }
+                    };
             listeners[i].start();
         }
         for (Thread listener : listeners) {
diff --git a/src/test/java/org/concurrentmockito/VerificationInOrderFromMultipleThreadsTest.java b/src/test/java/org/concurrentmockito/VerificationInOrderFromMultipleThreadsTest.java
index b30d21a573..8f2c5e8535 100644
--- a/src/test/java/org/concurrentmockito/VerificationInOrderFromMultipleThreadsTest.java
+++ b/src/test/java/org/concurrentmockito/VerificationInOrderFromMultipleThreadsTest.java
@@ -17,19 +17,23 @@ public class VerificationInOrderFromMultipleThreadsTest extends TestBase {
     public void shouldVerifyInOrderWhenMultipleThreadsInteractWithMock() throws Exception {
         final Foo testInf = mock(Foo.class);
 
-        Thread threadOne = new Thread(new Runnable(){
-            public void run() {
-                testInf.methodOne();
-            }
-        });
+        Thread threadOne =
+                new Thread(
+                        new Runnable() {
+                            public void run() {
+                                testInf.methodOne();
+                            }
+                        });
         threadOne.start();
         threadOne.join();
 
-        Thread threadTwo = new Thread(new Runnable(){
-            public void run() {
-                testInf.methodTwo();
-            }
-        });
+        Thread threadTwo =
+                new Thread(
+                        new Runnable() {
+                            public void run() {
+                                testInf.methodTwo();
+                            }
+                        });
         threadTwo.start();
         threadTwo.join();
 
@@ -40,6 +44,7 @@ public void run() {
 
     public interface Foo {
         void methodOne();
+
         void methodTwo();
     }
 }
diff --git a/src/test/java/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java b/src/test/java/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java
index 145e23c6a7..6a017d502e 100644
--- a/src/test/java/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java
+++ b/src/test/java/org/mockito/AnnotationsAreCopiedFromMockedTypeTest.java
@@ -24,10 +24,14 @@ public class AnnotationsAreCopiedFromMockedTypeTest {
 
     @Test
     public void mock_should_have_annotations_copied_from_mocked_type_at_class_level() {
-        AnnotationWithDefaultValue onClassDefaultValue = mock(OnClass.class).getClass().getAnnotation(AnnotationWithDefaultValue.class);
-        AnnotationWithCustomValue onClassCustomValue = mock(OnClass.class).getClass().getAnnotation(AnnotationWithCustomValue.class);
+        AnnotationWithDefaultValue onClassDefaultValue =
+                mock(OnClass.class).getClass().getAnnotation(AnnotationWithDefaultValue.class);
+        AnnotationWithCustomValue onClassCustomValue =
+                mock(OnClass.class).getClass().getAnnotation(AnnotationWithCustomValue.class);
 
-        assumeTrue("Annotation copying does not apply for inline mocks", mock(OnClass.class).getClass() != OnClass.class);
+        assumeTrue(
+                "Annotation copying does not apply for inline mocks",
+                mock(OnClass.class).getClass() != OnClass.class);
 
         Assertions.assertThat(onClassDefaultValue.value()).isEqualTo("yup");
         Assertions.assertThat(onClassCustomValue.value()).isEqualTo("yay");
@@ -35,8 +39,12 @@ public void mock_should_have_annotations_copied_from_mocked_type_at_class_level(
 
     @Test
     public void mock_should_have_annotations_copied_from_mocked_type_on_methods() {
-        AnnotationWithDefaultValue onClassDefaultValue = method("method", mock(OnMethod.class)).getAnnotation(AnnotationWithDefaultValue.class);
-        AnnotationWithCustomValue onClassCustomValue = method("method", mock(OnMethod.class)).getAnnotation(AnnotationWithCustomValue.class);
+        AnnotationWithDefaultValue onClassDefaultValue =
+                method("method", mock(OnMethod.class))
+                        .getAnnotation(AnnotationWithDefaultValue.class);
+        AnnotationWithCustomValue onClassCustomValue =
+                method("method", mock(OnMethod.class))
+                        .getAnnotation(AnnotationWithCustomValue.class);
 
         Assertions.assertThat(onClassDefaultValue.value()).isEqualTo("yup");
         Assertions.assertThat(onClassCustomValue.value()).isEqualTo("yay");
@@ -44,8 +52,12 @@ public void mock_should_have_annotations_copied_from_mocked_type_on_methods() {
 
     @Test
     public void mock_should_have_annotations_copied_from_mocked_type_on_method_parameters() {
-        AnnotationWithDefaultValue onClassDefaultValue = firstParamOf(method("method", mock(OnMethod.class))).getAnnotation(AnnotationWithDefaultValue.class);
-        AnnotationWithCustomValue onClassCustomValue = firstParamOf(method("method", mock(OnMethod.class))).getAnnotation(AnnotationWithCustomValue.class);
+        AnnotationWithDefaultValue onClassDefaultValue =
+                firstParamOf(method("method", mock(OnMethod.class)))
+                        .getAnnotation(AnnotationWithDefaultValue.class);
+        AnnotationWithCustomValue onClassCustomValue =
+                firstParamOf(method("method", mock(OnMethod.class)))
+                        .getAnnotation(AnnotationWithCustomValue.class);
 
         Assertions.assertThat(onClassDefaultValue.value()).isEqualTo("yup");
         Assertions.assertThat(onClassCustomValue.value()).isEqualTo("yay");
@@ -85,7 +97,7 @@ public Annotation[] getDeclaredAnnotations() {
 
     private Method method(String methodName, Object mock) {
         for (Method method : mock.getClass().getDeclaredMethods()) {
-            if(methodName.equals(method.getName())) {
+            if (methodName.equals(method.getName())) {
                 return method;
             }
         }
@@ -94,7 +106,7 @@ private Method method(String methodName, Object mock) {
 
     private Field field(String fieldName, Object mock) {
         for (Field field : mock.getClass().getDeclaredFields()) {
-            if(fieldName.equals(field.getName())) {
+            if (fieldName.equals(field.getName())) {
                 return field;
             }
         }
@@ -103,17 +115,15 @@ private Field field(String fieldName, Object mock) {
 
     @AnnotationWithDefaultValue
     @AnnotationWithCustomValue("yay")
-    public class OnClass { }
-
+    public class OnClass {}
 
     public class OnMethod {
         @AnnotationWithDefaultValue
         @AnnotationWithCustomValue("yay")
         public String method(
-                @AnnotationWithDefaultValue
-                @AnnotationWithCustomValue("yay")
-                String ignored
-        ) { return ""; }
+                @AnnotationWithDefaultValue @AnnotationWithCustomValue("yay") String ignored) {
+            return "";
+        }
     }
 
     @Retention(RetentionPolicy.RUNTIME)
diff --git a/src/test/java/org/mockito/ArgumentCaptorTest.java b/src/test/java/org/mockito/ArgumentCaptorTest.java
index 77ecf0d3be..13b37c89a6 100644
--- a/src/test/java/org/mockito/ArgumentCaptorTest.java
+++ b/src/test/java/org/mockito/ArgumentCaptorTest.java
@@ -22,7 +22,6 @@ public void tearDown() {
             validateMockitoUsage();
         } catch (InvalidUseOfMatchersException ignore) {
         }
-
     }
 
     @Test
@@ -30,7 +29,5 @@ public void tell_handy_return_values_to_return_value_for() throws Exception {
 
         ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class);
         assertThat(captor.capture()).isNull();
-
     }
-
 }
diff --git a/src/test/java/org/mockito/InvocationFactoryTest.java b/src/test/java/org/mockito/InvocationFactoryTest.java
index 229fbcb38f..5837a7d86f 100644
--- a/src/test/java/org/mockito/InvocationFactoryTest.java
+++ b/src/test/java/org/mockito/InvocationFactoryTest.java
@@ -27,15 +27,19 @@ public String testMethod() throws Throwable {
 
     @Test
     public void call_method_that_throws_a_throwable() throws Throwable {
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock,
-            withSettings().build(TestClass.class),
-            TestClass.class.getDeclaredMethod("testMethod"),
-            new InvocationFactory.RealMethodBehavior() {
-            @Override
-            public Object call() throws Throwable {
-                throw new Throwable("mocked");
-            }
-        });
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(TestClass.class),
+                                TestClass.class.getDeclaredMethod("testMethod"),
+                                new InvocationFactory.RealMethodBehavior() {
+                                    @Override
+                                    public Object call() throws Throwable {
+                                        throw new Throwable("mocked");
+                                    }
+                                });
 
         try {
             Mockito.mockingDetails(mock).getMockHandler().handle(invocation);
@@ -49,15 +53,19 @@ public Object call() throws Throwable {
 
     @Test
     public void call_method_that_returns_a_string() throws Throwable {
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock,
-            withSettings().build(TestClass.class),
-            TestClass.class.getDeclaredMethod("testMethod"),
-            new InvocationFactory.RealMethodBehavior() {
-                @Override
-                public Object call() throws Throwable {
-                    return "mocked";
-                }
-            });
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(TestClass.class),
+                                TestClass.class.getDeclaredMethod("testMethod"),
+                                new InvocationFactory.RealMethodBehavior() {
+                                    @Override
+                                    public Object call() throws Throwable {
+                                        return "mocked";
+                                    }
+                                });
 
         Object ret = Mockito.mockingDetails(mock).getMockHandler().handle(invocation);
         assertEquals("mocked", ret);
@@ -65,14 +73,18 @@ public Object call() throws Throwable {
 
     @Test
     public void deprecated_api_still_works() throws Throwable {
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock,
-            withSettings().build(TestClass.class),
-            TestClass.class.getDeclaredMethod("testMethod"),
-            new Callable() {
-                public Object call() throws Exception {
-                    return "mocked";
-                }
-            });
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(TestClass.class),
+                                TestClass.class.getDeclaredMethod("testMethod"),
+                                new Callable() {
+                                    public Object call() throws Exception {
+                                        return "mocked";
+                                    }
+                                });
 
         Object ret = Mockito.mockingDetails(mock).getMockHandler().handle(invocation);
         assertEquals("mocked", ret);
diff --git a/src/test/java/org/mockito/MockitoTest.java b/src/test/java/org/mockito/MockitoTest.java
index fb75024a27..008bf7f579 100644
--- a/src/test/java/org/mockito/MockitoTest.java
+++ b/src/test/java/org/mockito/MockitoTest.java
@@ -22,55 +22,54 @@ public class MockitoTest {
     public void shouldRemoveStubbableFromProgressAfterStubbing() {
         List mock = Mockito.mock(List.class);
         Mockito.when(mock.add("test")).thenReturn(true);
-        //TODO Consider to move to separate test
+        // TODO Consider to move to separate test
         assertThat(mockingProgress().pullOngoingStubbing()).isNull();
     }
 
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
-    @Test(expected=NotAMockException.class)
+    @Test(expected = NotAMockException.class)
     public void shouldValidateMockWhenVerifying() {
         Mockito.verify("notMock");
     }
 
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
-    @Test(expected=NotAMockException.class)
+    @Test(expected = NotAMockException.class)
     public void shouldValidateMockWhenVerifyingWithExpectedNumberOfInvocations() {
         Mockito.verify("notMock", times(19));
     }
 
-    @Test(expected=NotAMockException.class)
+    @Test(expected = NotAMockException.class)
     public void shouldValidateMockWhenVerifyingNoMoreInteractions() {
         Mockito.verifyNoMoreInteractions("notMock");
     }
 
-    @Test(expected=NotAMockException.class)
+    @Test(expected = NotAMockException.class)
     public void shouldValidateMockWhenVerifyingZeroInteractions() {
         Mockito.verifyZeroInteractions("notMock");
     }
 
-    @Test(expected=NotAMockException.class)
+    @Test(expected = NotAMockException.class)
     public void shouldValidateMockWhenVerifyingNoInteractions() {
         Mockito.verifyNoInteractions("notMock");
     }
 
-    @Test(expected=NullInsteadOfMockException.class)
+    @Test(expected = NullInsteadOfMockException.class)
     public void shouldValidateNullMockWhenVerifyingNoInteractions() {
-        Mockito.verifyNoInteractions(new Object[] { null });
+        Mockito.verifyNoInteractions(new Object[] {null});
     }
 
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
-    @Test(expected=NotAMockException.class)
+    @Test(expected = NotAMockException.class)
     public void shouldValidateMockWhenCreatingInOrderObject() {
         Mockito.inOrder("notMock");
     }
 
     @Test
     public void shouldStartingMockSettingsContainDefaultBehavior() {
-        //when
+        // when
         MockSettingsImpl settings = (MockSettingsImpl) Mockito.withSettings();
 
-        //then
+        // then
         assertThat(Mockito.RETURNS_DEFAULTS).isEqualTo(settings.getDefaultAnswer());
     }
-
 }
diff --git a/src/test/java/org/mockito/StaticMockingExperimentTest.java b/src/test/java/org/mockito/StaticMockingExperimentTest.java
index 59401c8794..afe049e202 100644
--- a/src/test/java/org/mockito/StaticMockingExperimentTest.java
+++ b/src/test/java/org/mockito/StaticMockingExperimentTest.java
@@ -43,119 +43,197 @@ public class StaticMockingExperimentTest extends TestBase {
     Foo mock = Mockito.mock(Foo.class);
     MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();
     Method staticMethod;
-    InvocationFactory.RealMethodBehavior realMethod = new InvocationFactory.RealMethodBehavior() {
-        @Override
-        public Object call() throws Throwable {
-            return null;
-        }
-    };
-
-    @Before public void before() throws Throwable {
+    InvocationFactory.RealMethodBehavior realMethod =
+            new InvocationFactory.RealMethodBehavior() {
+                @Override
+                public Object call() throws Throwable {
+                    return null;
+                }
+            };
+
+    @Before
+    public void before() throws Throwable {
         staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class);
     }
 
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
     @Test
     public void verify_static_method() throws Throwable {
-        //register staticMethod call on mock
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "some arg");
+        // register staticMethod call on mock
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "some arg");
         handler.handle(invocation);
 
-        //verify staticMethod on mock
-        //Mockito cannot capture static methods so we will simulate this scenario in 3 steps:
-        //1. Call standard 'verify' method. Internally, it will add verificationMode to the thread local state.
-        //  Effectively, we indicate to Mockito that right now we are about to verify a method call on this mock.
+        // verify staticMethod on mock
+        // Mockito cannot capture static methods so we will simulate this scenario in 3 steps:
+        // 1. Call standard 'verify' method. Internally, it will add verificationMode to the thread
+        // local state.
+        //  Effectively, we indicate to Mockito that right now we are about to verify a method call
+        // on this mock.
         verify(mock);
-        //2. Create the invocation instance using the new public API
-        //  Mockito cannot capture static methods but we can create an invocation instance of that static invocation
-        Invocation verification = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "some arg");
-        //3. Make Mockito handle the static method invocation
-        //  Mockito will find verification mode in thread local state and will try verify the invocation
+        // 2. Create the invocation instance using the new public API
+        //  Mockito cannot capture static methods but we can create an invocation instance of that
+        // static invocation
+        Invocation verification =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "some arg");
+        // 3. Make Mockito handle the static method invocation
+        //  Mockito will find verification mode in thread local state and will try verify the
+        // invocation
         handler.handle(verification);
 
-        //verify zero times, method with different argument
+        // verify zero times, method with different argument
         verify(mock, times(0));
-        Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "different arg");
+        Invocation differentArg =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "different arg");
         handler.handle(differentArg);
     }
 
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
     @Test
     public void verification_failure_static_method() throws Throwable {
-        //register staticMethod call on mock
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "foo");
+        // register staticMethod call on mock
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "foo");
         handler.handle(invocation);
 
-        //verify staticMethod on mock
+        // verify staticMethod on mock
         verify(mock);
-        Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "different arg");
+        Invocation differentArg =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "different arg");
 
         try {
             handler.handle(differentArg);
             fail();
-        } catch (ArgumentsAreDifferent e) {}
+        } catch (ArgumentsAreDifferent e) {
+        }
     }
 
     @Test
     public void stubbing_static_method() throws Throwable {
-        //register staticMethod call on mock
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "foo");
+        // register staticMethod call on mock
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "foo");
         handler.handle(invocation);
 
-        //register stubbing
+        // register stubbing
         when(null).thenReturn("hey");
 
-        //validate stubbed return value
+        // validate stubbed return value
         assertEquals("hey", handler.handle(invocation));
         assertEquals("hey", handler.handle(invocation));
 
-        //default null value is returned if invoked with different argument
-        Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "different arg");
+        // default null value is returned if invoked with different argument
+        Invocation differentArg =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "different arg");
         assertEquals(null, handler.handle(differentArg));
     }
 
     @Test
     public void do_answer_stubbing_static_method() throws Throwable {
-        //register stubbed return value
+        // register stubbed return value
         doReturn("hey").when(mock);
 
-        //complete stubbing by triggering an invocation that needs to be stubbed
-        Invocation invocation = Mockito.framework().getInvocationFactory()
-            .createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod, "foo");
+        // complete stubbing by triggering an invocation that needs to be stubbed
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "foo");
         handler.handle(invocation);
 
-        //validate stubbed return value
+        // validate stubbed return value
         assertEquals("hey", handler.handle(invocation));
         assertEquals("hey", handler.handle(invocation));
 
-        //default null value is returned if invoked with different argument
-        Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "different arg");
+        // default null value is returned if invoked with different argument
+        Invocation differentArg =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "different arg");
         assertEquals(null, handler.handle(differentArg));
     }
 
     @Test
     public void verify_no_more_interactions() throws Throwable {
-        //works for now because there are not interactions
+        // works for now because there are not interactions
         verifyNoMoreInteractions(mock);
 
-        //register staticMethod call on mock
-        Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
-            "foo");
+        // register staticMethod call on mock
+        Invocation invocation =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                staticMethod,
+                                realMethod,
+                                "foo");
         handler.handle(invocation);
 
-        //fails now because we have one static invocation recorded
+        // fails now because we have one static invocation recorded
         try {
             verifyNoMoreInteractions(mock);
             fail();
-        } catch (NoInteractionsWanted e) {}
+        } catch (NoInteractionsWanted e) {
+        }
     }
 
     @Test
@@ -163,19 +241,35 @@ public void stubbing_new() throws Throwable {
         Constructor ctr = Foo.class.getConstructor(String.class);
         Method adapter = ConstructorMethodAdapter.class.getDeclaredMethods()[0];
 
-        //stub constructor
+        // stub constructor
         doReturn(new Foo("hey!")).when(mock);
-        Invocation constructor = Mockito.framework().getInvocationFactory().createInvocation(
-            mock, withSettings().build(Foo.class), adapter, realMethod, ctr, "foo");
+        Invocation constructor =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                adapter,
+                                realMethod,
+                                ctr,
+                                "foo");
         handler.handle(constructor);
 
-        //test stubbing
+        // test stubbing
         Object result = handler.handle(constructor);
         assertEquals("foo:hey!", result.toString());
 
-        //stubbing miss
-        Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class),
-            adapter, realMethod, ctr, "different arg");
+        // stubbing miss
+        Invocation differentArg =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                adapter,
+                                realMethod,
+                                ctr,
+                                "different arg");
         Object result2 = handler.handle(differentArg);
         assertEquals(null, result2);
     }
@@ -186,26 +280,40 @@ public void verifying_new() throws Throwable {
         Constructor ctr = Foo.class.getConstructor(String.class);
         Method adapter = ConstructorMethodAdapter.class.getDeclaredMethods()[0];
 
-        //invoke constructor
-        Invocation constructor = Mockito.framework().getInvocationFactory().createInvocation(
-            mock, withSettings().build(Foo.class), adapter, realMethod, ctr, "matching arg");
+        // invoke constructor
+        Invocation constructor =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                adapter,
+                                realMethod,
+                                ctr,
+                                "matching arg");
         handler.handle(constructor);
 
-        //verify successfully
+        // verify successfully
         verify(mock);
         handler.handle(constructor);
 
-        //verification failure
+        // verification failure
         verify(mock);
-        Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class),
-            adapter, realMethod, ctr, "different arg");
+        Invocation differentArg =
+                Mockito.framework()
+                        .getInvocationFactory()
+                        .createInvocation(
+                                mock,
+                                withSettings().build(Foo.class),
+                                adapter,
+                                realMethod,
+                                ctr,
+                                "different arg");
         try {
             handler.handle(differentArg);
             fail();
         } catch (WantedButNotInvoked e) {
-            assertThat(e.getMessage())
-                .contains("matching arg")
-                .contains("different arg");
+            assertThat(e.getMessage()).contains("matching arg").contains("different arg");
         }
     }
 
diff --git a/src/test/java/org/mockito/configuration/MockitoConfiguration.java b/src/test/java/org/mockito/configuration/MockitoConfiguration.java
index bc7df845b4..5834485e43 100644
--- a/src/test/java/org/mockito/configuration/MockitoConfiguration.java
+++ b/src/test/java/org/mockito/configuration/MockitoConfiguration.java
@@ -7,7 +7,8 @@
 import org.mockito.stubbing.Answer;
 import org.mockitousage.configuration.CustomizedAnnotationForSmartMockTest;
 
-public class MockitoConfiguration extends DefaultMockitoConfiguration implements IMockitoConfiguration {
+public class MockitoConfiguration extends DefaultMockitoConfiguration
+        implements IMockitoConfiguration {
 
     private Answer overriddenDefaultAnswer = null;
 
@@ -17,22 +18,22 @@ public class MockitoConfiguration extends DefaultMockitoConfiguration implements
 
     private boolean enableClassCache = true;
 
-    //for testing purposes, allow to override the configuration
+    // for testing purposes, allow to override the configuration
     public void overrideDefaultAnswer(Answer defaultAnswer) {
         this.overriddenDefaultAnswer = defaultAnswer;
     }
 
-    //for testing purposes, allow to override the configuration
+    // for testing purposes, allow to override the configuration
     public void overrideCleansStackTrace(boolean cleansStackTrace) {
         this.cleansStackTrace = cleansStackTrace;
     }
 
-    //for testing purposes, allow to override the annotation engine
+    // for testing purposes, allow to override the annotation engine
     public void overrideAnnotationEngine(AnnotationEngine engine) {
         this.overriddenEngine = engine;
     }
 
-    //for testing purposes, allow to override the annotation engine
+    // for testing purposes, allow to override the annotation engine
     public void overrideEnableClassCache(boolean enableClassCache) {
         this.enableClassCache = enableClassCache;
     }
@@ -63,5 +64,4 @@ public boolean cleansStackTrace() {
     public boolean enableClassCache() {
         return enableClassCache;
     }
-
 }
diff --git a/src/test/java/org/mockito/exceptions/base/MockitoAssertionErrorTest.java b/src/test/java/org/mockito/exceptions/base/MockitoAssertionErrorTest.java
index fc2ceaa679..d54e7409a2 100644
--- a/src/test/java/org/mockito/exceptions/base/MockitoAssertionErrorTest.java
+++ b/src/test/java/org/mockito/exceptions/base/MockitoAssertionErrorTest.java
@@ -29,7 +29,8 @@ public void shouldKeepUnfilteredStackTrace() {
     @Test
     public void should_prepend_message_to_original() {
         MockitoAssertionError original = new MockitoAssertionError("original message");
-        MockitoAssertionError errorWithPrependedMessage = new MockitoAssertionError(original, "new message");
+        MockitoAssertionError errorWithPrependedMessage =
+                new MockitoAssertionError(original, "new message");
         assertEquals("new message\noriginal message", errorWithPrependedMessage.getMessage());
     }
 }
diff --git a/src/test/java/org/mockito/exceptions/base/MockitoSerializationIssueTest.java b/src/test/java/org/mockito/exceptions/base/MockitoSerializationIssueTest.java
index 0aa961ee06..edd6af4c79 100644
--- a/src/test/java/org/mockito/exceptions/base/MockitoSerializationIssueTest.java
+++ b/src/test/java/org/mockito/exceptions/base/MockitoSerializationIssueTest.java
@@ -19,11 +19,14 @@ public void should_filter_out_test_class_from_stacktrace_when_clean_flag_is_true
         ConfigurationAccess.getConfig().overrideCleansStackTrace(true);
 
         // when
-        MockitoSerializationIssue issue = new MockitoSerializationIssue("msg", new Exception("cause"));
+        MockitoSerializationIssue issue =
+                new MockitoSerializationIssue("msg", new Exception("cause"));
 
         // then
-        assertThat(Arrays.toString(issue.getUnfilteredStackTrace())).contains("MockitoSerializationIssueTest");
-        assertThat(Arrays.toString(issue.getStackTrace())).doesNotContain("MockitoSerializationIssueTest");
+        assertThat(Arrays.toString(issue.getUnfilteredStackTrace()))
+                .contains("MockitoSerializationIssueTest");
+        assertThat(Arrays.toString(issue.getStackTrace()))
+                .doesNotContain("MockitoSerializationIssueTest");
     }
 
     @Test
@@ -32,10 +35,13 @@ public void should_keep_executing_class_in_stacktrace_when_clean_flag_is_false()
         ConfigurationAccess.getConfig().overrideCleansStackTrace(false);
 
         // when
-        MockitoSerializationIssue issue = new MockitoSerializationIssue("msg", new Exception("cause"));
+        MockitoSerializationIssue issue =
+                new MockitoSerializationIssue("msg", new Exception("cause"));
 
         // then
-        assertThat(Arrays.toString(issue.getUnfilteredStackTrace())).contains("MockitoSerializationIssueTest");
-        assertThat(Arrays.toString(issue.getStackTrace())).contains("MockitoSerializationIssueTest");
+        assertThat(Arrays.toString(issue.getUnfilteredStackTrace()))
+                .contains("MockitoSerializationIssueTest");
+        assertThat(Arrays.toString(issue.getStackTrace()))
+                .contains("MockitoSerializationIssueTest");
     }
 }
diff --git a/src/test/java/org/mockito/exceptions/base/StackTraceBuilder.java b/src/test/java/org/mockito/exceptions/base/StackTraceBuilder.java
index 32f0d75604..d7bf1869b0 100644
--- a/src/test/java/org/mockito/exceptions/base/StackTraceBuilder.java
+++ b/src/test/java/org/mockito/exceptions/base/StackTraceBuilder.java
@@ -11,7 +11,7 @@ public class StackTraceBuilder {
 
     private String[] methods;
 
-    public StackTraceBuilder methods(String ... methods) {
+    public StackTraceBuilder methods(String... methods) {
         this.methods = methods;
         return this;
     }
diff --git a/src/test/java/org/mockito/exceptions/base/TraceBuilder.java b/src/test/java/org/mockito/exceptions/base/TraceBuilder.java
index d0fd77457e..7763913b16 100644
--- a/src/test/java/org/mockito/exceptions/base/TraceBuilder.java
+++ b/src/test/java/org/mockito/exceptions/base/TraceBuilder.java
@@ -38,12 +38,12 @@ public StackTraceElement[] toTraceArray() {
         return toTraceList().toArray(new StackTraceElement[0]);
     }
 
-    public TraceBuilder classes(String ... classes) {
+    public TraceBuilder classes(String... classes) {
         this.classes = classes;
         return this;
     }
 
-    public TraceBuilder methods(String ... methods) {
+    public TraceBuilder methods(String... methods) {
         this.methods = methods;
         return this;
     }
diff --git a/src/test/java/org/mockito/exceptions/stacktrace/StackTraceCleanerTest.java b/src/test/java/org/mockito/exceptions/stacktrace/StackTraceCleanerTest.java
index 54a0ff35c2..832d6d7572 100644
--- a/src/test/java/org/mockito/exceptions/stacktrace/StackTraceCleanerTest.java
+++ b/src/test/java/org/mockito/exceptions/stacktrace/StackTraceCleanerTest.java
@@ -11,7 +11,7 @@
 
 public class StackTraceCleanerTest {
 
-    private DefaultStackTraceCleaner cleaner= new DefaultStackTraceCleaner();
+    private DefaultStackTraceCleaner cleaner = new DefaultStackTraceCleaner();
 
     @Test
     public void allow_or_disallow_mockito_mockito_objects_in_stacktrace() throws Exception {
@@ -34,11 +34,15 @@ public void allow_or_disallow_mockito_mockito_objects_in_stacktrace() throws Exc
     }
 
     private void assertAcceptedInStackTrace(String className) {
-        assertThat(cleaner.isIn(stackTraceElementWith(className))).describedAs("Must be accepted in stacktrace %s", className).isTrue();
+        assertThat(cleaner.isIn(stackTraceElementWith(className)))
+                .describedAs("Must be accepted in stacktrace %s", className)
+                .isTrue();
     }
 
     private void assertRejectedInStackTrace(String className) {
-        assertThat(cleaner.isIn(stackTraceElementWith(className))).describedAs("Must be rejected in stacktrace %s", className).isFalse();
+        assertThat(cleaner.isIn(stackTraceElementWith(className)))
+                .describedAs("Must be rejected in stacktrace %s", className)
+                .isFalse();
     }
 
     private StackTraceElement stackTraceElementWith(String className) {
diff --git a/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java b/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java
index 44acd4c9eb..dac34c07e5 100644
--- a/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java
+++ b/src/test/java/org/mockito/internal/AllInvocationsFinderTest.java
@@ -36,22 +36,22 @@ public void setup() {
 
     @Test
     public void no_interactions() throws Exception {
-        //expect
+        // expect
         assertTrue(find(asList(mockOne, mockTwo)).isEmpty());
         assertTrue(findStubbings(asList(mockOne, mockTwo)).isEmpty());
     }
 
     @Test
     public void provides_invocations_in_order() throws Exception {
-        //given
+        // given
         mockOne.simpleMethod(100);
         mockTwo.simpleMethod(200);
         mockOne.simpleMethod(300);
 
-        //when
+        // when
         List invocations = find(asList(mockOne, mockTwo));
 
-        //then
+        // then
         assertEquals(3, invocations.size());
         assertArgumentEquals(100, invocations.get(0));
         assertArgumentEquals(200, invocations.get(1));
@@ -60,28 +60,29 @@ public void provides_invocations_in_order() throws Exception {
 
     @Test
     public void deduplicates_interactions_from_the_same_mock() throws Exception {
-        //given
+        // given
         mockOne.simpleMethod(100);
 
-        //when
+        // when
         List invocations = find(asList(mockOne, mockOne, mockOne));
 
-        //then
+        // then
         assertEquals(1, invocations.size());
     }
 
     @Test
     public void provides_stubbings_in_order() throws Exception {
-        //given
-        mockOne.simpleMethod(50); //ignored, not a stubbing
+        // given
+        mockOne.simpleMethod(50); // ignored, not a stubbing
         when(mockOne.simpleMethod(100)).thenReturn("100");
         when(mockOne.simpleMethod(200)).thenReturn("200");
         when(mockTwo.simpleMethod(300)).thenReturn("300");
 
-        //when
-        List stubbings = new ArrayList(findStubbings(asList(mockOne, mockOne, mockTwo)));
+        // when
+        List stubbings =
+                new ArrayList(findStubbings(asList(mockOne, mockOne, mockTwo)));
 
-        //then
+        // then
         assertEquals(3, stubbings.size());
         assertArgumentEquals(100, stubbings.get(0).getInvocation());
         assertArgumentEquals(200, stubbings.get(1).getInvocation());
diff --git a/src/test/java/org/mockito/internal/InOrderImplTest.java b/src/test/java/org/mockito/internal/InOrderImplTest.java
index cb5d7ecb81..5224a4fb7b 100644
--- a/src/test/java/org/mockito/internal/InOrderImplTest.java
+++ b/src/test/java/org/mockito/internal/InOrderImplTest.java
@@ -23,15 +23,15 @@ public class InOrderImplTest extends TestBase {
 
     @Test
     public void shouldMarkVerifiedInOrder() throws Exception {
-        //given
+        // given
         InOrderImpl impl = new InOrderImpl(singletonList(mock));
         Invocation i = new InvocationBuilder().toInvocation();
         assertFalse(impl.isVerified(i));
 
-        //when
+        // when
         impl.markVerified(i);
 
-        //then
+        // then
         assertTrue(impl.isVerified(i));
     }
 }
diff --git a/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java b/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java
index 6e55814ebc..62d120d361 100644
--- a/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java
+++ b/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java
@@ -154,13 +154,15 @@ public void shouldCorrectStateAfterDetectingUnfinishedStubbing() {
         try {
             doThrow(new RuntimeException()).when(mock).oneArg(true);
             fail();
-        } catch (UnfinishedStubbingException e) {}
+        } catch (UnfinishedStubbingException e) {
+        }
 
         doThrow(new RuntimeException()).when(mock).oneArg(true);
         try {
             mock.oneArg(true);
             fail();
-        } catch (RuntimeException e) {}
+        } catch (RuntimeException e) {
+        }
     }
 
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
@@ -172,7 +174,8 @@ public void shouldCorrectStateAfterDetectingUnfinishedVerification() {
         try {
             verify(mock).simpleMethod();
             fail();
-        } catch (UnfinishedVerificationException e) {}
+        } catch (UnfinishedVerificationException e) {
+        }
 
         verify(mock).simpleMethod();
     }
@@ -257,7 +260,7 @@ private void detectsAndCleansUp(DetectsInvalidState detector, Class expected)
         } catch (Exception e) {
             assertEquals(expected, e.getClass());
         }
-        //Make sure state is cleaned up
+        // Make sure state is cleaned up
         new StateMaster().validate();
     }
 }
diff --git a/src/test/java/org/mockito/internal/configuration/ClassPathLoaderTest.java b/src/test/java/org/mockito/internal/configuration/ClassPathLoaderTest.java
index 035e108c2e..faf86d716f 100644
--- a/src/test/java/org/mockito/internal/configuration/ClassPathLoaderTest.java
+++ b/src/test/java/org/mockito/internal/configuration/ClassPathLoaderTest.java
@@ -17,10 +17,13 @@ public class ClassPathLoaderTest extends TestBase {
 
     @Test
     public void shouldReadConfigurationClassFromClassPath() {
-        ConfigurationAccess.getConfig().overrideDefaultAnswer(new Answer() {
-            public Object answer(InvocationOnMock invocation) {
-                return "foo";
-            }});
+        ConfigurationAccess.getConfig()
+                .overrideDefaultAnswer(
+                        new Answer() {
+                            public Object answer(InvocationOnMock invocation) {
+                                return "foo";
+                            }
+                        });
 
         IMethods mock = mock(IMethods.class);
         assertEquals("foo", mock.simpleMethod());
diff --git a/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java b/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java
index b8d0a5612a..79d4fedd21 100644
--- a/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java
+++ b/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java
@@ -20,28 +20,36 @@ public class GlobalConfigurationTest {
     @Test
     public void returns_mockito_configuration_annotation_engine_if_non_default() throws Exception {
         ConfigurationAccess.getConfig().overrideAnnotationEngine(new CustomAnnotationEngine());
-        assertThat(new GlobalConfiguration().getAnnotationEngine()).isInstanceOf(CustomAnnotationEngine.class);
-        assertThat(new GlobalConfiguration().tryGetPluginAnnotationEngine()).isInstanceOf(CustomAnnotationEngine.class);
+        assertThat(new GlobalConfiguration().getAnnotationEngine())
+                .isInstanceOf(CustomAnnotationEngine.class);
+        assertThat(new GlobalConfiguration().tryGetPluginAnnotationEngine())
+                .isInstanceOf(CustomAnnotationEngine.class);
     }
 
     @Test
-    public void returns_mockito_annotation_engine_of_Plugins_if_no_MockitoConfiguration() throws Throwable {
-        ClassLoader anotherWorld = ClassLoaders.isolatedClassLoader()
-                .withCurrentCodeSourceUrls()
-                .withCodeSourceUrlOf(Mockito.class, ByteBuddy.class, Objenesis.class)
-                .withPrivateCopyOf("org.mockito", "net.bytebuddy", "org.objenesis")
-                .withCodeSourceUrlOf(Assertions.class)
-                .withPrivateCopyOf("org.assertj")
-                .without("org.mockito.configuration.MockitoConfiguration")
-                .build();
+    public void returns_mockito_annotation_engine_of_Plugins_if_no_MockitoConfiguration()
+            throws Throwable {
+        ClassLoader anotherWorld =
+                ClassLoaders.isolatedClassLoader()
+                        .withCurrentCodeSourceUrls()
+                        .withCodeSourceUrlOf(Mockito.class, ByteBuddy.class, Objenesis.class)
+                        .withPrivateCopyOf("org.mockito", "net.bytebuddy", "org.objenesis")
+                        .withCodeSourceUrlOf(Assertions.class)
+                        .withPrivateCopyOf("org.assertj")
+                        .without("org.mockito.configuration.MockitoConfiguration")
+                        .build();
 
-        ClassLoaders.using(anotherWorld).execute(new Runnable() {
-            @Override
-            public void run() {
-                assertThat(new GlobalConfiguration().getAnnotationEngine()).isInstanceOf(Plugins.getAnnotationEngine().getClass());
-                assertThat(new GlobalConfiguration().tryGetPluginAnnotationEngine()).isInstanceOf(Plugins.getAnnotationEngine().getClass());
-            }
-        });
+        ClassLoaders.using(anotherWorld)
+                .execute(
+                        new Runnable() {
+                            @Override
+                            public void run() {
+                                assertThat(new GlobalConfiguration().getAnnotationEngine())
+                                        .isInstanceOf(Plugins.getAnnotationEngine().getClass());
+                                assertThat(new GlobalConfiguration().tryGetPluginAnnotationEngine())
+                                        .isInstanceOf(Plugins.getAnnotationEngine().getClass());
+                            }
+                        });
     }
 
     @After
@@ -50,6 +58,7 @@ public void reset_annotation_engine() {
     }
 
     private static class CustomAnnotationEngine implements AnnotationEngine {
-        @Override public void process(Class clazz, Object testInstance) { }
+        @Override
+        public void process(Class clazz, Object testInstance) {}
     }
 }
diff --git a/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java b/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
index 7a8b064f68..274db3beca 100644
--- a/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
+++ b/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
@@ -12,16 +12,13 @@
 import org.mockito.Spy;
 import org.mockito.junit.MockitoJUnitRunner;
 
-class I { }
+class I {}
 
 @RunWith(MockitoJUnitRunner.class)
 public class InjectingAnnotationEngineTest extends I {
-    @InjectMocks
-    Target target;
-    @Mock
-    Foo foo;
-    @Spy
-    Bar bar = new Bar();
+    @InjectMocks Target target;
+    @Mock Foo foo;
+    @Spy Bar bar = new Bar();
 
     /*
      If the test case has super classes, the @InjectMocks field has a field that not listed in the constructor argument
@@ -52,9 +49,7 @@ public Bar getBar() {
         }
     }
 
-    public static class Foo {
-    }
+    public static class Foo {}
 
-    public static class Bar {
-    }
+    public static class Bar {}
 }
diff --git a/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java b/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java
index 4bd16c3c23..83012b299d 100644
--- a/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java
+++ b/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java
@@ -48,31 +48,42 @@ public void should_not_allow_null_on_mocks() throws Exception {
         MockInjection.onField(field("withConstructor"), this).withMocks(null);
     }
 
-
     @Test
     public void can_try_constructor_injection() throws Exception {
-        MockInjection.onField(field("withConstructor"), this).withMocks(oneSetMock()).tryConstructorInjection().apply();
+        MockInjection.onField(field("withConstructor"), this)
+                .withMocks(oneSetMock())
+                .tryConstructorInjection()
+                .apply();
 
         assertThat(withConstructor.initializedWithConstructor).isEqualTo(true);
     }
 
     @Test
     public void should_not_fail_if_constructor_injection_is_not_possible() throws Exception {
-        MockInjection.onField(field("withoutConstructor"), this).withMocks(otherKindOfMocks()).tryConstructorInjection().apply();
+        MockInjection.onField(field("withoutConstructor"), this)
+                .withMocks(otherKindOfMocks())
+                .tryConstructorInjection()
+                .apply();
 
         assertThat(withoutConstructor).isNull();
     }
 
     @Test
     public void can_try_property_or_setter_injection() throws Exception {
-        MockInjection.onField(field("withoutConstructor"), this).withMocks(oneSetMock()).tryPropertyOrFieldInjection().apply();
+        MockInjection.onField(field("withoutConstructor"), this)
+                .withMocks(oneSetMock())
+                .tryPropertyOrFieldInjection()
+                .apply();
 
         assertThat(withoutConstructor.theSet).isNotNull();
     }
 
     @Test
     public void should_not_fail_if_property_or_field_injection_is_not_possible() throws Exception {
-        MockInjection.onField(field("withoutConstructor"), this).withMocks(otherKindOfMocks()).tryPropertyOrFieldInjection().apply();
+        MockInjection.onField(field("withoutConstructor"), this)
+                .withMocks(otherKindOfMocks())
+                .tryPropertyOrFieldInjection()
+                .apply();
 
         assertThat(withoutConstructor.theSet).isNull();
     }
@@ -89,9 +100,9 @@ private Field field(String field) throws NoSuchFieldException {
         return getClass().getDeclaredField(field);
     }
 
-
     public static class AnObjectWithConstructor {
         public boolean initializedWithConstructor = false;
+
         public AnObjectWithConstructor(Set strings) {
             initializedWithConstructor = true;
         }
diff --git a/src/test/java/org/mockito/internal/configuration/injection/SimpleArgumentResolverTest.java b/src/test/java/org/mockito/internal/configuration/injection/SimpleArgumentResolverTest.java
index 70f5b497f3..4b4da06728 100644
--- a/src/test/java/org/mockito/internal/configuration/injection/SimpleArgumentResolverTest.java
+++ b/src/test/java/org/mockito/internal/configuration/injection/SimpleArgumentResolverTest.java
@@ -17,9 +17,14 @@ public class SimpleArgumentResolverTest {
     @Test
     public void should_return_object_matching_given_types() throws Exception {
         ConstructorInjection.SimpleArgumentResolver resolver =
-                new ConstructorInjection.SimpleArgumentResolver(newSetOf(new HashSet(), new ByteArrayOutputStream(), new HashMap()));
+                new ConstructorInjection.SimpleArgumentResolver(
+                        newSetOf(
+                                new HashSet(),
+                                new ByteArrayOutputStream(),
+                                new HashMap()));
 
-        Object[] resolvedInstance = resolver.resolveTypeInstances(Set.class, Map.class, OutputStream.class);
+        Object[] resolvedInstance =
+                resolver.resolveTypeInstances(Set.class, Map.class, OutputStream.class);
 
         assertEquals(3, resolvedInstance.length);
         assertTrue(resolvedInstance[0] instanceof Set);
@@ -30,9 +35,11 @@ public void should_return_object_matching_given_types() throws Exception {
     @Test
     public void should_return_null_when_match_is_not_possible_on_given_types() throws Exception {
         ConstructorInjection.SimpleArgumentResolver resolver =
-                new ConstructorInjection.SimpleArgumentResolver(newSetOf(new HashSet(), new ByteArrayOutputStream()));
+                new ConstructorInjection.SimpleArgumentResolver(
+                        newSetOf(new HashSet(), new ByteArrayOutputStream()));
 
-        Object[] resolvedInstance = resolver.resolveTypeInstances(Set.class, Map.class, OutputStream.class);
+        Object[] resolvedInstance =
+                resolver.resolveTypeInstances(Set.class, Map.class, OutputStream.class);
 
         assertEquals(3, resolvedInstance.length);
         assertTrue(resolvedInstance[0] instanceof Set);
@@ -43,9 +50,11 @@ public void should_return_null_when_match_is_not_possible_on_given_types() throw
     @Test
     public void should_return_null_when_types_are_primitives() throws Exception {
         ConstructorInjection.SimpleArgumentResolver resolver =
-                new ConstructorInjection.SimpleArgumentResolver(newSetOf(new HashMap(), new TreeSet()));
+                new ConstructorInjection.SimpleArgumentResolver(
+                        newSetOf(new HashMap(), new TreeSet()));
 
-        Object[] resolvedInstance = resolver.resolveTypeInstances(Set.class, Map.class, Boolean.class);
+        Object[] resolvedInstance =
+                resolver.resolveTypeInstances(Set.class, Map.class, Boolean.class);
 
         assertEquals(3, resolvedInstance.length);
         assertTrue(resolvedInstance[0] instanceof Set);
@@ -56,6 +65,4 @@ public void should_return_null_when_types_are_primitives() throws Exception {
     private Set newSetOf(Object... objects) {
         return new HashSet(Arrays.asList(objects));
     }
-
-
 }
diff --git a/src/test/java/org/mockito/internal/configuration/plugins/DefaultMockitoPluginsTest.java b/src/test/java/org/mockito/internal/configuration/plugins/DefaultMockitoPluginsTest.java
index 1324cc8289..3d3957c700 100644
--- a/src/test/java/org/mockito/internal/configuration/plugins/DefaultMockitoPluginsTest.java
+++ b/src/test/java/org/mockito/internal/configuration/plugins/DefaultMockitoPluginsTest.java
@@ -23,12 +23,16 @@ public class DefaultMockitoPluginsTest extends TestBase {
 
     @Test
     public void provides_plugins() throws Exception {
-        assertEquals("org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker",
-            plugins.getDefaultPluginClass(INLINE_ALIAS));
+        assertEquals(
+                "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker",
+                plugins.getDefaultPluginClass(INLINE_ALIAS));
         assertEquals(InlineByteBuddyMockMaker.class, plugins.getInlineMockMaker().getClass());
-        assertEquals(ByteBuddyMockMaker.class, plugins.getDefaultPlugin(MockMaker.class).getClass());
+        assertEquals(
+                ByteBuddyMockMaker.class, plugins.getDefaultPlugin(MockMaker.class).getClass());
         assertNotNull(plugins.getDefaultPlugin(InstantiatorProvider.class));
         assertNotNull(plugins.getDefaultPlugin(InstantiatorProvider2.class));
-        assertEquals(ConsoleMockitoLogger.class, plugins.getDefaultPlugin(MockitoLogger.class).getClass());
+        assertEquals(
+                ConsoleMockitoLogger.class,
+                plugins.getDefaultPlugin(MockitoLogger.class).getClass());
     }
 }
diff --git a/src/test/java/org/mockito/internal/configuration/plugins/PluginFileReaderTest.java b/src/test/java/org/mockito/internal/configuration/plugins/PluginFileReaderTest.java
index 40677be6a8..e33e3027b4 100644
--- a/src/test/java/org/mockito/internal/configuration/plugins/PluginFileReaderTest.java
+++ b/src/test/java/org/mockito/internal/configuration/plugins/PluginFileReaderTest.java
@@ -20,12 +20,12 @@ public class PluginFileReaderTest extends TestBase {
 
     @Test
     public void no_class_in_resource() throws IOException {
-        //no class
+        // no class
         assertNull(reader.readPluginClass(impl("")));
         assertNull(reader.readPluginClass(impl("  ")));
         assertNull(reader.readPluginClass(impl(" \n ")));
 
-        //commented out
+        // commented out
         assertNull(reader.readPluginClass(impl("#foo")));
         assertNull(reader.readPluginClass(impl("  # foo  ")));
         assertNull(reader.readPluginClass(impl("  # # # java.langString # ")));
@@ -41,7 +41,8 @@ public void reads_class_name() throws IOException {
         assertEquals("java.lang.String", reader.readPluginClass(impl("java.lang.String")));
         assertEquals("x", reader.readPluginClass(impl("x")));
         assertEquals("x y z", reader.readPluginClass(impl(" x y z ")));
-        assertEquals("foo.Foo", reader.readPluginClass(impl(" #my class\n  foo.Foo \n #other class ")));
+        assertEquals(
+                "foo.Foo", reader.readPluginClass(impl(" #my class\n  foo.Foo \n #other class ")));
         assertEquals("foo.Foo", reader.readPluginClass(impl("foo.Foo  # cool class")));
     }
 }
diff --git a/src/test/java/org/mockito/internal/configuration/plugins/PluginFinderTest.java b/src/test/java/org/mockito/internal/configuration/plugins/PluginFinderTest.java
index b922dddd57..97535dfc6d 100644
--- a/src/test/java/org/mockito/internal/configuration/plugins/PluginFinderTest.java
+++ b/src/test/java/org/mockito/internal/configuration/plugins/PluginFinderTest.java
@@ -26,92 +26,105 @@
 
 public class PluginFinderTest extends TestBase {
 
-    @Mock
-    PluginSwitch switcher;
+    @Mock PluginSwitch switcher;
     @InjectMocks PluginFinder finder;
     public @Rule TemporaryFolder tmp = new TemporaryFolder();
 
-    @Test public void empty_resources() {
+    @Test
+    public void empty_resources() {
         assertNull(finder.findPluginClass(Collections.emptyList()));
     }
 
-    @Test public void no_valid_impl() throws Exception {
+    @Test
+    public void no_valid_impl() throws Exception {
         File f = tmp.newFile();
 
-        //when
+        // when
         IOUtil.writeText("  \n  ", f);
 
-        //then
+        // then
         assertNull(finder.findPluginClass(asList(f.toURI().toURL())));
     }
 
-    @Test public void single_implementation() throws Exception {
+    @Test
+    public void single_implementation() throws Exception {
         File f = tmp.newFile();
         when(switcher.isEnabled("foo.Foo")).thenReturn(true);
 
-        //when
+        // when
         IOUtil.writeText("  foo.Foo  ", f);
 
-        //then
+        // then
         assertEquals("foo.Foo", finder.findPluginClass(asList(f.toURI().toURL())));
     }
 
-    @Test public void single_implementation_disabled() throws Exception {
+    @Test
+    public void single_implementation_disabled() throws Exception {
         File f = tmp.newFile();
         when(switcher.isEnabled("foo.Foo")).thenReturn(false);
 
-        //when
+        // when
         IOUtil.writeText("  foo.Foo  ", f);
 
-        //then
+        // then
         assertEquals(null, finder.findPluginClass(asList(f.toURI().toURL())));
     }
 
-    @Test public void multiple_implementations_only_one_enabled() throws Exception {
-        File f1 = tmp.newFile(); File f2 = tmp.newFile();
+    @Test
+    public void multiple_implementations_only_one_enabled() throws Exception {
+        File f1 = tmp.newFile();
+        File f2 = tmp.newFile();
 
         when(switcher.isEnabled("Bar")).thenReturn(true);
 
-        //when
-        IOUtil.writeText("Foo", f1); IOUtil.writeText("Bar", f2);
+        // when
+        IOUtil.writeText("Foo", f1);
+        IOUtil.writeText("Bar", f2);
 
-        //then
+        // then
         assertEquals("Bar", finder.findPluginClass(asList(f1.toURI().toURL(), f2.toURI().toURL())));
     }
 
-    @Test public void multiple_implementations_only_one_useful() throws Exception {
-        File f1 = tmp.newFile(); File f2 = tmp.newFile();
+    @Test
+    public void multiple_implementations_only_one_useful() throws Exception {
+        File f1 = tmp.newFile();
+        File f2 = tmp.newFile();
 
         when(switcher.isEnabled(anyString())).thenReturn(true);
 
-        //when
-        IOUtil.writeText("   ", f1); IOUtil.writeText("X", f2);
+        // when
+        IOUtil.writeText("   ", f1);
+        IOUtil.writeText("X", f2);
 
-        //then
+        // then
         assertEquals("X", finder.findPluginClass(asList(f1.toURI().toURL(), f2.toURI().toURL())));
     }
 
-    @Test public void multiple_empty_implementations() throws Exception {
-        File f1 = tmp.newFile(); File f2 = tmp.newFile();
+    @Test
+    public void multiple_empty_implementations() throws Exception {
+        File f1 = tmp.newFile();
+        File f2 = tmp.newFile();
 
         when(switcher.isEnabled(anyString())).thenReturn(true);
 
-        //when
-        IOUtil.writeText("   ", f1); IOUtil.writeText("\n", f2);
+        // when
+        IOUtil.writeText("   ", f1);
+        IOUtil.writeText("\n", f2);
 
-        //then
+        // then
         assertEquals(null, finder.findPluginClass(asList(f1.toURI().toURL(), f2.toURI().toURL())));
     }
 
-    @Test public void problems_loading_impl() throws Exception {
+    @Test
+    public void problems_loading_impl() throws Exception {
         when(switcher.isEnabled(anyString())).thenThrow(new RuntimeException("Boo!"));
 
         try {
-            //when
+            // when
             finder.findPluginClass(asList(new File("xxx").toURI().toURL()));
-            //then
+            // then
             fail();
-        } catch(Exception e) {
+        } catch (Exception e) {
             assertThat(e).hasMessageContaining("xxx");
             e.getCause().getMessage().equals("Boo!");
         }
diff --git a/src/test/java/org/mockito/internal/configuration/plugins/PluginLoaderTest.java b/src/test/java/org/mockito/internal/configuration/plugins/PluginLoaderTest.java
index cae06b40c6..543af6821d 100644
--- a/src/test/java/org/mockito/internal/configuration/plugins/PluginLoaderTest.java
+++ b/src/test/java/org/mockito/internal/configuration/plugins/PluginLoaderTest.java
@@ -31,10 +31,10 @@ public class PluginLoaderTest {
     public void loads_plugin() {
         when(initializer.loadImpl(FooPlugin.class)).thenReturn(new FooPlugin());
 
-        //when
+        // when
         FooPlugin plugin = loader.loadPlugin(FooPlugin.class);
 
-        //then
+        // then
         assertNotNull(plugin);
     }
 
@@ -44,10 +44,10 @@ public void loads_alternative_plugin() {
         BarPlugin expected = new BarPlugin();
         willReturn(expected).given(initializer).loadImpl(BarPlugin.class);
 
-        //when
+        // when
         Object plugin = loader.loadPlugin(FooPlugin.class, BarPlugin.class);
 
-        //then
+        // then
         assertSame(plugin, expected);
     }
 
@@ -58,10 +58,10 @@ public void loads_default_plugin() {
         FooPlugin expected = new FooPlugin();
         willReturn(expected).given(plugins).getDefaultPlugin(FooPlugin.class);
 
-        //when
+        // when
         Object plugin = loader.loadPlugin(FooPlugin.class, BarPlugin.class);
 
-        //then
+        // then
         assertSame(plugin, expected);
     }
 
@@ -70,21 +70,26 @@ public void fails_to_load_plugin() {
         RuntimeException cause = new RuntimeException("Boo!");
         when(initializer.loadImpl(Foo.class)).thenThrow(cause);
 
-        //when
+        // when
         final Foo plugin = loader.loadPlugin(Foo.class);
 
-        //then
-        Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            @Override
-            public void call() throws Throwable {
-                plugin.toString(); //call any method on the plugin
-            }
-        }).isInstanceOf(IllegalStateException.class)
-            .hasMessage("Could not initialize plugin: interface org.mockito.internal.configuration.plugins.PluginLoaderTest$Foo (alternate: null)")
-            .hasCause(cause);
+        // then
+        Assertions.assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            @Override
+                            public void call() throws Throwable {
+                                plugin.toString(); // call any method on the plugin
+                            }
+                        })
+                .isInstanceOf(IllegalStateException.class)
+                .hasMessage(
+                        "Could not initialize plugin: interface org.mockito.internal.configuration.plugins.PluginLoaderTest$Foo (alternate: null)")
+                .hasCause(cause);
     }
 
     static class FooPlugin {}
+
     static class BarPlugin {}
+
     static interface Foo {}
 }
diff --git a/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java b/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
index fe0c20188f..2efbc50653 100644
--- a/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
+++ b/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
@@ -31,31 +31,31 @@ public class MockSettingsImplTest extends TestBase {
     @Mock private InvocationListener invocationListener;
     @Mock private StubbingLookupListener stubbingLookupListener;
 
-    @Test(expected=MockitoException.class)
+    @Test(expected = MockitoException.class)
     @SuppressWarnings("unchecked")
     public void shouldNotAllowSettingNullInterface() {
         mockSettingsImpl.extraInterfaces(List.class, null);
     }
 
-    @Test(expected=MockitoException.class)
+    @Test(expected = MockitoException.class)
     @SuppressWarnings("unchecked")
     public void shouldNotAllowNonInterfaces() {
         mockSettingsImpl.extraInterfaces(List.class, LinkedList.class);
     }
 
-    @Test(expected=MockitoException.class)
+    @Test(expected = MockitoException.class)
     @SuppressWarnings("unchecked")
     public void shouldNotAllowUsingTheSameInterfaceAsExtra() {
         mockSettingsImpl.extraInterfaces(List.class, LinkedList.class);
     }
 
-    @Test(expected=MockitoException.class)
+    @Test(expected = MockitoException.class)
     @SuppressWarnings("unchecked")
     public void shouldNotAllowEmptyExtraInterfaces() {
         mockSettingsImpl.extraInterfaces();
     }
 
-    @Test(expected=MockitoException.class)
+    @Test(expected = MockitoException.class)
     @SuppressWarnings("unchecked")
     public void shouldNotAllowNullArrayOfExtraInterfaces() {
         mockSettingsImpl.extraInterfaces((Class[]) null);
@@ -64,10 +64,10 @@ public void shouldNotAllowNullArrayOfExtraInterfaces() {
     @Test
     @SuppressWarnings("unchecked")
     public void shouldAllowMultipleInterfaces() {
-        //when
+        // when
         mockSettingsImpl.extraInterfaces(List.class, Set.class);
 
-        //then
+        // then
         assertEquals(2, mockSettingsImpl.getExtraInterfaces().size());
         assertTrue(mockSettingsImpl.getExtraInterfaces().contains(List.class));
         assertTrue(mockSettingsImpl.getExtraInterfaces().contains(Set.class));
@@ -75,137 +75,169 @@ public void shouldAllowMultipleInterfaces() {
 
     @Test
     public void shouldSetMockToBeSerializable() throws Exception {
-        //when
+        // when
         mockSettingsImpl.serializable();
 
-        //then
+        // then
         assertTrue(mockSettingsImpl.isSerializable());
     }
 
     @Test
     public void shouldKnowIfIsSerializable() throws Exception {
-        //given
+        // given
         assertFalse(mockSettingsImpl.isSerializable());
 
-        //when
+        // when
         mockSettingsImpl.serializable();
 
-        //then
+        // then
         assertTrue(mockSettingsImpl.isSerializable());
     }
 
     @Test
     public void shouldAddVerboseLoggingListener() {
-        //given
+        // given
         assertFalse(mockSettingsImpl.hasInvocationListeners());
 
-        //when
+        // when
         mockSettingsImpl.verboseLogging();
 
-        //then
-        assertThat(mockSettingsImpl.getInvocationListeners()).extracting("class").contains(VerboseMockInvocationLogger.class);
+        // then
+        assertThat(mockSettingsImpl.getInvocationListeners())
+                .extracting("class")
+                .contains(VerboseMockInvocationLogger.class);
     }
 
     @Test
     public void shouldAddVerboseLoggingListenerOnlyOnce() {
-        //given
+        // given
         assertFalse(mockSettingsImpl.hasInvocationListeners());
 
-        //when
+        // when
         mockSettingsImpl.verboseLogging().verboseLogging();
 
-        //then
+        // then
         Assertions.assertThat(mockSettingsImpl.getInvocationListeners()).hasSize(1);
     }
 
     @Test
     @SuppressWarnings("unchecked")
     public void shouldAddInvocationListener() {
-        //given
+        // given
         assertFalse(mockSettingsImpl.hasInvocationListeners());
 
-        //when
+        // when
         mockSettingsImpl.invocationListeners(invocationListener);
 
-        //then
-        Assertions.assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener);
+        // then
+        Assertions.assertThat(mockSettingsImpl.getInvocationListeners())
+                .contains(invocationListener);
     }
 
     @Test
     @SuppressWarnings("unchecked")
     public void canAddDuplicateInvocationListeners_ItsNotOurBusinessThere() {
-        //given
+        // given
         assertFalse(mockSettingsImpl.hasInvocationListeners());
 
-        //when
-        mockSettingsImpl.invocationListeners(invocationListener, invocationListener).invocationListeners(invocationListener);
+        // when
+        mockSettingsImpl
+                .invocationListeners(invocationListener, invocationListener)
+                .invocationListeners(invocationListener);
 
-        //then
-        Assertions.assertThat(mockSettingsImpl.getInvocationListeners()).containsSequence(invocationListener, invocationListener, invocationListener);
+        // then
+        Assertions.assertThat(mockSettingsImpl.getInvocationListeners())
+                .containsSequence(invocationListener, invocationListener, invocationListener);
     }
 
     @Test
     public void validates_listeners() {
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.addListeners(new Object[] {}, new LinkedList(), "myListeners");
-            }
-        }).hasMessageContaining("myListeners() requires at least one listener");
-
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.addListeners(null, new LinkedList(), "myListeners");
-            }
-        }).hasMessageContaining("myListeners() does not accept null vararg array");
-
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.addListeners(new Object[] {null}, new LinkedList(), "myListeners");
-            }
-        }).hasMessageContaining("myListeners() does not accept null listeners");
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.addListeners(
+                                        new Object[] {}, new LinkedList(), "myListeners");
+                            }
+                        })
+                .hasMessageContaining("myListeners() requires at least one listener");
+
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.addListeners(
+                                        null, new LinkedList(), "myListeners");
+                            }
+                        })
+                .hasMessageContaining("myListeners() does not accept null vararg array");
+
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.addListeners(
+                                        new Object[] {null},
+                                        new LinkedList(),
+                                        "myListeners");
+                            }
+                        })
+                .hasMessageContaining("myListeners() does not accept null listeners");
     }
 
-
     @Test
     public void validates_stubbing_lookup_listeners() {
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.stubbingLookupListeners(new StubbingLookupListener[] {});
-            }
-        }).hasMessageContaining("stubbingLookupListeners() requires at least one listener");
-
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.stubbingLookupListeners(null);
-            }
-        }).hasMessageContaining("stubbingLookupListeners() does not accept null vararg array");
-
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.stubbingLookupListeners(new StubbingLookupListener[] {null});
-            }
-        }).hasMessageContaining("stubbingLookupListeners() does not accept null listeners");
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.stubbingLookupListeners(
+                                        new StubbingLookupListener[] {});
+                            }
+                        })
+                .hasMessageContaining("stubbingLookupListeners() requires at least one listener");
+
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.stubbingLookupListeners(null);
+                            }
+                        })
+                .hasMessageContaining(
+                        "stubbingLookupListeners() does not accept null vararg array");
+
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.stubbingLookupListeners(
+                                        new StubbingLookupListener[] {null});
+                            }
+                        })
+                .hasMessageContaining("stubbingLookupListeners() does not accept null listeners");
     }
 
     @Test
     public void validates_invocation_listeners() {
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.invocationListeners(new InvocationListener[] {});
-            }
-        }).hasMessageContaining("invocationListeners() requires at least one listener");
-
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.invocationListeners(null);
-            }
-        }).hasMessageContaining("invocationListeners() does not accept null vararg array");
-
-        assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                mockSettingsImpl.invocationListeners(new InvocationListener[] {null});
-            }
-        }).hasMessageContaining("invocationListeners() does not accept null listeners");
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.invocationListeners(new InvocationListener[] {});
+                            }
+                        })
+                .hasMessageContaining("invocationListeners() requires at least one listener");
+
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.invocationListeners(null);
+                            }
+                        })
+                .hasMessageContaining("invocationListeners() does not accept null vararg array");
+
+        assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                mockSettingsImpl.invocationListeners(
+                                        new InvocationListener[] {null});
+                            }
+                        })
+                .hasMessageContaining("invocationListeners() does not accept null listeners");
     }
 
     @Test
@@ -216,27 +248,28 @@ public void addListeners_has_empty_listeners_by_default() {
 
     @Test
     public void addListeners_shouldAddMockObjectListeners() {
-        //when
+        // when
         mockSettingsImpl.invocationListeners(invocationListener);
         mockSettingsImpl.stubbingLookupListeners(stubbingLookupListener);
 
-        //then
+        // then
         assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener);
         assertThat(mockSettingsImpl.getStubbingLookupListeners()).contains(stubbingLookupListener);
     }
 
     @Test
     public void addListeners_canAddDuplicateMockObjectListeners_ItsNotOurBusinessThere() {
-        //when
-        mockSettingsImpl.stubbingLookupListeners(stubbingLookupListener)
-                        .stubbingLookupListeners(stubbingLookupListener)
-                        .invocationListeners(invocationListener)
-                        .invocationListeners(invocationListener);
-
-        //then
+        // when
+        mockSettingsImpl
+                .stubbingLookupListeners(stubbingLookupListener)
+                .stubbingLookupListeners(stubbingLookupListener)
+                .invocationListeners(invocationListener)
+                .invocationListeners(invocationListener);
+
+        // then
         assertThat(mockSettingsImpl.getInvocationListeners())
-            .containsSequence(invocationListener, invocationListener);
+                .containsSequence(invocationListener, invocationListener);
         assertThat(mockSettingsImpl.getStubbingLookupListeners())
-            .containsSequence(stubbingLookupListener, stubbingLookupListener);
+                .containsSequence(stubbingLookupListener, stubbingLookupListener);
     }
 }
diff --git a/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java b/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java
index a50a45b913..f5b807a1ce 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java
@@ -40,16 +40,17 @@ public AbstractByteBuddyMockMakerTest(MM mockMaker) {
 
     @Test
     public void should_create_mock_from_interface() throws Exception {
-        SomeInterface proxy = mockMaker.createMock(settingsFor(SomeInterface.class), dummyHandler());
+        SomeInterface proxy =
+                mockMaker.createMock(settingsFor(SomeInterface.class), dummyHandler());
 
         Class superClass = proxy.getClass().getSuperclass();
         assertThat(superClass).isEqualTo(Object.class);
     }
 
-
     @Test
     public void should_create_mock_from_class() throws Exception {
-        ClassWithoutConstructor proxy = mockMaker.createMock(settingsFor(ClassWithoutConstructor.class), dummyHandler());
+        ClassWithoutConstructor proxy =
+                mockMaker.createMock(settingsFor(ClassWithoutConstructor.class), dummyHandler());
 
         Class superClass = mockTypeOf(proxy.getClass());
         assertThat(superClass).isEqualTo(ClassWithoutConstructor.class);
@@ -60,9 +61,11 @@ public void should_create_mock_from_class_even_when_constructor_is_dodgy() throw
         try {
             new ClassWithDodgyConstructor();
             fail();
-        } catch (Exception expected) {}
+        } catch (Exception expected) {
+        }
 
-        ClassWithDodgyConstructor mock = mockMaker.createMock(settingsFor(ClassWithDodgyConstructor.class), dummyHandler());
+        ClassWithDodgyConstructor mock =
+                mockMaker.createMock(settingsFor(ClassWithDodgyConstructor.class), dummyHandler());
         assertThat(mock).isNotNull();
     }
 
@@ -74,26 +77,31 @@ public void should_mocks_have_different_interceptors() throws Exception {
         MockHandler handlerOne = mockMaker.getHandler(mockOne);
         MockHandler handlerTwo = mockMaker.getHandler(mockTwo);
 
-
         assertThat(handlerOne).isNotSameAs(handlerTwo);
     }
 
     @Test
     public void should_use_ancillary_Types() {
-        SomeClass mock = mockMaker.createMock(settingsFor(SomeClass.class, SomeInterface.class), dummyHandler());
+        SomeClass mock =
+                mockMaker.createMock(
+                        settingsFor(SomeClass.class, SomeInterface.class), dummyHandler());
 
         assertThat(mock).isInstanceOf(SomeInterface.class);
     }
 
     @Test
     public void should_create_class_by_constructor() {
-        OtherClass mock = mockMaker.createMock(settingsWithConstructorFor(OtherClass.class), dummyHandler());
+        OtherClass mock =
+                mockMaker.createMock(settingsWithConstructorFor(OtherClass.class), dummyHandler());
         assertThat(mock).isNotNull();
     }
 
     @Test
     public void should_allow_serialization() throws Exception {
-        SerializableClass proxy = mockMaker.createMock(serializableSettingsFor(SerializableClass.class, SerializableMode.BASIC), dummyHandler());
+        SerializableClass proxy =
+                mockMaker.createMock(
+                        serializableSettingsFor(SerializableClass.class, SerializableMode.BASIC),
+                        dummyHandler());
 
         SerializableClass serialized = SimpleSerializationUtil.serializeAndBack(proxy);
         assertThat(serialized).isNotNull();
@@ -106,15 +114,19 @@ public void should_allow_serialization() throws Exception {
 
     @Test
     public void should_create_mock_from_class_with_super_call_to_final_method() throws Exception {
-        MockCreationSettings settings = settingsWithSuperCall(CallingSuperMethodClass.class);
-        SampleClass proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        MockCreationSettings settings =
+                settingsWithSuperCall(CallingSuperMethodClass.class);
+        SampleClass proxy =
+                mockMaker.createMock(
+                        settings, new MockHandlerImpl(settings));
         assertThat(proxy.foo()).isEqualTo("foo");
     }
 
     @Test
     public void should_reset_mock_and_set_new_handler() throws Throwable {
         MockCreationSettings settings = settingsWithSuperCall(SampleClass.class);
-        SampleClass proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        SampleClass proxy =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
 
         MockHandler handler = new MockHandlerImpl(settings);
         mockMaker.resetMock(proxy, handler, settings);
@@ -122,8 +134,11 @@ public void should_reset_mock_and_set_new_handler() throws Throwable {
     }
 
     class SomeClass {}
+
     interface SomeInterface {}
+
     static class OtherClass {}
+
     static class SerializableClass implements Serializable {}
 
     private class ClassWithoutConstructor {}
@@ -137,16 +152,17 @@ public ClassWithDodgyConstructor() {
     @Test
     public void instantiate_fine_when_objenesis_on_the_classpath() throws Exception {
         // given
-        ClassLoader classpath_with_objenesis = ClassLoaders.excludingClassLoader()
-                .withCodeSourceUrlOf(Mockito.class, ByteBuddy.class, ObjenesisStd.class)
-                .withCodeSourceUrlOf(coverageTool())
-                .build();
-
-        Class mock_maker_class_loaded_fine_until = Class.forName(
-                "org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker",
-                true,
-                classpath_with_objenesis
-        );
+        ClassLoader classpath_with_objenesis =
+                ClassLoaders.excludingClassLoader()
+                        .withCodeSourceUrlOf(Mockito.class, ByteBuddy.class, ObjenesisStd.class)
+                        .withCodeSourceUrlOf(coverageTool())
+                        .build();
+
+        Class mock_maker_class_loaded_fine_until =
+                Class.forName(
+                        "org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker",
+                        true,
+                        classpath_with_objenesis);
 
         // when
         mock_maker_class_loaded_fine_until.newInstance();
@@ -154,14 +170,16 @@ public void instantiate_fine_when_objenesis_on_the_classpath() throws Exception
         // then everything went fine
     }
 
-    private static  MockCreationSettings settingsFor(Class type, Class... extraInterfaces) {
+    private static  MockCreationSettings settingsFor(
+            Class type, Class... extraInterfaces) {
         MockSettingsImpl mockSettings = new MockSettingsImpl();
         mockSettings.setTypeToMock(type);
-        if(extraInterfaces.length > 0) mockSettings.extraInterfaces(extraInterfaces);
+        if (extraInterfaces.length > 0) mockSettings.extraInterfaces(extraInterfaces);
         return mockSettings;
     }
 
-    private static  MockCreationSettings serializableSettingsFor(Class type, SerializableMode serializableMode) {
+    private static  MockCreationSettings serializableSettingsFor(
+            Class type, SerializableMode serializableMode) {
         MockSettingsImpl mockSettings = new MockSettingsImpl();
         mockSettings.serializable(serializableMode);
         mockSettings.setTypeToMock(type);
@@ -186,10 +204,19 @@ protected static MockHandler dummyHandler() {
     }
 
     private static class DummyMockHandler implements MockHandler {
-        public Object handle(Invocation invocation) throws Throwable { return null; }
-        public MockCreationSettings getMockSettings() { return null; }
-        public InvocationContainer getInvocationContainer() { return null; }
-        public void setAnswersForStubbing(List> list) { }
+        public Object handle(Invocation invocation) throws Throwable {
+            return null;
+        }
+
+        public MockCreationSettings getMockSettings() {
+            return null;
+        }
+
+        public InvocationContainer getInvocationContainer() {
+            return null;
+        }
+
+        public void setAnswersForStubbing(List> list) {}
     }
 
     private static class SampleClass {
diff --git a/src/test/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java b/src/test/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java
index 8dfc4d5122..f4891a762f 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMakerTest.java
@@ -15,11 +15,9 @@
 
 public class ByteBuddyMockMakerTest extends TestBase {
 
-    @InjectMocks
-    private ByteBuddyMockMaker mockMaker = new ByteBuddyMockMaker();
+    @InjectMocks private ByteBuddyMockMaker mockMaker = new ByteBuddyMockMaker();
 
-    @Mock
-    private ClassCreatingMockMaker delegate;
+    @Mock private ClassCreatingMockMaker delegate;
 
     @Test
     public void should_delegate_call() {
diff --git a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
index 2620cca7f2..8ec5318748 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
@@ -37,7 +37,8 @@
 import org.mockito.mock.SerializableMode;
 import org.mockito.plugins.MockMaker;
 
-public class InlineByteBuddyMockMakerTest extends AbstractByteBuddyMockMakerTest {
+public class InlineByteBuddyMockMakerTest
+        extends AbstractByteBuddyMockMakerTest {
 
     public InlineByteBuddyMockMakerTest() {
         super(new InlineByteBuddyMockMaker());
@@ -51,7 +52,8 @@ protected Class mockTypeOf(Class type) {
     @Test
     public void should_create_mock_from_final_class() throws Exception {
         MockCreationSettings settings = settingsFor(FinalClass.class);
-        FinalClass proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        FinalClass proxy =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
         assertThat(proxy.foo()).isEqualTo("bar");
     }
 
@@ -64,16 +66,21 @@ public void should_create_mock_from_final_class_in_the_JDK() throws Exception {
 
     @Test
     public void should_create_mock_from_abstract_class_with_final_method() throws Exception {
-        MockCreationSettings settings = settingsFor(FinalMethodAbstractType.class);
-        FinalMethodAbstractType proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        MockCreationSettings settings =
+                settingsFor(FinalMethodAbstractType.class);
+        FinalMethodAbstractType proxy =
+                mockMaker.createMock(
+                        settings, new MockHandlerImpl(settings));
         assertThat(proxy.foo()).isEqualTo("bar");
         assertThat(proxy.bar()).isEqualTo("bar");
     }
 
     @Test
     public void should_create_mock_from_final_class_with_interface_methods() throws Exception {
-        MockCreationSettings settings = settingsFor(FinalMethod.class, SampleInterface.class);
-        FinalMethod proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        MockCreationSettings settings =
+                settingsFor(FinalMethod.class, SampleInterface.class);
+        FinalMethod proxy =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
         assertThat(proxy.foo()).isEqualTo("bar");
         assertThat(((SampleInterface) proxy).bar()).isEqualTo("bar");
     }
@@ -81,7 +88,8 @@ public void should_create_mock_from_final_class_with_interface_methods() throws
     @Test
     public void should_detect_non_overridden_generic_method_of_supertype() throws Exception {
         MockCreationSettings settings = settingsFor(GenericSubClass.class);
-        GenericSubClass proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        GenericSubClass proxy =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
         assertThat(proxy.value()).isEqualTo("bar");
     }
 
@@ -126,10 +134,12 @@ public void should_create_mock_from_enum() throws Exception {
     }
 
     @Test
-    public void should_fail_at_creating_a_mock_of_a_final_class_with_explicit_serialization() throws Exception {
-        MockCreationSettings settings = new CreationSettings()
-                .setTypeToMock(FinalClass.class)
-                .setSerializableMode(SerializableMode.BASIC);
+    public void should_fail_at_creating_a_mock_of_a_final_class_with_explicit_serialization()
+            throws Exception {
+        MockCreationSettings settings =
+                new CreationSettings()
+                        .setTypeToMock(FinalClass.class)
+                        .setSerializableMode(SerializableMode.BASIC);
 
         try {
             mockMaker.createMock(settings, new MockHandlerImpl(settings));
@@ -143,10 +153,12 @@ public void should_fail_at_creating_a_mock_of_a_final_class_with_explicit_serial
     }
 
     @Test
-    public void should_fail_at_creating_a_mock_of_a_final_class_with_extra_interfaces() throws Exception {
-        MockCreationSettings settings = new CreationSettings()
-                .setTypeToMock(FinalClass.class)
-                .setExtraInterfaces(Sets.>newSet(List.class));
+    public void should_fail_at_creating_a_mock_of_a_final_class_with_extra_interfaces()
+            throws Exception {
+        MockCreationSettings settings =
+                new CreationSettings()
+                        .setTypeToMock(FinalClass.class)
+                        .setExtraInterfaces(Sets.>newSet(List.class));
 
         try {
             mockMaker.createMock(settings, new MockHandlerImpl(settings));
@@ -181,48 +193,57 @@ public void should_mock_interface_to_string() {
 
     @Test
     public void should_remove_recursive_self_call_from_stack_trace() throws Exception {
-        StackTraceElement[] stack = new StackTraceElement[]{
-                new StackTraceElement("foo", "", "", -1),
-                new StackTraceElement(SampleInterface.class.getName(), "", "", -1),
-                new StackTraceElement("qux", "", "", -1),
-                new StackTraceElement("bar", "", "", -1),
-                new StackTraceElement("baz", "", "", -1)
-        };
+        StackTraceElement[] stack =
+                new StackTraceElement[] {
+                    new StackTraceElement("foo", "", "", -1),
+                    new StackTraceElement(SampleInterface.class.getName(), "", "", -1),
+                    new StackTraceElement("qux", "", "", -1),
+                    new StackTraceElement("bar", "", "", -1),
+                    new StackTraceElement("baz", "", "", -1)
+                };
 
         Throwable throwable = new Throwable();
         throwable.setStackTrace(stack);
         throwable = MockMethodAdvice.hideRecursiveCall(throwable, 2, SampleInterface.class);
 
-        assertThat(throwable.getStackTrace()).isEqualTo(new StackTraceElement[]{
-                new StackTraceElement("foo", "", "", -1),
-                new StackTraceElement("bar", "", "", -1),
-                new StackTraceElement("baz", "", "", -1)
-        });
+        assertThat(throwable.getStackTrace())
+                .isEqualTo(
+                        new StackTraceElement[] {
+                            new StackTraceElement("foo", "", "", -1),
+                            new StackTraceElement("bar", "", "", -1),
+                            new StackTraceElement("baz", "", "", -1)
+                        });
     }
 
     @Test
     public void should_handle_missing_or_inconsistent_stack_trace() throws Exception {
         Throwable throwable = new Throwable();
         throwable.setStackTrace(new StackTraceElement[0]);
-        assertThat(MockMethodAdvice.hideRecursiveCall(throwable, 0, SampleInterface.class)).isSameAs(throwable);
+        assertThat(MockMethodAdvice.hideRecursiveCall(throwable, 0, SampleInterface.class))
+                .isSameAs(throwable);
     }
 
     @Test
     public void should_provide_reason_for_wrapper_class() {
         MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Integer.class);
-        assertThat(mockable.nonMockableReason()).isEqualTo("Cannot mock wrapper types, String.class or Class.class");
+        assertThat(mockable.nonMockableReason())
+                .isEqualTo("Cannot mock wrapper types, String.class or Class.class");
     }
 
     @Test
     public void should_provide_reason_for_vm_unsupported() {
         MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(int[].class);
-        assertThat(mockable.nonMockableReason()).isEqualTo("VM does not support modification of given type");
+        assertThat(mockable.nonMockableReason())
+                .isEqualTo("VM does not support modification of given type");
     }
 
     @Test
     public void should_mock_method_of_package_private_class() throws Exception {
-        MockCreationSettings settings = settingsFor(NonPackagePrivateSubClass.class);
-        NonPackagePrivateSubClass proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        MockCreationSettings settings =
+                settingsFor(NonPackagePrivateSubClass.class);
+        NonPackagePrivateSubClass proxy =
+                mockMaker.createMock(
+                        settings, new MockHandlerImpl(settings));
         assertThat(proxy.value()).isEqualTo("bar");
     }
 
@@ -230,14 +251,16 @@ public void should_mock_method_of_package_private_class() throws Exception {
     public void is_type_mockable_excludes_String() {
         MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(String.class);
         assertThat(mockable.mockable()).isFalse();
-        assertThat(mockable.nonMockableReason()).contains("Cannot mock wrapper types, String.class or Class.class");
+        assertThat(mockable.nonMockableReason())
+                .contains("Cannot mock wrapper types, String.class or Class.class");
     }
 
     @Test
     public void is_type_mockable_excludes_Class() {
         MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Class.class);
         assertThat(mockable.mockable()).isFalse();
-        assertThat(mockable.nonMockableReason()).contains("Cannot mock wrapper types, String.class or Class.class");
+        assertThat(mockable.nonMockableReason())
+                .contains("Cannot mock wrapper types, String.class or Class.class");
     }
 
     @Test
@@ -249,11 +272,11 @@ public void is_type_mockable_excludes_primitive_classes() {
 
     @Test
     public void is_type_mockable_allows_anonymous() {
-        Observer anonymous = new Observer() {
-            @Override
-            public void update(Observable o, Object arg) {
-            }
-        };
+        Observer anonymous =
+                new Observer() {
+                    @Override
+                    public void update(Observable o, Object arg) {}
+                };
         MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(anonymous.getClass());
         assertThat(mockable.mockable()).isTrue();
         assertThat(mockable.nonMockableReason()).contains("");
@@ -277,35 +300,44 @@ public void is_type_mockable_give_allow_final_mockable_from_JDK() {
     public void test_parameters_retention() throws Exception {
         assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V8));
 
-        Class typeWithParameters = new ByteBuddy()
-                .subclass(Object.class)
-                .defineMethod("foo", void.class, Visibility.PUBLIC)
-                .withParameter(String.class, "bar")
-                .intercept(StubMethod.INSTANCE)
-                .make()
-                .load(null)
-                .getLoaded();
+        Class typeWithParameters =
+                new ByteBuddy()
+                        .subclass(Object.class)
+                        .defineMethod("foo", void.class, Visibility.PUBLIC)
+                        .withParameter(String.class, "bar")
+                        .intercept(StubMethod.INSTANCE)
+                        .make()
+                        .load(null)
+                        .getLoaded();
 
         MockCreationSettings settings = settingsFor(typeWithParameters);
         @SuppressWarnings("unchecked")
         Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
 
         assertThat(proxy.getClass()).isEqualTo(typeWithParameters);
-        assertThat(new TypeDescription.ForLoadedType(typeWithParameters).getDeclaredMethods().filter(named("foo"))
-                .getOnly().getParameters().getOnly().getName()).isEqualTo("bar");
+        assertThat(
+                        new TypeDescription.ForLoadedType(typeWithParameters)
+                                .getDeclaredMethods()
+                                .filter(named("foo"))
+                                .getOnly()
+                                .getParameters()
+                                .getOnly()
+                                .getName())
+                .isEqualTo("bar");
     }
 
     @Test
     public void test_constant_dynamic_compatibility() throws Exception {
         assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V11));
 
-        Class typeWithCondy = new ByteBuddy()
-                .subclass(Callable.class)
-                .method(named("call"))
-                .intercept(FixedValue.value(JavaConstant.Dynamic.ofNullConstant()))
-                .make()
-                .load(null)
-                .getLoaded();
+        Class typeWithCondy =
+                new ByteBuddy()
+                        .subclass(Callable.class)
+                        .method(named("call"))
+                        .intercept(FixedValue.value(JavaConstant.Dynamic.ofNullConstant()))
+                        .make()
+                        .load(null)
+                        .getLoaded();
 
         MockCreationSettings settings = settingsFor(typeWithCondy);
         @SuppressWarnings("unchecked")
@@ -317,35 +349,39 @@ public void test_constant_dynamic_compatibility() throws Exception {
     @Test
     public void test_clear_mock_clears_handler() {
         MockCreationSettings settings = settingsFor(GenericSubClass.class);
-        GenericSubClass proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        GenericSubClass proxy =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
         assertThat(mockMaker.getHandler(proxy)).isNotNull();
 
-        //when
+        // when
         mockMaker.clearMock(proxy);
 
-        //then
+        // then
         assertThat(mockMaker.getHandler(proxy)).isNull();
     }
 
     @Test
     public void test_clear_all_mock_clears_handler() {
         MockCreationSettings settings = settingsFor(GenericSubClass.class);
-        GenericSubClass proxy1 = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        GenericSubClass proxy1 =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
         assertThat(mockMaker.getHandler(proxy1)).isNotNull();
 
         settings = settingsFor(GenericSubClass.class);
-        GenericSubClass proxy2 = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+        GenericSubClass proxy2 =
+                mockMaker.createMock(settings, new MockHandlerImpl(settings));
         assertThat(mockMaker.getHandler(proxy1)).isNotNull();
 
-        //when
+        // when
         mockMaker.clearAllMocks();
 
-        //then
+        // then
         assertThat(mockMaker.getHandler(proxy1)).isNull();
         assertThat(mockMaker.getHandler(proxy2)).isNull();
     }
 
-    private static  MockCreationSettings settingsFor(Class type, Class... extraInterfaces) {
+    private static  MockCreationSettings settingsFor(
+            Class type, Class... extraInterfaces) {
         MockSettingsImpl mockSettings = new MockSettingsImpl();
         mockSettings.setTypeToMock(type);
         mockSettings.defaultAnswer(new Returns("bar"));
@@ -355,9 +391,12 @@ private static  MockCreationSettings settingsFor(Class type, Class..
 
     @Test
     public void testMockDispatcherIsRelocated() throws Exception {
-        assertThat(InlineByteBuddyMockMaker.class.getClassLoader()
-            .getResource("org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.raw"))
-            .isNotNull();
+        assertThat(
+                        InlineByteBuddyMockMaker.class
+                                .getClassLoader()
+                                .getResource(
+                                        "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.raw"))
+                .isNotNull();
     }
 
     private static final class FinalClass {
@@ -368,7 +407,6 @@ public String foo() {
     }
 
     private enum EnumClass {
-
         INSTANCE;
 
         public String foo() {
@@ -421,6 +459,5 @@ public T value() {
         }
     }
 
-    public static class GenericSubClass extends GenericClass {
-    }
+    public static class GenericSubClass extends GenericClass {}
 }
diff --git a/src/test/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMakerTest.java b/src/test/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMakerTest.java
index 819e62c2c5..35c74d6bd4 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/SubclassByteBuddyMockMakerTest.java
@@ -15,7 +15,8 @@
 import org.mockito.internal.creation.MockSettingsImpl;
 import org.mockito.plugins.MockMaker;
 
-public class SubclassByteBuddyMockMakerTest extends AbstractByteBuddyMockMakerTest {
+public class SubclassByteBuddyMockMakerTest
+        extends AbstractByteBuddyMockMakerTest {
 
     public SubclassByteBuddyMockMakerTest() {
         super(new SubclassByteBuddyMockMaker());
@@ -37,9 +38,11 @@ public void is_type_mockable_excludes_primitive_classes() {
 
     @Test
     public void is_type_mockable_allow_anonymous() {
-        Observer anonymous = new Observer() {
-            @Override public void update(Observable o, Object arg) { }
-        };
+        Observer anonymous =
+                new Observer() {
+                    @Override
+                    public void update(Observable o, Object arg) {}
+                };
         MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(anonymous.getClass());
         assertThat(mockable.mockable()).isTrue();
         assertThat(mockable.nonMockableReason()).contains("");
@@ -54,7 +57,8 @@ public void is_type_mockable_give_empty_reason_if_type_is_mockable() {
 
     @Test
     public void mock_type_with_annotations() throws Exception {
-        MockSettingsImpl mockSettings = new MockSettingsImpl();
+        MockSettingsImpl mockSettings =
+                new MockSettingsImpl();
         mockSettings.setTypeToMock(ClassWithAnnotation.class);
 
         ClassWithAnnotation proxy = mockMaker.createMock(mockSettings, dummyHandler());
@@ -62,20 +66,34 @@ public void mock_type_with_annotations() throws Exception {
         assertThat(proxy.getClass().isAnnotationPresent(SampleAnnotation.class)).isTrue();
         assertThat(proxy.getClass().getAnnotation(SampleAnnotation.class).value()).isEqualTo("foo");
 
-        assertThat(proxy.getClass().getMethod("sampleMethod").isAnnotationPresent(SampleAnnotation.class)).isTrue();
-        assertThat(proxy.getClass().getMethod("sampleMethod").getAnnotation(SampleAnnotation.class).value()).isEqualTo("bar");
+        assertThat(
+                        proxy.getClass()
+                                .getMethod("sampleMethod")
+                                .isAnnotationPresent(SampleAnnotation.class))
+                .isTrue();
+        assertThat(
+                        proxy.getClass()
+                                .getMethod("sampleMethod")
+                                .getAnnotation(SampleAnnotation.class)
+                                .value())
+                .isEqualTo("bar");
     }
 
     @Test
     public void mock_type_without_annotations() throws Exception {
-        MockSettingsImpl mockSettings = new MockSettingsImpl();
+        MockSettingsImpl mockSettings =
+                new MockSettingsImpl();
         mockSettings.setTypeToMock(ClassWithAnnotation.class);
         mockSettings.withoutAnnotations();
 
         ClassWithAnnotation proxy = mockMaker.createMock(mockSettings, dummyHandler());
 
         assertThat(proxy.getClass().isAnnotationPresent(SampleAnnotation.class)).isFalse();
-        assertThat(proxy.getClass().getMethod("sampleMethod").isAnnotationPresent(SampleAnnotation.class)).isFalse();
+        assertThat(
+                        proxy.getClass()
+                                .getMethod("sampleMethod")
+                                .isAnnotationPresent(SampleAnnotation.class))
+                .isFalse();
     }
 
     @Override
diff --git a/src/test/java/org/mockito/internal/creation/bytebuddy/TypeCachingMockBytecodeGeneratorTest.java b/src/test/java/org/mockito/internal/creation/bytebuddy/TypeCachingMockBytecodeGeneratorTest.java
index a75062ae0a..d0ed772a68 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/TypeCachingMockBytecodeGeneratorTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/TypeCachingMockBytecodeGeneratorTest.java
@@ -29,23 +29,28 @@ public void ensure_disable_gc_is_activated() throws Exception {
     }
 
     @Test
-    public void ensure_cache_is_cleared_if_no_reference_to_classloader_and_classes() throws Exception {
+    public void ensure_cache_is_cleared_if_no_reference_to_classloader_and_classes()
+            throws Exception {
         // given
-        ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader()
-                .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
-                .build();
-
-        TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
-
-        Class the_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(
-                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
-                Collections.>emptySet(),
-                SerializableMode.NONE,
-                false
-        ));
+        ClassLoader classloader_with_life_shorter_than_cache =
+                inMemoryClassLoader()
+                        .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
+                        .build();
+
+        TypeCachingBytecodeGenerator cachingMockBytecodeGenerator =
+                new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
+
+        Class the_mock_type =
+                cachingMockBytecodeGenerator.mockClass(
+                        withMockFeatures(
+                                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
+                                Collections.>emptySet(),
+                                SerializableMode.NONE,
+                                false));
 
         ReferenceQueue referenceQueue = new ReferenceQueue();
-        Reference typeReference = new PhantomReference(the_mock_type, referenceQueue);
+        Reference typeReference =
+                new PhantomReference(the_mock_type, referenceQueue);
 
         // when
         classloader_with_life_shorter_than_cache = is_no_more_referenced();
@@ -61,29 +66,34 @@ public void ensure_cache_is_cleared_if_no_reference_to_classloader_and_classes()
     @Test
     public void ensure_cache_returns_same_instance() throws Exception {
         // given
-        ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader()
-                .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
-                .build();
-
-        TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
-        Class the_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(
-                        classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
-                        Collections.>emptySet(),
-                        SerializableMode.NONE,
-                        false
-                ));
-
-        Class other_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(
-                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
-                Collections.>emptySet(),
-                SerializableMode.NONE,
-                false
-        ));
+        ClassLoader classloader_with_life_shorter_than_cache =
+                inMemoryClassLoader()
+                        .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
+                        .build();
+
+        TypeCachingBytecodeGenerator cachingMockBytecodeGenerator =
+                new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
+        Class the_mock_type =
+                cachingMockBytecodeGenerator.mockClass(
+                        withMockFeatures(
+                                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
+                                Collections.>emptySet(),
+                                SerializableMode.NONE,
+                                false));
+
+        Class other_mock_type =
+                cachingMockBytecodeGenerator.mockClass(
+                        withMockFeatures(
+                                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
+                                Collections.>emptySet(),
+                                SerializableMode.NONE,
+                                false));
 
         assertThat(other_mock_type).isSameAs(the_mock_type);
 
         ReferenceQueue referenceQueue = new ReferenceQueue();
-        Reference typeReference = new PhantomReference(the_mock_type, referenceQueue);
+        Reference typeReference =
+                new PhantomReference(the_mock_type, referenceQueue);
 
         // when
         classloader_with_life_shorter_than_cache = is_no_more_referenced();
@@ -100,37 +110,47 @@ public void ensure_cache_returns_same_instance() throws Exception {
     @Test
     public void ensure_cache_returns_different_instance_serializableMode() throws Exception {
         // given
-        ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader()
-                .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
-                .build();
-
-        TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
-        Class the_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(
-                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
-                Collections.>emptySet(),
-                SerializableMode.NONE,
-                false
-        ));
-
-        Class other_mock_type = cachingMockBytecodeGenerator.mockClass(withMockFeatures(
-                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
-                Collections.>emptySet(),
-                SerializableMode.BASIC,
-                false
-        ));
+        ClassLoader classloader_with_life_shorter_than_cache =
+                inMemoryClassLoader()
+                        .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
+                        .build();
+
+        TypeCachingBytecodeGenerator cachingMockBytecodeGenerator =
+                new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true);
+        Class the_mock_type =
+                cachingMockBytecodeGenerator.mockClass(
+                        withMockFeatures(
+                                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
+                                Collections.>emptySet(),
+                                SerializableMode.NONE,
+                                false));
+
+        Class other_mock_type =
+                cachingMockBytecodeGenerator.mockClass(
+                        withMockFeatures(
+                                classloader_with_life_shorter_than_cache.loadClass("foo.Bar"),
+                                Collections.>emptySet(),
+                                SerializableMode.BASIC,
+                                false));
 
         assertThat(other_mock_type).isNotSameAs(the_mock_type);
     }
 
     @Test
-    public void validate_simple_code_idea_where_weakhashmap_with_classloader_as_key_get_GCed_when_no_more_references() throws Exception {
+    public void
+            validate_simple_code_idea_where_weakhashmap_with_classloader_as_key_get_GCed_when_no_more_references()
+                    throws Exception {
         // given
         WeakHashMap cache = new WeakHashMap();
-        ClassLoader short_lived_classloader = inMemoryClassLoader()
-                .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
-                .build();
+        ClassLoader short_lived_classloader =
+                inMemoryClassLoader()
+                        .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar"))
+                        .build();
 
-        cache.put(short_lived_classloader, new HoldingAReference(new WeakReference>(short_lived_classloader.loadClass("foo.Bar"))));
+        cache.put(
+                short_lived_classloader,
+                new HoldingAReference(
+                        new WeakReference>(short_lived_classloader.loadClass("foo.Bar"))));
 
         assertThat(cache).hasSize(1);
 
@@ -152,7 +172,6 @@ static class HoldingAReference {
         }
     }
 
-
     private static  T is_no_more_referenced() {
         return null;
     }
diff --git a/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java b/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java
index 07deae8aa6..d576116aa2 100644
--- a/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java
+++ b/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java
@@ -13,60 +13,77 @@
 
 public class ConstructorInstantiatorTest extends TestBase {
 
-    static class SomeClass {
+    static class SomeClass {}
 
-    }
-
-    class SomeInnerClass {
+    class SomeInnerClass {}
 
-    }
-
-    class ChildOfThis extends ConstructorInstantiatorTest {
-
-    }
+    class ChildOfThis extends ConstructorInstantiatorTest {}
 
     static class SomeClass2 {
 
-        SomeClass2(String x) {
-        }
+        SomeClass2(String x) {}
     }
 
     static class SomeClass3 {
 
-        SomeClass3(int i) {
-
-        }
+        SomeClass3(int i) {}
     }
 
     @Test
     public void creates_instances() {
-        assertEquals(new ConstructorInstantiator(false, new Object[0]).newInstance(SomeClass.class).getClass(), SomeClass.class);
+        assertEquals(
+                new ConstructorInstantiator(false, new Object[0])
+                        .newInstance(SomeClass.class)
+                        .getClass(),
+                SomeClass.class);
     }
 
     @Test
     public void creates_instances_of_inner_classes() {
-        assertEquals(new ConstructorInstantiator(true, this).newInstance(SomeInnerClass.class).getClass(), SomeInnerClass.class);
-        assertEquals(new ConstructorInstantiator(true, new ChildOfThis()).newInstance(SomeInnerClass.class).getClass(), SomeInnerClass.class);
+        assertEquals(
+                new ConstructorInstantiator(true, this)
+                        .newInstance(SomeInnerClass.class)
+                        .getClass(),
+                SomeInnerClass.class);
+        assertEquals(
+                new ConstructorInstantiator(true, new ChildOfThis())
+                        .newInstance(SomeInnerClass.class)
+                        .getClass(),
+                SomeInnerClass.class);
     }
 
     @Test
     public void creates_instances_with_arguments() {
-        assertEquals(new ConstructorInstantiator(false, "someString").newInstance(SomeClass2.class).getClass(), SomeClass2.class);
+        assertEquals(
+                new ConstructorInstantiator(false, "someString")
+                        .newInstance(SomeClass2.class)
+                        .getClass(),
+                SomeClass2.class);
     }
 
     @Test
     public void creates_instances_with_null_arguments() {
-        assertEquals(new ConstructorInstantiator(false, new Object[]{null}).newInstance(SomeClass2.class).getClass(), SomeClass2.class);
+        assertEquals(
+                new ConstructorInstantiator(false, new Object[] {null})
+                        .newInstance(SomeClass2.class)
+                        .getClass(),
+                SomeClass2.class);
     }
 
     @Test
     public void creates_instances_with_primitive_arguments() {
-        assertEquals(new ConstructorInstantiator(false, 123).newInstance(SomeClass3.class).getClass(), SomeClass3.class);
+        assertEquals(
+                new ConstructorInstantiator(false, 123).newInstance(SomeClass3.class).getClass(),
+                SomeClass3.class);
     }
 
     @Test(expected = org.mockito.creation.instance.InstantiationException.class)
     public void fails_when_null_is_passed_for_a_primitive() {
-        assertEquals(new ConstructorInstantiator(false, new Object[]{null}).newInstance(SomeClass3.class).getClass(), SomeClass3.class);
+        assertEquals(
+                new ConstructorInstantiator(false, new Object[] {null})
+                        .newInstance(SomeClass3.class)
+                        .getClass(),
+                SomeClass3.class);
     }
 
     @Test
@@ -75,8 +92,10 @@ public void explains_when_constructor_cannot_be_found() {
             new ConstructorInstantiator(false, new Object[0]).newInstance(SomeClass2.class);
             fail();
         } catch (org.mockito.creation.instance.InstantiationException e) {
-            assertThat(e).hasMessageContaining("Unable to create instance of 'SomeClass2'.\n" +
-                    "Please ensure that the target class has a 0-arg constructor.");
+            assertThat(e)
+                    .hasMessageContaining(
+                            "Unable to create instance of 'SomeClass2'.\n"
+                                    + "Please ensure that the target class has a 0-arg constructor.");
         }
     }
 }
diff --git a/src/test/java/org/mockito/internal/debugging/LoggingListenerTest.java b/src/test/java/org/mockito/internal/debugging/LoggingListenerTest.java
index b7eda71294..54c5bec09d 100644
--- a/src/test/java/org/mockito/internal/debugging/LoggingListenerTest.java
+++ b/src/test/java/org/mockito/internal/debugging/LoggingListenerTest.java
@@ -4,7 +4,6 @@
  */
 package org.mockito.internal.debugging;
 
-
 import static org.junit.Assert.assertEquals;
 
 import org.junit.Test;
@@ -15,30 +14,31 @@ public class LoggingListenerTest extends TestBase {
 
     @Test
     public void may_not_have_any_information() {
-        //given
+        // given
         LoggingListener listener = new LoggingListener(true);
 
-        //expect
+        // expect
         assertEquals("", listener.getStubbingInfo());
     }
 
     @Test
     public void informs_about_unused_stubs() {
-        //given
+        // given
         LoggingListener listener = new LoggingListener(false);
 
-        //when
+        // when
         listener.foundUnusedStub(invocationAt("at com.FooTest:30"));
         listener.foundUnusedStub(invocationAt("at com.FooTest:32"));
 
-        //then
+        // then
         assertEquals(
-            "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n" +
-            "[Mockito]\n" +
-            "[Mockito] Unused stubbing (perhaps can be removed from the test?):\n" +
-            "[Mockito]\n" +
-            "[Mockito] 1. at com.FooTest:30\n" +
-            "[Mockito] 2. at com.FooTest:32", listener.getStubbingInfo());
+                "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] Unused stubbing (perhaps can be removed from the test?):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] 1. at com.FooTest:30\n"
+                        + "[Mockito] 2. at com.FooTest:32",
+                listener.getStubbingInfo());
     }
 
     @Test
@@ -51,79 +51,85 @@ public void calculates_indexes_for_clean_output() {
 
     @Test
     public void informs_about_unused_stubs_due_arg_mismatch() {
-        //given
+        // given
         LoggingListener listener = new LoggingListener(false);
 
-        //when
-        listener.foundStubCalledWithDifferentArgs(invocationAt("at com.FooTest:20"), invocationMatcherAt("at com.Foo:100"));
-        listener.foundStubCalledWithDifferentArgs(invocationAt("at com.FooTest:21"), invocationMatcherAt("at com.Foo:121"));
+        // when
+        listener.foundStubCalledWithDifferentArgs(
+                invocationAt("at com.FooTest:20"), invocationMatcherAt("at com.Foo:100"));
+        listener.foundStubCalledWithDifferentArgs(
+                invocationAt("at com.FooTest:21"), invocationMatcherAt("at com.Foo:121"));
 
-        //then
+        // then
         assertEquals(
-            "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n" +
-            "[Mockito]\n" +
-            "[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):\n" +
-            "[Mockito]\n" +
-            "[Mockito] 1. Stubbed at com.FooTest:20\n" +
-            "[Mockito]    Invoked at com.Foo:100\n" +
-            "[Mockito] 2. Stubbed at com.FooTest:21\n" +
-            "[Mockito]    Invoked at com.Foo:121", listener.getStubbingInfo());
+                "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] 1. Stubbed at com.FooTest:20\n"
+                        + "[Mockito]    Invoked at com.Foo:100\n"
+                        + "[Mockito] 2. Stubbed at com.FooTest:21\n"
+                        + "[Mockito]    Invoked at com.Foo:121",
+                listener.getStubbingInfo());
     }
 
     @Test
     public void informs_about_various_kinds_of_stubs() {
-        //given
+        // given
         LoggingListener listener = new LoggingListener(true);
 
-        //when
+        // when
         listener.foundUnusedStub(invocationAt("at com.FooTest:30"));
-        listener.foundStubCalledWithDifferentArgs(invocationAt("at com.FooTest:20"), invocationMatcherAt("at com.Foo:100"));
+        listener.foundStubCalledWithDifferentArgs(
+                invocationAt("at com.FooTest:20"), invocationMatcherAt("at com.Foo:100"));
         listener.foundUnstubbed(invocationMatcherAt("at com.Foo:96"));
 
-        //then
+        // then
         assertEquals(
-            "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n" +
-            "[Mockito]\n" +
-            "[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):\n" +
-            "[Mockito]\n" +
-            "[Mockito] 1. Stubbed at com.FooTest:20\n" +
-            "[Mockito]    Invoked at com.Foo:100\n" +
-            "[Mockito]\n" +
-            "[Mockito] Unused stubbing (perhaps can be removed from the test?):\n" +
-            "[Mockito]\n" +
-            "[Mockito] 1. at com.FooTest:30\n" +
-            "[Mockito]\n" +
-            "[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):\n" +
-            "[Mockito]\n" +
-            "[Mockito] 1. at com.Foo:96", listener.getStubbingInfo());
+                "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] 1. Stubbed at com.FooTest:20\n"
+                        + "[Mockito]    Invoked at com.Foo:100\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] Unused stubbing (perhaps can be removed from the test?):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] 1. at com.FooTest:30\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] 1. at com.Foo:96",
+                listener.getStubbingInfo());
     }
 
     @Test
     public void hides_unstubbed() {
-        //given
+        // given
         LoggingListener listener = new LoggingListener(false);
 
-        //when
+        // when
         listener.foundUnstubbed(new InvocationBuilder().toInvocationMatcher());
 
-        //then
+        // then
         assertEquals("", listener.getStubbingInfo());
     }
 
     @Test
     public void informs_about_unstubbed() {
-        //given
+        // given
         LoggingListener listener = new LoggingListener(true);
 
-        //when
+        // when
         listener.foundUnstubbed(invocationMatcherAt("com.Foo:20"));
 
-        //then
+        // then
         assertEquals(
-                "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n" +
-                "[Mockito]\n" +
-                "[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):\n" +
-                "[Mockito]\n" +
-                "[Mockito] 1. com.Foo:20", listener.getStubbingInfo());
+                "[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):\n"
+                        + "[Mockito]\n"
+                        + "[Mockito] 1. com.Foo:20",
+                listener.getStubbingInfo());
     }
 }
diff --git a/src/test/java/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java b/src/test/java/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java
index 6b722f4729..2fb7a0ddb4 100644
--- a/src/test/java/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java
+++ b/src/test/java/org/mockito/internal/debugging/VerboseMockInvocationLoggerTest.java
@@ -57,7 +57,8 @@ public void should_print_invocation_with_return_value() {
     @Test
     public void should_print_invocation_with_exception() {
         // when
-        listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
+        listener.reportInvocation(
+                new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
 
         // then
         assertThat(printed())
@@ -87,13 +88,16 @@ public void should_print_stubbed_info_if_available() throws Exception {
     @Test
     public void should_log_count_of_interactions() {
         // when & then
-        listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
+        listener.reportInvocation(
+                new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
         assertThat(printed()).contains("#1");
 
-        listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
+        listener.reportInvocation(
+                new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
         assertThat(printed()).contains("#2");
 
-        listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
+        listener.reportInvocation(
+                new NotifiedMethodInvocationReport(invocation, new ThirdPartyException()));
         assertThat(printed()).contains("#3");
     }
 
diff --git a/src/test/java/org/mockito/internal/debugging/WarningsFinderTest.java b/src/test/java/org/mockito/internal/debugging/WarningsFinderTest.java
index 97d7242dd3..c8fd02fb2d 100644
--- a/src/test/java/org/mockito/internal/debugging/WarningsFinderTest.java
+++ b/src/test/java/org/mockito/internal/debugging/WarningsFinderTest.java
@@ -30,7 +30,8 @@ public void shouldPrintUnusedStub() {
         Invocation unusedStub = new InvocationBuilder().simpleMethod().toInvocation();
 
         // when
-        WarningsFinder finder = new WarningsFinder(asList(unusedStub), Arrays.asList());
+        WarningsFinder finder =
+                new WarningsFinder(asList(unusedStub), Arrays.asList());
         finder.find(listener);
 
         // then
@@ -40,10 +41,14 @@ public void shouldPrintUnusedStub() {
     @Test
     public void shouldPrintUnstubbedInvocation() {
         // given
-        InvocationMatcher unstubbedInvocation = new InvocationBuilder().differentMethod().toInvocationMatcher();
+        InvocationMatcher unstubbedInvocation =
+                new InvocationBuilder().differentMethod().toInvocationMatcher();
 
         // when
-        WarningsFinder finder = new WarningsFinder(Arrays.asList(), Arrays.asList(unstubbedInvocation));
+        WarningsFinder finder =
+                new WarningsFinder(
+                        Arrays.asList(),
+                        Arrays.asList(unstubbedInvocation));
         finder.find(listener);
 
         // then
@@ -54,10 +59,14 @@ public void shouldPrintUnstubbedInvocation() {
     public void shouldPrintStubWasUsedWithDifferentArgs() {
         // given
         Invocation stub = new InvocationBuilder().arg("foo").mock(mock).toInvocation();
-        InvocationMatcher wrongArg = new InvocationBuilder().arg("bar").mock(mock).toInvocationMatcher();
+        InvocationMatcher wrongArg =
+                new InvocationBuilder().arg("bar").mock(mock).toInvocationMatcher();
 
         // when
-        WarningsFinder finder = new WarningsFinder(Arrays. asList(stub), Arrays. asList(wrongArg));
+        WarningsFinder finder =
+                new WarningsFinder(
+                        Arrays.asList(stub),
+                        Arrays.asList(wrongArg));
         finder.find(listener);
 
         // then
diff --git a/src/test/java/org/mockito/internal/exceptions/ReporterTest.java b/src/test/java/org/mockito/internal/exceptions/ReporterTest.java
index 1519bdc347..3b71be348f 100644
--- a/src/test/java/org/mockito/internal/exceptions/ReporterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/ReporterTest.java
@@ -25,7 +25,10 @@ public class ReporterTest extends TestBase {
 
     @Test(expected = TooFewActualInvocations.class)
     public void should_let_passing_null_last_actual_stack_trace() throws Exception {
-        throw Reporter.tooFewActualInvocations(new org.mockito.internal.reporting.Discrepancy(1, 2), new InvocationBuilder().toInvocation(), null);
+        throw Reporter.tooFewActualInvocations(
+                new org.mockito.internal.reporting.Discrepancy(1, 2),
+                new InvocationBuilder().toInvocation(),
+                null);
     }
 
     @Test(expected = MockitoException.class)
@@ -34,51 +37,86 @@ public void should_throw_correct_exception_for_null_invocation_listener() throws
     }
 
     @Test(expected = NoInteractionsWanted.class)
-    public void can_use_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted() throws Exception {
-        Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
-        throw Reporter.noMoreInteractionsWanted(invocation_with_bogus_default_answer, Collections.emptyList());
+    public void
+            can_use_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted()
+                    throws Exception {
+        Invocation invocation_with_bogus_default_answer =
+                new InvocationBuilder()
+                        .mock(mock(IMethods.class, new Returns(false)))
+                        .toInvocation();
+        throw Reporter.noMoreInteractionsWanted(
+                invocation_with_bogus_default_answer,
+                Collections.emptyList());
     }
 
     @Test(expected = VerificationInOrderFailure.class)
-    public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted_in_order() throws Exception {
-        Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
+    public void
+            can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted_in_order()
+                    throws Exception {
+        Invocation invocation_with_bogus_default_answer =
+                new InvocationBuilder()
+                        .mock(mock(IMethods.class, new Returns(false)))
+                        .toInvocation();
         throw Reporter.noMoreInteractionsWantedInOrder(invocation_with_bogus_default_answer);
     }
 
     @Test(expected = MockitoException.class)
-    public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_invalid_argument_position() throws Exception {
-        Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
-        throw Reporter.invalidArgumentPositionRangeAtInvocationTime(invocation_with_bogus_default_answer, true, 0);
+    public void
+            can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_invalid_argument_position()
+                    throws Exception {
+        Invocation invocation_with_bogus_default_answer =
+                new InvocationBuilder()
+                        .mock(mock(IMethods.class, new Returns(false)))
+                        .toInvocation();
+        throw Reporter.invalidArgumentPositionRangeAtInvocationTime(
+                invocation_with_bogus_default_answer, true, 0);
     }
 
     @Test(expected = MockitoException.class)
-    public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_wrong_argument_to_return() throws Exception {
-        Invocation invocation_with_bogus_default_answer = new InvocationBuilder().mock(mock(IMethods.class, new Returns(false))).toInvocation();
-        throw Reporter.wrongTypeOfArgumentToReturn(invocation_with_bogus_default_answer, "", String.class, 0);
+    public void
+            can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_wrong_argument_to_return()
+                    throws Exception {
+        Invocation invocation_with_bogus_default_answer =
+                new InvocationBuilder()
+                        .mock(mock(IMethods.class, new Returns(false)))
+                        .toInvocation();
+        throw Reporter.wrongTypeOfArgumentToReturn(
+                invocation_with_bogus_default_answer, "", String.class, 0);
     }
 
     @Test(expected = MockitoException.class)
-    public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_dont_exists() throws Exception {
+    public void
+            can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_dont_exists()
+                    throws Exception {
         Invocation dumb_invocation = new InvocationBuilder().toInvocation();
         IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false));
-        throw Reporter.delegatedMethodDoesNotExistOnDelegate(dumb_invocation.getMethod(), mock_with_bogus_default_answer, String.class);
+        throw Reporter.delegatedMethodDoesNotExistOnDelegate(
+                dumb_invocation.getMethod(), mock_with_bogus_default_answer, String.class);
     }
 
     @Test(expected = MockitoException.class)
-    public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_has_wrong_return_type() throws Exception {
+    public void
+            can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_has_wrong_return_type()
+                    throws Exception {
         Invocation dumb_invocation = new InvocationBuilder().toInvocation();
         IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false));
-        throw Reporter.delegatedMethodHasWrongReturnType(dumb_invocation.getMethod(), dumb_invocation.getMethod(), mock_with_bogus_default_answer, String.class);
+        throw Reporter.delegatedMethodHasWrongReturnType(
+                dumb_invocation.getMethod(),
+                dumb_invocation.getMethod(),
+                mock_with_bogus_default_answer,
+                String.class);
     }
 
     @Test(expected = MockitoException.class)
-    public void can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_injection_failure() throws Exception {
+    public void
+            can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_injection_failure()
+                    throws Exception {
         IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false));
-        throw Reporter.cannotInjectDependency(someField(), mock_with_bogus_default_answer, new Exception());
+        throw Reporter.cannotInjectDependency(
+                someField(), mock_with_bogus_default_answer, new Exception());
     }
 
     private Field someField() {
         return Mockito.class.getDeclaredFields()[0];
     }
-
 }
diff --git a/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java b/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java
index 26872fb01d..064bca5e54 100644
--- a/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilterTest.java
@@ -20,24 +20,27 @@ public class ConditionalStackTraceFilterTest extends TestBase {
     public void shouldNotFilterWhenConfigurationSaysNo() {
         ConfigurationAccess.getConfig().overrideCleansStackTrace(false);
 
-        Throwable t = new TraceBuilder().classes(
-                "org.test.MockitoSampleTest",
-                "org.mockito.Mockito"
-        ).toThrowable();
+        Throwable t =
+                new TraceBuilder()
+                        .classes("org.test.MockitoSampleTest", "org.mockito.Mockito")
+                        .toThrowable();
 
         filter.filter(t);
 
-        Assertions.assertThat(t).has(onlyThoseClassesInStackTrace("org.mockito.Mockito", "org.test.MockitoSampleTest"));
+        Assertions.assertThat(t)
+                .has(
+                        onlyThoseClassesInStackTrace(
+                                "org.mockito.Mockito", "org.test.MockitoSampleTest"));
     }
 
     @Test
     public void shouldFilterWhenConfigurationSaysYes() {
         ConfigurationAccess.getConfig().overrideCleansStackTrace(true);
 
-        Throwable t = new TraceBuilder().classes(
-                "org.test.MockitoSampleTest",
-                "org.mockito.Mockito"
-        ).toThrowable();
+        Throwable t =
+                new TraceBuilder()
+                        .classes("org.test.MockitoSampleTest", "org.mockito.Mockito")
+                        .toThrowable();
 
         filter.filter(t);
 
diff --git a/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java b/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
index 78e026795b..589c03cbf2 100644
--- a/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilterTest.java
@@ -18,10 +18,10 @@ public class StackTraceFilterTest extends TestBase {
 
     @Test
     public void shouldFilterOutCglibGarbage() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-            "MockitoExampleTest",
-            "List$$EnhancerByMockitoWithCGLIB$$2c406024"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes("MockitoExampleTest", "List$$EnhancerByMockitoWithCGLIB$$2c406024")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
@@ -30,23 +30,24 @@ public void shouldFilterOutCglibGarbage() {
 
     @Test
     public void shouldFilterOutByteBuddyGarbage() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "MockitoExampleTest",
-                "org.testcase.MockedClass$MockitoMock$1882975947.doSomething(Unknown Source)"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "MockitoExampleTest",
+                                "org.testcase.MockedClass$MockitoMock$1882975947.doSomething(Unknown Source)")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
         Assertions.assertThat(filtered).has(onlyThoseClasses("MockitoExampleTest"));
     }
 
-
     @Test
     public void shouldFilterOutMockitoPackage() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-            "org.test.MockitoSampleTest",
-            "org.mockito.Mockito"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes("org.test.MockitoSampleTest", "org.mockito.Mockito")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
@@ -55,100 +56,134 @@ public void shouldFilterOutMockitoPackage() {
 
     @Test
     public void shouldNotFilterOutTracesMiddleGoodTraces() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "org.test.MockitoSampleTest",
-                "org.test.TestSupport",
-                "org.mockito.Mockito",
-                "org.test.TestSupport",
-                "org.mockito.Mockito"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "org.test.MockitoSampleTest",
+                                "org.test.TestSupport",
+                                "org.mockito.Mockito",
+                                "org.test.TestSupport",
+                                "org.mockito.Mockito")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
-        Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.TestSupport", "org.test.TestSupport", "org.test.MockitoSampleTest"));
+        Assertions.assertThat(filtered)
+                .has(
+                        onlyThoseClasses(
+                                "org.test.TestSupport",
+                                "org.test.TestSupport",
+                                "org.test.MockitoSampleTest"));
     }
 
     @Test
     public void shouldKeepRunners() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "org.mockito.runners.Runner",
-                "junit.stuff",
-                "org.test.MockitoSampleTest",
-                "org.mockito.Mockito"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "org.mockito.runners.Runner",
+                                "junit.stuff",
+                                "org.test.MockitoSampleTest",
+                                "org.mockito.Mockito")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
-        Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "junit.stuff", "org.mockito.runners.Runner"));
+        Assertions.assertThat(filtered)
+                .has(
+                        onlyThoseClasses(
+                                "org.test.MockitoSampleTest",
+                                "junit.stuff",
+                                "org.mockito.runners.Runner"));
     }
 
     @Test
     public void shouldNotFilterElementsAboveMockitoJUnitRule() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)",
-                "org.mockito.runners.Runner",
-                "junit.stuff",
-                "org.test.MockitoSampleTest",
-                "org.mockito.internal.MockitoCore.verifyNoMoreInteractions",
-                "org.mockito.internal.debugging.LocationImpl"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)",
+                                "org.mockito.runners.Runner",
+                                "junit.stuff",
+                                "org.test.MockitoSampleTest",
+                                "org.mockito.internal.MockitoCore.verifyNoMoreInteractions",
+                                "org.mockito.internal.debugging.LocationImpl")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
-        Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "junit.stuff", "org.mockito.runners.Runner","org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)"));
+        Assertions.assertThat(filtered)
+                .has(
+                        onlyThoseClasses(
+                                "org.test.MockitoSampleTest",
+                                "junit.stuff",
+                                "org.mockito.runners.Runner",
+                                "org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:16)"));
     }
 
     @Test
     public void shouldKeepInternalRunners() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "org.mockito.internal.runners.Runner",
-                "org.test.MockitoSampleTest"
-        ).toTraceArray();
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "org.mockito.internal.runners.Runner", "org.test.MockitoSampleTest")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, false);
 
-        Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "org.mockito.internal.runners.Runner"));
+        Assertions.assertThat(filtered)
+                .has(
+                        onlyThoseClasses(
+                                "org.test.MockitoSampleTest",
+                                "org.mockito.internal.runners.Runner"));
     }
 
     @Test
     public void shouldStartFilteringAndKeepTop() {
-        //given
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "org.test.Good",
-                "org.mockito.internal.Bad",
-                "org.test.MockitoSampleTest"
-        ).toTraceArray();
-
-        //when
+        // given
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "org.test.Good",
+                                "org.mockito.internal.Bad",
+                                "org.test.MockitoSampleTest")
+                        .toTraceArray();
+
+        // when
         StackTraceElement[] filtered = filter.filter(t, true);
 
-        //then
-        Assertions.assertThat(filtered).has(onlyThoseClasses("org.test.MockitoSampleTest", "org.test.Good"));
+        // then
+        Assertions.assertThat(filtered)
+                .has(onlyThoseClasses("org.test.MockitoSampleTest", "org.test.Good"));
     }
 
     @Test
-    public void shouldKeepGoodTraceFromTheTopBecauseRealImplementationsOfSpiesSometimesThrowExceptions() {
-        StackTraceElement[] t = new TraceBuilder().classes(
-                "org.good.Trace",
-                "org.yet.another.good.Trace",
-                "org.mockito.internal.to.be.Filtered",
-                "org.test.MockitoSampleTest"
-        ).toTraceArray();
+    public void
+            shouldKeepGoodTraceFromTheTopBecauseRealImplementationsOfSpiesSometimesThrowExceptions() {
+        StackTraceElement[] t =
+                new TraceBuilder()
+                        .classes(
+                                "org.good.Trace",
+                                "org.yet.another.good.Trace",
+                                "org.mockito.internal.to.be.Filtered",
+                                "org.test.MockitoSampleTest")
+                        .toTraceArray();
 
         StackTraceElement[] filtered = filter.filter(t, true);
 
-        Assertions.assertThat(filtered).has(onlyThoseClasses(
-                "org.test.MockitoSampleTest",
-                "org.yet.another.good.Trace",
-                "org.good.Trace"
-                ));
+        Assertions.assertThat(filtered)
+                .has(
+                        onlyThoseClasses(
+                                "org.test.MockitoSampleTest",
+                                "org.yet.another.good.Trace",
+                                "org.good.Trace"));
     }
 
     @Test
     public void shouldReturnEmptyArrayWhenInputIsEmpty() throws Exception {
-        //when
+        // when
         StackTraceElement[] filtered = filter.filter(new StackTraceElement[0], false);
-        //then
+        // then
         assertEquals(0, filtered.length);
     }
 }
diff --git a/src/test/java/org/mockito/internal/exceptions/util/ScenarioPrinterTest.java b/src/test/java/org/mockito/internal/exceptions/util/ScenarioPrinterTest.java
index 3a897d164e..68df19372f 100644
--- a/src/test/java/org/mockito/internal/exceptions/util/ScenarioPrinterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/util/ScenarioPrinterTest.java
@@ -22,28 +22,26 @@ public class ScenarioPrinterTest extends TestBase {
 
     @Test
     public void shouldPrintInvocations() {
-        //given
+        // given
         Invocation verified = new InvocationBuilder().simpleMethod().verified().toInvocation();
         Invocation unverified = new InvocationBuilder().differentMethod().toInvocation();
 
-        //when
+        // when
         String out = sp.print((List) asList(verified, unverified));
 
-        //then
-        assertThat(out)
-            .contains("1. -> at")
-            .contains("2. [?]-> at");
+        // then
+        assertThat(out).contains("1. -> at").contains("2. [?]-> at");
     }
 
     @Test
     public void shouldNotPrintInvocationsWhenSingleUnwanted() {
-        //given
+        // given
         Invocation unverified = new InvocationBuilder().differentMethod().toInvocation();
 
-        //when
+        // when
         String out = sp.print((List) asList(unverified));
 
-        //then
+        // then
         assertThat(out).contains("Actually, above is the only interaction with this mock.");
     }
 }
diff --git a/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java b/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
index a17ec7f713..344621eead 100644
--- a/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
+++ b/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
@@ -36,7 +36,8 @@ public class DefaultMockitoFrameworkTest extends TestBase {
 
     private DefaultMockitoFramework framework = new DefaultMockitoFramework();
 
-    @After public void clearListeners() {
+    @After
+    public void clearListeners() {
         new StateMaster().clearMockitoListeners();
     }
 
@@ -52,7 +53,7 @@ public void prevents_removing_null_listener() {
 
     @Test
     public void ok_to_remove_unknown_listener() {
-        //it is safe to remove listener that was not added before
+        // it is safe to remove listener that was not added before
         framework.removeListener(new MockitoListener() {});
     }
 
@@ -60,26 +61,26 @@ public void ok_to_remove_unknown_listener() {
     public void ok_to_remove_listener_multiple_times() {
         MockitoListener listener = new MockitoListener() {};
 
-        //when
+        // when
         framework.addListener(listener);
 
-        //then it is ok to:
+        // then it is ok to:
         framework.removeListener(listener);
         framework.removeListener(listener);
     }
 
     @Test
     public void adds_creation_listener() {
-        //given creation listener is added
+        // given creation listener is added
         MockCreationListener listener = mock(MockCreationListener.class);
         framework.addListener(listener);
 
-        //when
+        // when
         MockSettings settings = withSettings().name("my list");
         List mock = mock(List.class, settings);
         Set mock2 = mock(Set.class);
 
-        //then
+        // then
         verify(listener).onMockCreated(eq(mock), any(MockCreationSettings.class));
         verify(listener).onMockCreated(eq(mock2), any(MockCreationSettings.class));
         verifyNoMoreInteractions(listener);
@@ -88,84 +89,88 @@ public void adds_creation_listener() {
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
     @Test
     public void removes_creation_listener() {
-        //given creation listener is added
+        // given creation listener is added
         MockCreationListener listener = mock(MockCreationListener.class);
         framework.addListener(listener);
 
-        //and hooked up correctly
+        // and hooked up correctly
         mock(List.class);
         verify(listener).onMockCreated(ArgumentMatchers.any(), any(MockCreationSettings.class));
 
-        //when
+        // when
         framework.removeListener(listener);
         mock(Set.class);
 
-        //then
+        // then
         verifyNoMoreInteractions(listener);
     }
 
-    @Test public void prevents_duplicate_listeners_of_the_same_type() {
-        //given creation listener is added
+    @Test
+    public void prevents_duplicate_listeners_of_the_same_type() {
+        // given creation listener is added
         framework.addListener(new MyListener());
 
-        assertThat(new Runnable() {
-            @Override
-            public void run() {
-                framework.addListener(new MyListener());
-            }
-        })  .throwsException(RedundantListenerException.class)
-            .throwsMessage("\n" +
-                    "Problems adding Mockito listener.\n" +
-                    "Listener of type 'MyListener' has already been added and not removed.\n" +
-                    "It indicates that previous listener was not removed according to the API.\n" +
-                    "When you add a listener, don't forget to remove the listener afterwards:\n" +
-                    "  Mockito.framework().removeListener(myListener);\n" +
-                    "For more information, see the javadoc for RedundantListenerException class.");
+        assertThat(
+                        new Runnable() {
+                            @Override
+                            public void run() {
+                                framework.addListener(new MyListener());
+                            }
+                        })
+                .throwsException(RedundantListenerException.class)
+                .throwsMessage(
+                        "\n"
+                                + "Problems adding Mockito listener.\n"
+                                + "Listener of type 'MyListener' has already been added and not removed.\n"
+                                + "It indicates that previous listener was not removed according to the API.\n"
+                                + "When you add a listener, don't forget to remove the listener afterwards:\n"
+                                + "  Mockito.framework().removeListener(myListener);\n"
+                                + "For more information, see the javadoc for RedundantListenerException class.");
     }
 
     @Test
     public void clearing_all_mocks_is_safe_regardless_of_mock_maker_type() {
         List mock = mock(List.class);
 
-        //expect
+        // expect
         assertTrue(mockingDetails(mock).isMock());
         framework.clearInlineMocks();
     }
 
     @Test
     public void clears_all_mocks() {
-        //clearing mocks only works with inline mocking
+        // clearing mocks only works with inline mocking
         assumeTrue(Plugins.getMockMaker() instanceof InlineMockMaker);
 
-        //given
+        // given
         List list1 = mock(List.class);
         assertTrue(mockingDetails(list1).isMock());
         List list2 = mock(List.class);
         assertTrue(mockingDetails(list2).isMock());
 
-        //when
+        // when
         framework.clearInlineMocks();
 
-        //then
+        // then
         assertFalse(mockingDetails(list1).isMock());
         assertFalse(mockingDetails(list2).isMock());
     }
 
     @Test
     public void clears_mock() {
-        //clearing mocks only works with inline mocking
+        // clearing mocks only works with inline mocking
         assumeTrue(Plugins.getMockMaker() instanceof InlineMockMaker);
 
-        //given
+        // given
         List list1 = mock(List.class);
         assertTrue(mockingDetails(list1).isMock());
         List list2 = mock(List.class);
         assertTrue(mockingDetails(list2).isMock());
 
-        //when
+        // when
         framework.clearInlineMock(list1);
 
-        //then
+        // then
         assertFalse(mockingDetails(list1).isMock());
         assertTrue(mockingDetails(list2).isMock());
     }
diff --git a/src/test/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractorTest.java b/src/test/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractorTest.java
index 25cc68c58c..154a7bc91b 100644
--- a/src/test/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractorTest.java
+++ b/src/test/java/org/mockito/internal/hamcrest/MatcherGenericTypeExtractorTest.java
@@ -18,79 +18,92 @@
 
 public class MatcherGenericTypeExtractorTest extends TestBase {
 
-    //traditional inner class for matcher
+    // traditional inner class for matcher
     private class IntMatcher extends BaseMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeTo(Description description) {}
     }
 
-    //static class with matcher
+    // static class with matcher
     private static class StaticIntMatcher extends BaseMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeTo(Description description) {}
     }
 
-    //static subclass
+    // static subclass
     private static class StaticIntMatcherSubclass extends StaticIntMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeTo(Description description) {}
     }
 
-    //non-generic
+    // non-generic
     @SuppressWarnings("rawtypes")
     private static class NonGenericMatcher extends BaseMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeTo(Description description) {}
     }
 
-    //Matcher interface implementation (instead of the BaseMatcher)
+    // Matcher interface implementation (instead of the BaseMatcher)
     private class IntMatcherFromInterface extends BaseMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeMismatch(Object item, Description mismatchDescription) {}
+
         public void describeTo(Description description) {}
     }
 
-    //Static Matcher interface implementation (instead of the BaseMatcher)
+    // Static Matcher interface implementation (instead of the BaseMatcher)
     private static class StaticIntMatcherFromInterface extends BaseMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeMismatch(Object item, Description mismatchDescription) {}
+
         public void describeTo(Description description) {}
     }
 
-    //non-generic matcher implementing the interface
+    // non-generic matcher implementing the interface
     @SuppressWarnings("rawtypes")
     private static class NonGenericMatcherFromInterface extends BaseMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeMismatch(Object item, Description mismatchDescription) {}
+
         public void describeTo(Description description) {}
     }
 
     private interface IMatcher extends Matcher {}
 
-    //non-generic matcher implementing the interface
-    private static class SubclassGenericMatcherFromInterface extends BaseMatcher implements Serializable, Cloneable, IMatcher {
+    // non-generic matcher implementing the interface
+    private static class SubclassGenericMatcherFromInterface extends BaseMatcher
+            implements Serializable, Cloneable, IMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeMismatch(Object item, Description mismatchDescription) {}
+
         public void describeTo(Description description) {}
     }
 
-    //I refuse to comment on the sanity of this case
+    // I refuse to comment on the sanity of this case
     private static class InsaneEdgeCase extends SubclassGenericMatcherFromInterface {}
 
     @Test
@@ -101,34 +114,39 @@ public void findsGenericType() {
         assertEquals(Integer.class, genericTypeOfMatcher(StaticIntMatcherSubclass.class));
         assertEquals(Integer.class, genericTypeOfMatcher(IntMatcherFromInterface.class));
         assertEquals(Integer.class, genericTypeOfMatcher(StaticIntMatcherFromInterface.class));
-        assertEquals(Integer.class, genericTypeOfMatcher(SubclassGenericMatcherFromInterface.class));
+        assertEquals(
+                Integer.class, genericTypeOfMatcher(SubclassGenericMatcherFromInterface.class));
         assertEquals(Integer.class, genericTypeOfMatcher(InsaneEdgeCase.class));
 
-        assertEquals(Integer.class, genericTypeOfMatcher(new BaseMatcher() {
-            public void describeTo(Description description) {
-            }
-
-            public boolean matches(Object o) {
-                return false;
-            }
-        }.getClass()));
-        assertEquals(Integer.class, genericTypeOfMatcher(new BaseMatcher() {
-            public void describeTo(Description description) {
-            }
-
-            public boolean matches(Object o) {
-                return false;
-            }
-
-            public void describeMismatch(Object item, Description mismatchDescription) {
-            }
-        }.getClass()));
+        assertEquals(
+                Integer.class,
+                genericTypeOfMatcher(
+                        new BaseMatcher() {
+                            public void describeTo(Description description) {}
+
+                            public boolean matches(Object o) {
+                                return false;
+                            }
+                        }.getClass()));
+        assertEquals(
+                Integer.class,
+                genericTypeOfMatcher(
+                        new BaseMatcher() {
+                            public void describeTo(Description description) {}
+
+                            public boolean matches(Object o) {
+                                return false;
+                            }
+
+                            public void describeMismatch(
+                                    Object item, Description mismatchDescription) {}
+                        }.getClass()));
 
         assertEquals(Object.class, genericTypeOfMatcher(Object.class));
         assertEquals(Object.class, genericTypeOfMatcher(String.class));
         assertEquals(Object.class, genericTypeOfMatcher(HashMap.class));
-        assertEquals(Object.class, genericTypeOfMatcher(new HashMap() {
-        }.getClass()));
+        assertEquals(
+                Object.class, genericTypeOfMatcher(new HashMap() {}.getClass()));
         assertEquals(Object.class, genericTypeOfMatcher(NonGenericMatcher.class));
         assertEquals(Object.class, genericTypeOfMatcher(NonGenericMatcherFromInterface.class));
     }
diff --git a/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java b/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java
index c9c17afb55..a95921bfcc 100644
--- a/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java
+++ b/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java
@@ -29,7 +29,6 @@
 import org.mockito.mock.MockCreationSettings;
 import org.mockito.stubbing.Answer;
 
-
 @RunWith(MockitoJUnitRunner.class)
 @SuppressWarnings("unchecked")
 public class InvocationNotifierHandlerTest {
@@ -38,7 +37,6 @@ public class InvocationNotifierHandlerTest {
     private static final OutOfMemoryError SOME_ERROR = new OutOfMemoryError();
     private static final Answer SOME_ANSWER = mock(Answer.class);
 
-
     @Mock private InvocationListener listener1;
     @Mock private InvocationListener listener2;
     @Spy private CustomListener customListener;
@@ -50,10 +48,12 @@ public class InvocationNotifierHandlerTest {
 
     @Before
     public void setUp() throws Exception {
-        notifier = new InvocationNotifierHandler>>(
-                mockHandler,
-                (MockCreationSettings>>) new MockSettingsImpl>>().invocationListeners(customListener, listener1, listener2)
-        );
+        notifier =
+                new InvocationNotifierHandler>>(
+                        mockHandler,
+                        (MockCreationSettings>>)
+                                new MockSettingsImpl>>()
+                                        .invocationListeners(customListener, listener1, listener2));
     }
 
     @Test
@@ -65,12 +65,15 @@ public void should_notify_all_listeners_when_calling_delegate_handler() throws T
         notifier.handle(invocation);
 
         // then
-        verify(listener1).reportInvocation(new NotifiedMethodInvocationReport(invocation, "returned value"));
-        verify(listener2).reportInvocation(new NotifiedMethodInvocationReport(invocation, "returned value"));
+        verify(listener1)
+                .reportInvocation(new NotifiedMethodInvocationReport(invocation, "returned value"));
+        verify(listener2)
+                .reportInvocation(new NotifiedMethodInvocationReport(invocation, "returned value"));
     }
 
     @Test
-    public void should_notify_all_listeners_when_called_delegate_handler_returns_ex() throws Throwable {
+    public void should_notify_all_listeners_when_called_delegate_handler_returns_ex()
+            throws Throwable {
         // given
         Exception computedException = new Exception("computed");
         given(mockHandler.handle(invocation)).willReturn(computedException);
@@ -79,12 +82,18 @@ public void should_notify_all_listeners_when_called_delegate_handler_returns_ex(
         notifier.handle(invocation);
 
         // then
-        verify(listener1).reportInvocation(new NotifiedMethodInvocationReport(invocation, (Object) computedException));
-        verify(listener2).reportInvocation(new NotifiedMethodInvocationReport(invocation, (Object) computedException));
+        verify(listener1)
+                .reportInvocation(
+                        new NotifiedMethodInvocationReport(invocation, (Object) computedException));
+        verify(listener2)
+                .reportInvocation(
+                        new NotifiedMethodInvocationReport(invocation, (Object) computedException));
     }
 
     @Test(expected = ParseException.class)
-    public void should_notify_all_listeners_when_called_delegate_handler_throws_exception_and_rethrow_it() throws Throwable {
+    public void
+            should_notify_all_listeners_when_called_delegate_handler_throws_exception_and_rethrow_it()
+                    throws Throwable {
         // given
         ParseException parseException = new ParseException("", 0);
         given(mockHandler.handle(invocation)).willThrow(parseException);
@@ -95,14 +104,20 @@ public void should_notify_all_listeners_when_called_delegate_handler_throws_exce
             fail();
         } finally {
             // then
-            verify(listener1).reportInvocation(new NotifiedMethodInvocationReport(invocation, parseException));
-            verify(listener2).reportInvocation(new NotifiedMethodInvocationReport(invocation, parseException));
+            verify(listener1)
+                    .reportInvocation(
+                            new NotifiedMethodInvocationReport(invocation, parseException));
+            verify(listener2)
+                    .reportInvocation(
+                            new NotifiedMethodInvocationReport(invocation, parseException));
         }
     }
 
     @Test
     public void should_report_listener_exception() throws Throwable {
-        willThrow(new NullPointerException()).given(customListener).reportInvocation(any(MethodInvocationReport.class));
+        willThrow(new NullPointerException())
+                .given(customListener)
+                .reportInvocation(any(MethodInvocationReport.class));
 
         try {
             notifier.handle(invocation);
@@ -117,7 +132,8 @@ public void should_report_listener_exception() throws Throwable {
     }
 
     @Test
-    public void should_delegate_all_MockHandlerInterface_to_the_parameterized_MockHandler() throws Exception {
+    public void should_delegate_all_MockHandlerInterface_to_the_parameterized_MockHandler()
+            throws Exception {
         notifier.getInvocationContainer();
         notifier.getMockSettings();
 
diff --git a/src/test/java/org/mockito/internal/handler/MockHandlerFactoryTest.java b/src/test/java/org/mockito/internal/handler/MockHandlerFactoryTest.java
index 9b999740ed..d82bc7829e 100644
--- a/src/test/java/org/mockito/internal/handler/MockHandlerFactoryTest.java
+++ b/src/test/java/org/mockito/internal/handler/MockHandlerFactoryTest.java
@@ -26,37 +26,39 @@ public class MockHandlerFactoryTest extends TestBase {
     private final IMethods mock = Mockito.mock(IMethods.class);
 
     @Test
-    //see issue 331
+    // see issue 331
     public void handle_result_must_not_be_null_for_primitives() throws Throwable {
-        //given:
-        MockCreationSettings settings = (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(null));
+        // given:
+        MockCreationSettings settings =
+                (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(null));
         MockHandler handler = createMockHandler(settings);
 
         mock.intReturningMethod();
         Invocation invocation = super.getLastInvocation();
 
-        //when:
+        // when:
         Object result = handler.handle(invocation);
 
-        //then null value is not a valid result for a primitive
+        // then null value is not a valid result for a primitive
         assertNotNull(result);
         assertEquals(0, result);
     }
 
     @Test
-    //see issue 331
+    // see issue 331
     public void valid_handle_result_is_permitted() throws Throwable {
-        //given:
-        MockCreationSettings settings = (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(123));
-        MockHandler handler =  createMockHandler(settings);
+        // given:
+        MockCreationSettings settings =
+                (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(123));
+        MockHandler handler = createMockHandler(settings);
 
         mock.intReturningMethod();
         Invocation invocation = super.getLastInvocation();
 
-        //when:
+        // when:
         Object result = handler.handle(invocation);
 
-        //then
+        // then
         assertEquals(123, result);
     }
 }
diff --git a/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java b/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java
index 853de46f12..c0fed25fb1 100644
--- a/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java
+++ b/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java
@@ -35,7 +35,8 @@
 @SuppressWarnings({"unchecked", "serial"})
 public class MockHandlerImplTest extends TestBase {
 
-    private StubbedInvocationMatcher stubbedInvocationMatcher = mock(StubbedInvocationMatcher.class);
+    private StubbedInvocationMatcher stubbedInvocationMatcher =
+            mock(StubbedInvocationMatcher.class);
     private Invocation invocation = mock(Invocation.class);
 
     @Test
@@ -45,11 +46,13 @@ public void should_remove_verification_mode_even_when_invalid_matchers() throws
         @SuppressWarnings("rawtypes")
         MockHandlerImpl handler = new MockHandlerImpl(new MockSettingsImpl());
         mockingProgress().verificationStarted(VerificationModeFactory.atLeastOnce());
-        handler.matchersBinder = new MatchersBinder() {
-            public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
-                throw new InvalidUseOfMatchersException();
-            }
-        };
+        handler.matchersBinder =
+                new MatchersBinder() {
+                    public InvocationMatcher bindMatchers(
+                            ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
+                        throw new InvalidUseOfMatchersException();
+                    }
+                };
 
         try {
             // when
@@ -63,12 +66,14 @@ public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStor
         assertNull(mockingProgress().pullVerificationMode());
     }
 
-
     @Test(expected = MockitoException.class)
-    public void should_throw_mockito_exception_when_invocation_handler_throws_anything() throws Throwable {
+    public void should_throw_mockito_exception_when_invocation_handler_throws_anything()
+            throws Throwable {
         // given
         InvocationListener throwingListener = mock(InvocationListener.class);
-        doThrow(new Throwable()).when(throwingListener).reportInvocation(any(MethodInvocationReport.class));
+        doThrow(new Throwable())
+                .when(throwingListener)
+                .reportInvocation(any(MethodInvocationReport.class));
         MockHandlerImpl handler = create_correctly_stubbed_handler(throwingListener);
 
         // when
@@ -82,12 +87,16 @@ public void should_report_bogus_default_answer() throws Throwable {
         given(mockSettings.getDefaultAnswer()).willReturn(new Returns(AWrongType.WRONG_TYPE));
 
         @SuppressWarnings("unused") // otherwise cast is not done
-        String there_should_not_be_a_CCE_here = (String) handler.handle(
-                new InvocationBuilder().method(Object.class.getDeclaredMethod("toString")).toInvocation()
-        );
+        String there_should_not_be_a_CCE_here =
+                (String)
+                        handler.handle(
+                                new InvocationBuilder()
+                                        .method(Object.class.getDeclaredMethod("toString"))
+                                        .toInvocation());
     }
 
-    private MockHandlerImpl create_correctly_stubbed_handler(InvocationListener throwingListener) {
+    private MockHandlerImpl create_correctly_stubbed_handler(
+            InvocationListener throwingListener) {
         MockHandlerImpl handler = create_handler_with_listeners(throwingListener);
         stub_ordinary_invocation_with_given_return_value(handler);
         return handler;
@@ -97,18 +106,18 @@ private void stub_ordinary_invocation_with_given_return_value(MockHandlerImpl
         stub_ordinary_invocation_with_invocation_matcher(handler, stubbedInvocationMatcher);
     }
 
-
-    private void stub_ordinary_invocation_with_invocation_matcher(MockHandlerImpl handler, StubbedInvocationMatcher value) {
+    private void stub_ordinary_invocation_with_invocation_matcher(
+            MockHandlerImpl handler, StubbedInvocationMatcher value) {
         handler.invocationContainer = mock(InvocationContainerImpl.class);
         given(handler.invocationContainer.findAnswerFor(any(Invocation.class))).willReturn(value);
     }
 
-
     private MockHandlerImpl create_handler_with_listeners(InvocationListener... listener) {
         @SuppressWarnings("rawtypes")
         MockHandlerImpl handler = new MockHandlerImpl(mock(MockSettingsImpl.class));
         handler.matchersBinder = mock(MatchersBinder.class);
-        given(handler.getMockSettings().getInvocationListeners()).willReturn(Arrays.asList(listener));
+        given(handler.getMockSettings().getInvocationListeners())
+                .willReturn(Arrays.asList(listener));
         return handler;
     }
 
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
index 8c5fedbb50..281d41b3c3 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
@@ -28,7 +28,7 @@ public class InvocationBuilder {
 
     private String methodName = "simpleMethod";
     private int sequenceNumber = 0;
-    private Object[] args = new Object[]{};
+    private Object[] args = new Object[] {};
     private Object mock = Mockito.mock(IMethods.class);
     private Method method;
     private boolean verified;
@@ -56,27 +56,38 @@ public Invocation toInvocation() {
             }
 
             try {
-                method = IMethods.class.getMethod(methodName, argTypes.toArray(new Class[argTypes.size()]));
+                method =
+                        IMethods.class.getMethod(
+                                methodName, argTypes.toArray(new Class[argTypes.size()]));
             } catch (Exception e) {
-                throw new RuntimeException("builder only creates invocations of IMethods interface", e);
+                throw new RuntimeException(
+                        "builder only creates invocations of IMethods interface", e);
             }
         }
 
-        Invocation i = createInvocation(new MockStrongReference(mock, false),
-            new SerializableMethod(method),
-            args,
-            NO_OP,
-            location == null ? new LocationImpl() : location,
-            1);
+        Invocation i =
+                createInvocation(
+                        new MockStrongReference(mock, false),
+                        new SerializableMethod(method),
+                        args,
+                        NO_OP,
+                        location == null ? new LocationImpl() : location,
+                        1);
         if (verified) {
             i.markVerified();
         }
         return i;
     }
 
-    protected Invocation createInvocation(MockReference mockRef, MockitoMethod mockitoMethod, Object[] arguments,
-                                          RealMethod realMethod, Location location, int sequenceNumber) {
-        return new InterceptedInvocation(mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber);
+    protected Invocation createInvocation(
+            MockReference mockRef,
+            MockitoMethod mockitoMethod,
+            Object[] arguments,
+            RealMethod realMethod,
+            Location location,
+            int sequenceNumber) {
+        return new InterceptedInvocation(
+                mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber);
     }
 
     public InvocationBuilder method(String methodName) {
@@ -95,7 +106,7 @@ public InvocationBuilder args(Object... args) {
     }
 
     public InvocationBuilder arg(Object o) {
-        this.args = new Object[]{o};
+        this.args = new Object[] {o};
         return this;
     }
 
@@ -132,14 +143,16 @@ public InvocationBuilder argTypes(Class... argTypes) {
     }
 
     public InvocationBuilder location(final String location) {
-        this.location = new Location() {
-            public String toString() {
-                return location;
-            }
-            public String getSourceFile() {
-                return "SomeClass";
-            }
-        };
+        this.location =
+                new Location() {
+                    public String toString() {
+                        return location;
+                    }
+
+                    public String getSourceFile() {
+                        return "SomeClass";
+                    }
+                };
         return this;
     }
 }
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java b/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java
index 4cb228af72..55b721e9f2 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationMarkerTest.java
@@ -19,38 +19,40 @@ public class InvocationMarkerTest extends TestBase {
 
     @Test
     public void shouldMarkInvocationAsVerified() {
-        //given
+        // given
         Invocation i = new InvocationBuilder().toInvocation();
         InvocationMatcher im = new InvocationBuilder().toInvocationMatcher();
         assertFalse(i.isVerified());
 
-        //when
+        // when
         InvocationMarker.markVerified(Arrays.asList(i), im);
 
-        //then
+        // then
         assertTrue(i.isVerified());
     }
 
     @Test
     public void shouldCaptureArguments() {
-        //given
+        // given
         Invocation i = new InvocationBuilder().toInvocation();
         final AtomicReference box = new AtomicReference();
-        MatchableInvocation c = new InvocationMatcher(i) {
-            public void captureArgumentsFrom(Invocation i) {
-                box.set(i);
-            }};
+        MatchableInvocation c =
+                new InvocationMatcher(i) {
+                    public void captureArgumentsFrom(Invocation i) {
+                        box.set(i);
+                    }
+                };
 
-        //when
+        // when
         InvocationMarker.markVerified(Arrays.asList(i), c);
 
-        //then
+        // then
         assertEquals(i, box.get());
     }
 
     @Test
     public void shouldMarkInvocationsAsVerifiedInOrder() {
-        //given
+        // given
         InOrderContextImpl context = new InOrderContextImpl();
 
         Invocation i = new InvocationBuilder().toInvocation();
@@ -58,10 +60,10 @@ public void shouldMarkInvocationsAsVerifiedInOrder() {
         assertFalse(context.isVerified(i));
         assertFalse(i.isVerified());
 
-        //when
+        // when
         InvocationMarker.markVerifiedInOrder(Arrays.asList(i), im, context);
 
-        //then
+        // then
         assertTrue(context.isVerified(i));
         assertTrue(i.isVerified());
     }
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationMatcherTest.java b/src/test/java/org/mockito/internal/invocation/InvocationMatcherTest.java
index 5434ce35f2..0b3d09d5f1 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationMatcherTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationMatcherTest.java
@@ -55,8 +55,10 @@ public void should_be_a_citizen_of_hashes() throws Exception {
 
     @Test
     public void should_not_equal_if_number_of_arguments_differ() throws Exception {
-        InvocationMatcher withOneArg = new InvocationMatcher(new InvocationBuilder().args("test").toInvocation());
-        InvocationMatcher withTwoArgs = new InvocationMatcher(new InvocationBuilder().args("test", 100).toInvocation());
+        InvocationMatcher withOneArg =
+                new InvocationMatcher(new InvocationBuilder().args("test").toInvocation());
+        InvocationMatcher withTwoArgs =
+                new InvocationMatcher(new InvocationBuilder().args("test", 100).toInvocation());
 
         assertFalse(withOneArg.equals(null));
         assertFalse(withOneArg.equals(withTwoArgs));
@@ -65,9 +67,11 @@ public void should_not_equal_if_number_of_arguments_differ() throws Exception {
     @Test
     public void should_to_string_with_matchers() throws Exception {
         ArgumentMatcher m = NotNull.NOT_NULL;
-        InvocationMatcher notNull = new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(m));
+        InvocationMatcher notNull =
+                new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(m));
         ArgumentMatcher mTwo = new Equals('x');
-        InvocationMatcher equals = new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(mTwo));
+        InvocationMatcher equals =
+                new InvocationMatcher(new InvocationBuilder().toInvocation(), asList(mTwo));
 
         assertThat(notNull.toString()).contains("simpleMethod(notNull())");
         assertThat(equals.toString()).contains("simpleMethod('x')");
@@ -90,19 +94,23 @@ public void should_not_be_similar_to_verified_invocation() throws Exception {
 
     @Test
     public void should_not_be_similar_if_mocks_are_different() throws Exception {
-        Invocation onDifferentMock = new InvocationBuilder().simpleMethod().mock("different mock").toInvocation();
+        Invocation onDifferentMock =
+                new InvocationBuilder().simpleMethod().mock("different mock").toInvocation();
         assertFalse(simpleMethod.hasSimilarMethod(onDifferentMock));
     }
 
     @Test
-    public void should_not_be_similar_if_is_overloaded_but_used_with_the_same_arg() throws Exception {
+    public void should_not_be_similar_if_is_overloaded_but_used_with_the_same_arg()
+            throws Exception {
         Method method = IMethods.class.getMethod("simpleMethod", String.class);
         Method overloadedMethod = IMethods.class.getMethod("simpleMethod", Object.class);
 
         String sameArg = "test";
 
-        InvocationMatcher invocation = new InvocationBuilder().method(method).arg(sameArg).toInvocationMatcher();
-        Invocation overloadedInvocation = new InvocationBuilder().method(overloadedMethod).arg(sameArg).toInvocation();
+        InvocationMatcher invocation =
+                new InvocationBuilder().method(method).arg(sameArg).toInvocationMatcher();
+        Invocation overloadedInvocation =
+                new InvocationBuilder().method(overloadedMethod).arg(sameArg).toInvocation();
 
         assertFalse(invocation.hasSimilarMethod(overloadedInvocation));
     }
@@ -112,76 +120,84 @@ public void should_be_similar_if_is_overloaded_but_used_with_different_arg() thr
         Method method = IMethods.class.getMethod("simpleMethod", String.class);
         Method overloadedMethod = IMethods.class.getMethod("simpleMethod", Object.class);
 
-        InvocationMatcher invocation = new InvocationBuilder().mock(mock).method(method).arg("foo").toInvocationMatcher();
-        Invocation overloadedInvocation = new InvocationBuilder().mock(mock).method(overloadedMethod).arg("bar").toInvocation();
+        InvocationMatcher invocation =
+                new InvocationBuilder().mock(mock).method(method).arg("foo").toInvocationMatcher();
+        Invocation overloadedInvocation =
+                new InvocationBuilder()
+                        .mock(mock)
+                        .method(overloadedMethod)
+                        .arg("bar")
+                        .toInvocation();
 
         assertTrue(invocation.hasSimilarMethod(overloadedInvocation));
     }
 
     @Test
     public void should_capture_arguments_from_invocation() throws Exception {
-        //given
+        // given
         Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
         CapturingMatcher capturingMatcher = new CapturingMatcher();
-        InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("1"), capturingMatcher));
+        InvocationMatcher invocationMatcher =
+                new InvocationMatcher(invocation, (List) asList(new Equals("1"), capturingMatcher));
 
-        //when
+        // when
         invocationMatcher.captureArgumentsFrom(invocation);
 
-        //then
+        // then
         assertEquals(1, capturingMatcher.getAllValues().size());
         assertEquals(100, capturingMatcher.getLastValue());
     }
 
     @Test
     public void should_match_varargs_using_any_varargs() throws Exception {
-        //given
+        // given
         mock.varargs("1", "2");
         Invocation invocation = getLastInvocation();
         InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(ANY));
 
-        //when
+        // when
         boolean match = invocationMatcher.matches(invocation);
 
-        //then
+        // then
         assertTrue(match);
     }
 
     @Test
     public void should_capture_varargs_as_vararg() throws Exception {
-        //given
+        // given
         mock.mixedVarargs(1, "a", "b");
         Invocation invocation = getLastInvocation();
         CapturingMatcher m = new CapturingMatcher();
-        InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, Arrays.asList(new Equals(1), m));
+        InvocationMatcher invocationMatcher =
+                new InvocationMatcher(invocation, Arrays.asList(new Equals(1), m));
 
-        //when
+        // when
         invocationMatcher.captureArgumentsFrom(invocation);
 
-        //then
+        // then
         Assertions.assertThat(m.getAllValues()).containsExactly("a", "b");
     }
 
-    @Test  // like using several time the captor in the vararg
+    @Test // like using several time the captor in the vararg
     public void should_capture_arguments_when_args_count_does_NOT_match() throws Exception {
-        //given
+        // given
         mock.varargs();
         Invocation invocation = getLastInvocation();
 
-        //when
-        InvocationMatcher invocationMatcher = new InvocationMatcher(invocation,(List) asList(ANY));
+        // when
+        InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(ANY));
 
-        //then
+        // then
         invocationMatcher.captureArgumentsFrom(invocation);
     }
 
     @Test
     public void should_create_from_invocations() throws Exception {
-        //given
+        // given
         Invocation i = new InvocationBuilder().toInvocation();
-        //when
+        // when
         List out = InvocationMatcher.createFrom(asList(i));
-        //then
+        // then
         assertEquals(1, out.size());
         assertEquals(i, out.get(0).getInvocation());
     }
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java b/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
index d962d8a75c..fd02ac5769 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
@@ -24,7 +24,6 @@
 import org.mockitousage.IMethods;
 import org.mockitoutil.TestBase;
 
-
 public class InvocationsFinderTest extends TestBase {
 
     private LinkedList invocations = new LinkedList();
@@ -32,26 +31,36 @@ public class InvocationsFinderTest extends TestBase {
     private Invocation simpleMethodInvocationTwo;
     private Invocation differentMethodInvocation;
 
-
     private final InOrderContext context = new InOrderContextImpl();
 
     @Mock private IMethods mock;
 
     @Before
     public void setup() throws Exception {
-        simpleMethodInvocation = new InvocationBuilder().mock(mock).simpleMethod().seq(1).toInvocation();
-        simpleMethodInvocationTwo = new InvocationBuilder().mock(mock).simpleMethod().seq(2).toInvocation();
-        differentMethodInvocation = new InvocationBuilder().mock(mock).differentMethod().seq(3).toInvocation();
-        invocations.addAll(Arrays.asList(simpleMethodInvocation, simpleMethodInvocationTwo, differentMethodInvocation));
-
+        simpleMethodInvocation =
+                new InvocationBuilder().mock(mock).simpleMethod().seq(1).toInvocation();
+        simpleMethodInvocationTwo =
+                new InvocationBuilder().mock(mock).simpleMethod().seq(2).toInvocation();
+        differentMethodInvocation =
+                new InvocationBuilder().mock(mock).differentMethod().seq(3).toInvocation();
+        invocations.addAll(
+                Arrays.asList(
+                        simpleMethodInvocation,
+                        simpleMethodInvocationTwo,
+                        differentMethodInvocation));
     }
 
     @Test
     public void shouldFindActualInvocations() throws Exception {
-        List actual = InvocationsFinder.findInvocations(invocations, new InvocationMatcher(simpleMethodInvocation));
-        Assertions.assertThat(actual).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
-
-        actual = InvocationsFinder.findInvocations(invocations, new InvocationMatcher(differentMethodInvocation));
+        List actual =
+                InvocationsFinder.findInvocations(
+                        invocations, new InvocationMatcher(simpleMethodInvocation));
+        Assertions.assertThat(actual)
+                .containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
+
+        actual =
+                InvocationsFinder.findInvocations(
+                        invocations, new InvocationMatcher(differentMethodInvocation));
         Assertions.assertThat(actual).containsSequence(differentMethodInvocation);
     }
 
@@ -70,60 +79,75 @@ public void shouldFindFirstUnverifiedInvocation() throws Exception {
 
     @Test
     public void shouldFindFirstUnverifiedInOrder() throws Exception {
-        //given
+        // given
         InOrderContextImpl context = new InOrderContextImpl();
-        assertSame(simpleMethodInvocation, InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
+        assertSame(
+                simpleMethodInvocation,
+                InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
 
-        //when
+        // when
         context.markVerified(simpleMethodInvocationTwo);
         context.markVerified(simpleMethodInvocation);
 
-        //then
-        assertSame(differentMethodInvocation, InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
+        // then
+        assertSame(
+                differentMethodInvocation,
+                InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
 
-        //when
+        // when
         context.markVerified(differentMethodInvocation);
 
-        //then
+        // then
         assertNull(InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
     }
 
     @Test
     public void shouldFindFirstUnverifiedInOrderAndRespectSequenceNumber() throws Exception {
-        //given
+        // given
         InOrderContextImpl context = new InOrderContextImpl();
-        assertSame(simpleMethodInvocation, InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
+        assertSame(
+                simpleMethodInvocation,
+                InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
 
-        //when
-        //skipping verification of first invocation, then:
+        // when
+        // skipping verification of first invocation, then:
         context.markVerified(simpleMethodInvocationTwo);
         context.markVerified(differentMethodInvocation);
 
-        //then
+        // then
         assertSame(null, InvocationsFinder.findFirstUnverifiedInOrder(context, invocations));
     }
 
     @Test
     public void shouldFindFirstUnverifiedInvocationOnMock() throws Exception {
-        assertSame(simpleMethodInvocation, InvocationsFinder.findFirstUnverified(invocations, simpleMethodInvocation.getMock()));
+        assertSame(
+                simpleMethodInvocation,
+                InvocationsFinder.findFirstUnverified(
+                        invocations, simpleMethodInvocation.getMock()));
         assertNull(InvocationsFinder.findFirstUnverified(invocations, "different mock"));
     }
 
     @Test
     public void shouldFindFirstSimilarInvocationByName() throws Exception {
-        Invocation overloadedSimpleMethod = new InvocationBuilder().mock(mock).simpleMethod().arg("test").toInvocation();
+        Invocation overloadedSimpleMethod =
+                new InvocationBuilder().mock(mock).simpleMethod().arg("test").toInvocation();
 
-        Invocation found = InvocationsFinder.findSimilarInvocation(invocations, new InvocationMatcher(overloadedSimpleMethod));
+        Invocation found =
+                InvocationsFinder.findSimilarInvocation(
+                        invocations, new InvocationMatcher(overloadedSimpleMethod));
         assertSame(found, simpleMethodInvocation);
     }
 
     @Test
     public void shouldFindInvocationWithTheSameMethod() throws Exception {
-        Invocation overloadedDifferentMethod = new InvocationBuilder().differentMethod().arg("test").toInvocation();
+        Invocation overloadedDifferentMethod =
+                new InvocationBuilder().differentMethod().arg("test").toInvocation();
 
         invocations.add(overloadedDifferentMethod);
 
-        Invocation found = InvocationsFinder.findSimilarInvocation(invocations, new InvocationMatcher(overloadedDifferentMethod));
+        Invocation found =
+                InvocationsFinder.findSimilarInvocation(
+                        invocations, new InvocationMatcher(overloadedDifferentMethod));
         assertSame(found, overloadedDifferentMethod);
     }
 
@@ -137,22 +161,32 @@ public void shouldGetLastStackTrace() throws Exception {
 
     @Test
     public void shouldFindAllMatchingUnverifiedChunks() throws Exception {
-        List allMatching = InvocationsFinder.findAllMatchingUnverifiedChunks(invocations, new InvocationMatcher(simpleMethodInvocation), context);
-        Assertions.assertThat(allMatching).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
+        List allMatching =
+                InvocationsFinder.findAllMatchingUnverifiedChunks(
+                        invocations, new InvocationMatcher(simpleMethodInvocation), context);
+        Assertions.assertThat(allMatching)
+                .containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
 
         context.markVerified(simpleMethodInvocation);
-        allMatching = InvocationsFinder.findAllMatchingUnverifiedChunks(invocations, new InvocationMatcher(simpleMethodInvocation), context);
+        allMatching =
+                InvocationsFinder.findAllMatchingUnverifiedChunks(
+                        invocations, new InvocationMatcher(simpleMethodInvocation), context);
         Assertions.assertThat(allMatching).containsSequence(simpleMethodInvocationTwo);
 
         context.markVerified(simpleMethodInvocationTwo);
-        allMatching = InvocationsFinder.findAllMatchingUnverifiedChunks(invocations, new InvocationMatcher(simpleMethodInvocation), context);
+        allMatching =
+                InvocationsFinder.findAllMatchingUnverifiedChunks(
+                        invocations, new InvocationMatcher(simpleMethodInvocation), context);
         assertTrue(allMatching.isEmpty());
     }
 
     @Test
     public void shouldFindMatchingChunk() throws Exception {
-        List chunk = InvocationsFinder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 2, context);
-        Assertions.assertThat(chunk).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
+        List chunk =
+                InvocationsFinder.findMatchingChunk(
+                        invocations, new InvocationMatcher(simpleMethodInvocation), 2, context);
+        Assertions.assertThat(chunk)
+                .containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo);
     }
 
     @Test
@@ -160,8 +194,14 @@ public void shouldReturnAllChunksWhenModeIsAtLeastOnce() throws Exception {
         Invocation simpleMethodInvocationThree = new InvocationBuilder().mock(mock).toInvocation();
         invocations.add(simpleMethodInvocationThree);
 
-        List chunk = InvocationsFinder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
-        Assertions.assertThat(chunk).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree);
+        List chunk =
+                InvocationsFinder.findMatchingChunk(
+                        invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
+        Assertions.assertThat(chunk)
+                .containsSequence(
+                        simpleMethodInvocation,
+                        simpleMethodInvocationTwo,
+                        simpleMethodInvocationThree);
     }
 
     @Test
@@ -169,8 +209,14 @@ public void shouldReturnAllChunksWhenWantedCountDoesntMatch() throws Exception {
         Invocation simpleMethodInvocationThree = new InvocationBuilder().mock(mock).toInvocation();
         invocations.add(simpleMethodInvocationThree);
 
-        List chunk = InvocationsFinder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
-        Assertions.assertThat(chunk).containsSequence(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree);
+        List chunk =
+                InvocationsFinder.findMatchingChunk(
+                        invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
+        Assertions.assertThat(chunk)
+                .containsSequence(
+                        simpleMethodInvocation,
+                        simpleMethodInvocationTwo,
+                        simpleMethodInvocationThree);
     }
 
     @Test
@@ -188,11 +234,17 @@ public void shouldFindPreviousInOrder() throws Exception {
     @Test
     public void shouldFindAllStackTraces() {
         List all = InvocationsFinder.getAllLocations(invocations);
-        Assertions.assertThat(all).contains(simpleMethodInvocation.getLocation(), simpleMethodInvocationTwo.getLocation(), differentMethodInvocation.getLocation());
+        Assertions.assertThat(all)
+                .contains(
+                        simpleMethodInvocation.getLocation(),
+                        simpleMethodInvocationTwo.getLocation(),
+                        differentMethodInvocation.getLocation());
     }
 
     @Test
     public void shouldNotFindLocationsForEmptyInvocationsList() {
-        Assertions.assertThat(InvocationsFinder.getAllLocations(Collections.emptyList())).isEmpty();
+        Assertions.assertThat(
+                        InvocationsFinder.getAllLocations(Collections.emptyList()))
+                .isEmpty();
     }
 }
diff --git a/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
index b29345984b..b79a1fc082 100644
--- a/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
+++ b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
@@ -33,8 +33,7 @@
 @SuppressWarnings("unchecked")
 public class MatcherApplicationStrategyTest extends TestBase {
 
-    @Mock
-    IMethods mock;
+    @Mock IMethods mock;
     private Invocation invocation;
     private List matchers;
 
@@ -52,7 +51,9 @@ public void shouldKnowWhenActualArgsSizeIsDifferent1() {
         matchers = asList(new Equals("1"));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_FALSE);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(RETURN_ALWAYS_FALSE);
 
         // then
         assertFalse(match);
@@ -65,7 +66,9 @@ public void shouldKnowWhenActualArgsSizeIsDifferent2() {
         matchers = asList(new Equals("1"));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
 
         // then
         assertTrue(match);
@@ -78,7 +81,9 @@ public void shouldKnowWhenActualArgsSizeIsDifferent() {
         matchers = asList(new Equals("1"));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
 
         // then
         assertFalse(match);
@@ -91,7 +96,9 @@ public void shouldKnowWhenMatchersSizeIsDifferent() {
         matchers = asList(new Equals("1"), new Equals("2"));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(RETURN_ALWAYS_TRUE);
 
         // then
         assertFalse(match);
@@ -104,7 +111,9 @@ public void shouldKnowWhenVarargsMatch() {
         matchers = asList(new Equals("1"), Any.ANY, new InstanceOf(String.class));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(recordAction);
 
         // then
         assertTrue(match);
@@ -117,7 +126,9 @@ public void shouldAllowAnyVarargMatchEntireVararg() {
         matchers = asList(ANY);
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(recordAction);
 
         // then
         assertTrue(match);
@@ -130,7 +141,9 @@ public void shouldNotAllowAnyObjectWithMixedVarargs() {
         matchers = asList(new Equals(1));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(recordAction);
 
         // then
         assertFalse(match);
@@ -143,7 +156,9 @@ public void shouldAllowAnyObjectWithMixedVarargs() {
         matchers = asList(new Equals(1), ANY);
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(recordAction);
 
         // then
         assertTrue(match);
@@ -156,7 +171,9 @@ public void shouldAnyObjectVarargDealWithDifferentSizeOfArgs() {
         matchers = asList(new Equals(1));
 
         // when
-        boolean match = getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        boolean match =
+                getMatcherApplicationStrategyFor(invocation, matchers)
+                        .forEachMatcherAndArgument(recordAction);
 
         // then
         assertFalse(match);
@@ -171,11 +188,11 @@ public void shouldMatchAnyVarargEvenIfOneOfTheArgsIsNull() {
         matchers = asList(new Equals(null), ANY);
 
         // when
-        getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        getMatcherApplicationStrategyFor(invocation, matchers)
+                .forEachMatcherAndArgument(recordAction);
 
         // then
         recordAction.assertContainsExactly(new Equals(null), ANY, ANY);
-
     }
 
     @Test
@@ -185,7 +202,8 @@ public void shouldMatchAnyVarargEvenIfMatcherIsDecorated() {
         matchers = asList(ANY);
 
         // when
-        getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        getMatcherApplicationStrategyFor(invocation, matchers)
+                .forEachMatcherAndArgument(recordAction);
 
         // then
         recordAction.assertContainsExactly(ANY, ANY);
@@ -199,7 +217,8 @@ public void shouldMatchAnyVarargEvenIfMatcherIsWrappedInHamcrestMatcher() {
         matchers = asList(argumentMatcher);
 
         // when
-        getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+        getMatcherApplicationStrategyFor(invocation, matchers)
+                .forEachMatcherAndArgument(recordAction);
 
         // then
         recordAction.assertContainsExactly(argumentMatcher, argumentMatcher);
@@ -209,6 +228,7 @@ class IntMatcher extends BaseMatcher implements VarargMatcher {
         public boolean matches(Object o) {
             return true;
         }
+
         public void describeTo(Description description) {}
     }
 
@@ -240,18 +260,19 @@ public void assertContainsExactly(ArgumentMatcher... matchers) {
         }
     }
 
-    private static final ArgumentMatcherAction RETURN_ALWAYS_TRUE = new ArgumentMatcherAction() {
-        @Override
-        public boolean apply(ArgumentMatcher matcher, Object argument) {
-            return true;
-        }
-    };
-
-    private static final ArgumentMatcherAction RETURN_ALWAYS_FALSE = new ArgumentMatcherAction() {
-        @Override
-        public boolean apply(ArgumentMatcher matcher, Object argument) {
-            return false;
-        }
-    };
-
+    private static final ArgumentMatcherAction RETURN_ALWAYS_TRUE =
+            new ArgumentMatcherAction() {
+                @Override
+                public boolean apply(ArgumentMatcher matcher, Object argument) {
+                    return true;
+                }
+            };
+
+    private static final ArgumentMatcherAction RETURN_ALWAYS_FALSE =
+            new ArgumentMatcherAction() {
+                @Override
+                public boolean apply(ArgumentMatcher matcher, Object argument) {
+                    return false;
+                }
+            };
 }
diff --git a/src/test/java/org/mockito/internal/invocation/SerializableMethodTest.java b/src/test/java/org/mockito/internal/invocation/SerializableMethodTest.java
index 69a241bd9f..bbf7eb9890 100644
--- a/src/test/java/org/mockito/internal/invocation/SerializableMethodTest.java
+++ b/src/test/java/org/mockito/internal/invocation/SerializableMethodTest.java
@@ -14,7 +14,6 @@
 import org.junit.Test;
 import org.mockitoutil.TestBase;
 
-
 public class SerializableMethodTest extends TestBase {
 
     private MockitoMethod method;
@@ -70,6 +69,6 @@ public void shouldNotBeEqualForSameMethodFromTwoDifferentClasses() throws Except
         assertFalse(new SerializableMethod(testBaseToStringMethod).equals(method));
     }
 
-    //TODO: add tests for generated equals() method
+    // TODO: add tests for generated equals() method
 
 }
diff --git a/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java b/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
index 94b4a2346b..0a29cee3ae 100644
--- a/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
+++ b/src/test/java/org/mockito/internal/invocation/TypeSafeMatchingTest.java
@@ -25,11 +25,9 @@ public class TypeSafeMatchingTest {
 
     private static final Object NOT_A_COMPARABLE = new Object();
 
-    @Rule
-    public MockitoRule mockitoRule = MockitoJUnit.rule();
+    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
 
-    @Mock
-    public IMethods mock;
+    @Mock public IMethods mock;
 
     /**
      * Should not throw an {@link NullPointerException}
@@ -40,7 +38,6 @@ public class TypeSafeMatchingTest {
     public void compareNullArgument() {
         boolean match = matchesTypeSafe().apply(new LessOrEqual(5), null);
         assertThat(match).isFalse();
-
     }
 
     /**
@@ -102,7 +99,6 @@ public boolean matches(Date arg) {
             public boolean matches(Integer arg, Void v) {
                 throw new UnsupportedOperationException();
             }
-
         }
 
         boolean match = matchesTypeSafe().apply(new TestMatcher(), 123);
@@ -111,8 +107,7 @@ public boolean matches(Integer arg, Void v) {
 
     @Test
     public void matchesWithSubTypeExtendingGenericClass() {
-        abstract class GenericMatcher implements ArgumentMatcher {
-        }
+        abstract class GenericMatcher implements ArgumentMatcher {}
         class TestMatcher extends GenericMatcher {
             @Override
             public boolean matches(Integer argument) {
@@ -127,8 +122,7 @@ public boolean matches(Integer argument) {
     public void dontMatchesWithSubTypeExtendingGenericClass() {
         final AtomicBoolean wasCalled = new AtomicBoolean();
 
-        abstract class GenericMatcher implements ArgumentMatcher {
-        }
+        abstract class GenericMatcher implements ArgumentMatcher {}
         class TestMatcher extends GenericMatcher {
             @Override
             public boolean matches(Integer argument) {
diff --git a/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java b/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java
index aa38dd4e97..5c31e5ac56 100644
--- a/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java
+++ b/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java
@@ -15,9 +15,9 @@ public class MockWeakReferenceTest extends TestBase {
     @Test
     public void descriptive_exception_when_mock_was_collected() {
         try {
-            //when
+            // when
             new MockWeakReference(null).get();
-            //then
+            // then
             fail();
         } catch (Exception e) {
             Assertions.assertThat(e).hasMessageContaining("The mock object was garbage collected");
diff --git a/src/test/java/org/mockito/internal/junit/ArgMismatchFinderTest.java b/src/test/java/org/mockito/internal/junit/ArgMismatchFinderTest.java
index d4fccc2732..265941269c 100644
--- a/src/test/java/org/mockito/internal/junit/ArgMismatchFinderTest.java
+++ b/src/test/java/org/mockito/internal/junit/ArgMismatchFinderTest.java
@@ -22,109 +22,112 @@ public class ArgMismatchFinderTest extends TestBase {
 
     @Test
     public void no_interactions() throws Exception {
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(0, mismatches.size());
     }
 
     @Test
     public void no_mismatch_when_mock_different() throws Exception {
-        //given
+        // given
         when(mock1.simpleMethod(1)).thenReturn("1");
-        mock2.simpleMethod(2); //arg mismatch on different mock
+        mock2.simpleMethod(2); // arg mismatch on different mock
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(0, mismatches.size());
     }
 
     @Test
     public void no_mismatch_when_method_different() throws Exception {
-        //given
+        // given
         when(mock1.simpleMethod(1)).thenReturn("1");
         mock1.otherMethod();
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(0, mismatches.size());
     }
 
     @Test
     public void no_mismatch_when_stubbing_used() throws Exception {
-        //given
+        // given
         when(mock1.simpleMethod(1)).thenReturn("1");
         mock1.simpleMethod(1); // stub used
         mock1.simpleMethod(2); // no stubbing, but we don't want it to be reported, either
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(0, mismatches.size());
     }
 
     @Test
     public void stubbing_mismatch() throws Exception {
-        //given
+        // given
         when(mock1.simpleMethod(1)).thenReturn("1");
         mock1.simpleMethod(2);
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(1, mismatches.size());
     }
 
     @Test
     public void single_mismatch_with_multiple_invocations() throws Exception {
-        //given
+        // given
         when(mock1.simpleMethod(1)).thenReturn("1");
         mock1.simpleMethod(2);
         mock1.simpleMethod(3);
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(1, mismatches.size());
-        assertEquals("{mock1.simpleMethod(1);=[mock1.simpleMethod(2);, mock1.simpleMethod(3);]}", mismatches.toString());
+        assertEquals(
+                "{mock1.simpleMethod(1);=[mock1.simpleMethod(2);, mock1.simpleMethod(3);]}",
+                mismatches.toString());
     }
 
     @Test
     public void single_invocation_with_multiple_stubs() throws Exception {
-        //given
+        // given
         when(mock1.simpleMethod(1)).thenReturn("1");
         when(mock1.simpleMethod(2)).thenReturn("2");
         mock1.simpleMethod(3);
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals(2, mismatches.size());
-        assertEquals("{mock1.simpleMethod(1);=[mock1.simpleMethod(3);], mock1.simpleMethod(2);=[mock1.simpleMethod(3);]}"
-                , mismatches.toString());
+        assertEquals(
+                "{mock1.simpleMethod(1);=[mock1.simpleMethod(3);], mock1.simpleMethod(2);=[mock1.simpleMethod(3);]}",
+                mismatches.toString());
     }
 
     @Test
     public void mismatch_reports_only_unstubbed_invocations() throws Exception {
-        //given
-        when(mock1.simpleMethod(1)).thenReturn("1"); //unused
-        when(mock1.simpleMethod(2)).thenReturn("2"); //used
-        mock1.simpleMethod(2); //stubbed
-        mock1.simpleMethod(3); //unstubbed
+        // given
+        when(mock1.simpleMethod(1)).thenReturn("1"); // unused
+        when(mock1.simpleMethod(2)).thenReturn("2"); // used
+        mock1.simpleMethod(2); // stubbed
+        mock1.simpleMethod(3); // unstubbed
 
-        //when
+        // when
         StubbingArgMismatches mismatches = finder.getStubbingArgMismatches(asList(mock1, mock2));
 
-        //then
+        // then
         assertEquals("{mock1.simpleMethod(1);=[mock1.simpleMethod(3);]}", mismatches.toString());
     }
 }
diff --git a/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java b/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
index 2c1037bae2..69baf30427 100644
--- a/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
+++ b/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
@@ -15,16 +15,26 @@
 
 public class ExceptionFactoryTest {
 
-    private static ClassLoader classLoaderWithoutJUnitOrOpenTest = excludingClassLoader().withCodeSourceUrlOf(ExceptionFactory.class).without("org.junit", "junit", "org.opentest4j").build();
-    private static ClassLoader classLoaderWithoutOpenTest = excludingClassLoader().withCodeSourceUrlOf(ExceptionFactory.class, org.junit.ComparisonFailure.class).without("org.opentest4j").build();
+    private static ClassLoader classLoaderWithoutJUnitOrOpenTest =
+            excludingClassLoader()
+                    .withCodeSourceUrlOf(ExceptionFactory.class)
+                    .without("org.junit", "junit", "org.opentest4j")
+                    .build();
+    private static ClassLoader classLoaderWithoutOpenTest =
+            excludingClassLoader()
+                    .withCodeSourceUrlOf(ExceptionFactory.class, org.junit.ComparisonFailure.class)
+                    .without("org.opentest4j")
+                    .build();
     private static ClassLoader currentClassLoader = ExceptionFactoryTest.class.getClassLoader();
 
     /** loaded by the current classloader */
     private static Class opentestComparisonFailure;
+
     private static Class opentestArgumentsAreDifferent;
 
     /** loaded by the classloader {@value #classLoaderWithoutOpenTest}, which excludes OpenTest4J classes */
     private static Class junit3ComparisonFailure;
+
     private static Class junit3ArgumentsAreDifferent;
 
     /** loaded by the custom classloader {@value #classLoaderWithoutJUnitOrOpenTest}, which excludes JUnit and OpenTest4J classes */
@@ -32,11 +42,18 @@ public class ExceptionFactoryTest {
 
     @BeforeClass
     public static void init() throws ClassNotFoundException {
-        nonJunitArgumentsAreDifferent = classLoaderWithoutJUnitOrOpenTest.loadClass(ArgumentsAreDifferent.class.getName());
-        junit3ComparisonFailure = classLoaderWithoutOpenTest.loadClass(junit.framework.ComparisonFailure.class.getName());
-        junit3ArgumentsAreDifferent = classLoaderWithoutOpenTest.loadClass(org.mockito.exceptions.verification.junit.ArgumentsAreDifferent.class.getName());
+        nonJunitArgumentsAreDifferent =
+                classLoaderWithoutJUnitOrOpenTest.loadClass(ArgumentsAreDifferent.class.getName());
+        junit3ComparisonFailure =
+                classLoaderWithoutOpenTest.loadClass(
+                        junit.framework.ComparisonFailure.class.getName());
+        junit3ArgumentsAreDifferent =
+                classLoaderWithoutOpenTest.loadClass(
+                        org.mockito.exceptions.verification.junit.ArgumentsAreDifferent.class
+                                .getName());
         opentestComparisonFailure = org.opentest4j.AssertionFailedError.class;
-        opentestArgumentsAreDifferent = org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent.class;
+        opentestArgumentsAreDifferent =
+                org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent.class;
     }
 
     @Test
@@ -50,14 +67,18 @@ public void createArgumentsAreDifferentException_withoutJUnitOrOpenTest() throws
     public void createArgumentsAreDifferentException_withJUnit3_butNotOpenTest() throws Exception {
         AssertionError e = invokeFactoryThroughLoader(classLoaderWithoutOpenTest);
 
-        assertThat(e).isExactlyInstanceOf(junit3ArgumentsAreDifferent).isInstanceOf(junit3ComparisonFailure);
+        assertThat(e)
+                .isExactlyInstanceOf(junit3ArgumentsAreDifferent)
+                .isInstanceOf(junit3ComparisonFailure);
     }
 
     @Test
     public void createArgumentsAreDifferentException_withOpenTest() throws Exception {
         AssertionError e = invokeFactoryThroughLoader(currentClassLoader);
 
-        assertThat(e).isExactlyInstanceOf(opentestArgumentsAreDifferent).isInstanceOf(opentestComparisonFailure);
+        assertThat(e)
+                .isExactlyInstanceOf(opentestArgumentsAreDifferent)
+                .isInstanceOf(opentestComparisonFailure);
     }
 
     @Test
@@ -96,7 +117,12 @@ public void createArgumentsAreDifferentException_withOpenTest_2x() throws Except
     private static AssertionError invokeFactoryThroughLoader(ClassLoader loader) throws Exception {
         Class exceptionFactory = loader.loadClass(ExceptionFactory.class.getName());
 
-        Method m = exceptionFactory.getDeclaredMethod("createArgumentsAreDifferentException", String.class, String.class, String.class);
+        Method m =
+                exceptionFactory.getDeclaredMethod(
+                        "createArgumentsAreDifferentException",
+                        String.class,
+                        String.class,
+                        String.class);
         return (AssertionError) m.invoke(null, "message", "wanted", "actual");
     }
 }
diff --git a/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java b/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java
index 1f9a3183a0..f971893e4b 100644
--- a/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java
+++ b/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java
@@ -22,7 +22,8 @@ public class JUnitRuleTest {
     @Rule public SafeJUnitRule rule = new SafeJUnitRule(MockitoJUnit.rule());
     @Mock IMethods mock;
 
-    @Test public void injects_into_test_case() throws Throwable {
+    @Test
+    public void injects_into_test_case() throws Throwable {
         assertTrue(mockingDetails(mock).isMock());
     }
 
@@ -42,9 +43,9 @@ public void detects_invalid_mockito_usage_on_success() throws Throwable {
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
     @Test
     public void does_not_check_invalid_mockito_usage_on_failure() throws Throwable {
-        //This intended behavior is questionable
-        //However, it was like that since the beginning of JUnit rule support
-        //Users never questioned this behavior. Hence, let's stick to it unless we have more data
+        // This intended behavior is questionable
+        // However, it was like that since the beginning of JUnit rule support
+        // Users never questioned this behavior. Hence, let's stick to it unless we have more data
         rule.expectFailure(RuntimeException.class, "foo");
 
         Mockito.when(mock.simpleMethod()); // <--- unfinished stubbing
diff --git a/src/test/java/org/mockito/internal/junit/StubbingArgMismatchesTest.java b/src/test/java/org/mockito/internal/junit/StubbingArgMismatchesTest.java
index beb94210e6..53493648ed 100644
--- a/src/test/java/org/mockito/internal/junit/StubbingArgMismatchesTest.java
+++ b/src/test/java/org/mockito/internal/junit/StubbingArgMismatchesTest.java
@@ -20,51 +20,67 @@ public class StubbingArgMismatchesTest extends TestBase {
 
     @Test
     public void no_op_when_no_mismatches() throws Exception {
-        //when
+        // when
         mismatches.format("MyTest.myTestMethod", logger);
 
-        //then
+        // then
         assertTrue(logger.isEmpty());
     }
 
     @Test
     public void logs_mismatch() throws Exception {
-        //given
+        // given
         mismatches.add(
                 new InvocationBuilder().args("a").location("-> at A.java").toInvocation(),
                 new InvocationBuilder().args("b").location("-> at B.java").toInvocation());
 
-        //when
+        // when
         mismatches.format("MyTest.myTestMethod", logger);
 
-        //then
+        // then
         assertEquals(
-            "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n" +
-            "[MockitoHint] 1. Unused... -> at B.java\n" +
-            "[MockitoHint]  ...args ok? -> at A.java\n", logger.getLoggedInfo());
+                "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n"
+                        + "[MockitoHint] 1. Unused... -> at B.java\n"
+                        + "[MockitoHint]  ...args ok? -> at A.java\n",
+                logger.getLoggedInfo());
     }
 
     @Test
-    public void multiple_matching_invocations_per_stub_plus_some_other_invocation() throws Exception {
-        //given
-        Invocation stubbing = new InvocationBuilder().args("a").location("-> at A.java").toInvocation();
-        mismatches.add(new InvocationBuilder().args("x").location("-> at X.java").toInvocation(), stubbing);
-        mismatches.add(new InvocationBuilder().args("y").location("-> at Y.java").toInvocation(), stubbing);
+    public void multiple_matching_invocations_per_stub_plus_some_other_invocation()
+            throws Exception {
+        // given
+        Invocation stubbing =
+                new InvocationBuilder().args("a").location("-> at A.java").toInvocation();
+        mismatches.add(
+                new InvocationBuilder().args("x").location("-> at X.java").toInvocation(),
+                stubbing);
+        mismatches.add(
+                new InvocationBuilder().args("y").location("-> at Y.java").toInvocation(),
+                stubbing);
 
         mismatches.add(
-                new InvocationBuilder().method("differentMethod").args("n").location("-> at N.java").toInvocation(),
-                new InvocationBuilder().method("differentMethod").args("m").location("-> at M.java").toInvocation());
+                new InvocationBuilder()
+                        .method("differentMethod")
+                        .args("n")
+                        .location("-> at N.java")
+                        .toInvocation(),
+                new InvocationBuilder()
+                        .method("differentMethod")
+                        .args("m")
+                        .location("-> at M.java")
+                        .toInvocation());
 
-        //when
+        // when
         mismatches.format("MyTest.myTestMethod", logger);
 
-        //then
+        // then
         assertEquals(
-            "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n" +
-            "[MockitoHint] 1. Unused... -> at A.java\n" +
-            "[MockitoHint]  ...args ok? -> at X.java\n" +
-            "[MockitoHint]  ...args ok? -> at Y.java\n" +
-            "[MockitoHint] 2. Unused... -> at M.java\n" +
-            "[MockitoHint]  ...args ok? -> at N.java\n", logger.getLoggedInfo());
+                "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n"
+                        + "[MockitoHint] 1. Unused... -> at A.java\n"
+                        + "[MockitoHint]  ...args ok? -> at X.java\n"
+                        + "[MockitoHint]  ...args ok? -> at Y.java\n"
+                        + "[MockitoHint] 2. Unused... -> at M.java\n"
+                        + "[MockitoHint]  ...args ok? -> at N.java\n",
+                logger.getLoggedInfo());
     }
 }
diff --git a/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java b/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java
index f169516e73..9083d19dc0 100644
--- a/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java
+++ b/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java
@@ -24,36 +24,44 @@ public class UnusedStubbingsTest extends TestBase {
 
     @Test
     public void no_unused_stubbings() throws Exception {
-        //given
+        // given
         UnusedStubbings stubbings = new UnusedStubbings(Collections.emptyList());
 
-        //when
+        // when
         stubbings.format("MyTest.myTestMethod", logger);
 
-        //then
+        // then
         assertEquals("", logger.getLoggedInfo());
     }
 
     @Test
     public void unused_stubbings() throws Exception {
-        //given
-        UnusedStubbings stubbings = new UnusedStubbings(Arrays.asList(
-            new StubbedInvocationMatcher(doesNothing(), new InvocationBuilder().toInvocationMatcher(), null),
-            new StubbedInvocationMatcher(doesNothing(), new InvocationBuilder().toInvocationMatcher(), null)
-        ));
+        // given
+        UnusedStubbings stubbings =
+                new UnusedStubbings(
+                        Arrays.asList(
+                                new StubbedInvocationMatcher(
+                                        doesNothing(),
+                                        new InvocationBuilder().toInvocationMatcher(),
+                                        null),
+                                new StubbedInvocationMatcher(
+                                        doesNothing(),
+                                        new InvocationBuilder().toInvocationMatcher(),
+                                        null)));
 
-
-        //when
+        // when
         stubbings.format("MyTest.myTestMethod", logger);
 
-        //then
-        assertThat(filterLineNo(logger.getLoggedInfo())).isIn(
-            "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n" +  //Java <9
-                                    "[MockitoHint] 1. Unused -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
-                                    "[MockitoHint] 2. Unused -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n",
-            "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n" +  //Java 9
-                                    "[MockitoHint] 1. Unused -> at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n" +
-                                    "[MockitoHint] 2. Unused -> at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
-        );
+        // then
+        assertThat(filterLineNo(logger.getLoggedInfo()))
+                .isIn(
+                        "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n"
+                                + // Java <9
+                                "[MockitoHint] 1. Unused -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
+                                + "[MockitoHint] 2. Unused -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n",
+                        "[MockitoHint] MyTest.myTestMethod (see javadoc for MockitoHint):\n"
+                                + // Java 9
+                                "[MockitoHint] 1. Unused -> at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n"
+                                + "[MockitoHint] 2. Unused -> at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n");
     }
 }
diff --git a/src/test/java/org/mockito/internal/junit/util/JUnitFailureHackerTest.java b/src/test/java/org/mockito/internal/junit/util/JUnitFailureHackerTest.java
index 5da1ffad08..3e3fb8d633 100644
--- a/src/test/java/org/mockito/internal/junit/util/JUnitFailureHackerTest.java
+++ b/src/test/java/org/mockito/internal/junit/util/JUnitFailureHackerTest.java
@@ -20,27 +20,28 @@ public class JUnitFailureHackerTest extends TestBase {
 
     @Test
     public void shouldReplaceException() throws Exception {
-        //given
+        // given
         RuntimeException actualExc = new RuntimeException("foo");
         Failure failure = new Failure(Description.EMPTY, actualExc);
 
-        //when
+        // when
         hacker.appendWarnings(failure, "unused stubbing");
 
-        //then
+        // then
         assertEquals(ExceptionIncludingMockitoWarnings.class, failure.getException().getClass());
         assertEquals(actualExc, failure.getException().getCause());
-        Assertions.assertThat(actualExc.getStackTrace()).isEqualTo(failure.getException().getStackTrace());
+        Assertions.assertThat(actualExc.getStackTrace())
+                .isEqualTo(failure.getException().getStackTrace());
     }
 
     @Test
     public void shouldAppendWarning() throws Exception {
         Failure failure = new Failure(Description.EMPTY, new RuntimeException("foo"));
 
-        //when
+        // when
         hacker.appendWarnings(failure, "unused stubbing blah");
 
-        //then
+        // then
         assertThat(failure.getException()).hasMessageContaining("unused stubbing blah");
     }
 
@@ -49,10 +50,10 @@ public void shouldNotAppendWhenNoWarnings() throws Exception {
         RuntimeException ex = new RuntimeException("foo");
         Failure failure = new Failure(Description.EMPTY, ex);
 
-        //when
+        // when
         hacker.appendWarnings(failure, "");
 
-        //then
+        // then
         assertEquals(ex, failure.getException());
     }
 
@@ -61,10 +62,10 @@ public void shouldNotAppendWhenNullWarnings() throws Exception {
         RuntimeException ex = new RuntimeException("foo");
         Failure failure = new Failure(Description.EMPTY, ex);
 
-        //when
+        // when
         hacker.appendWarnings(failure, null);
 
-        //then
+        // then
         assertEquals(ex, failure.getException());
     }
 
@@ -72,10 +73,10 @@ public void shouldNotAppendWhenNullWarnings() throws Exception {
     public void shouldPrintTheWarningSoICanSeeIt() throws Exception {
         Failure failure = new Failure(Description.EMPTY, new RuntimeException("foo"));
 
-        //when
+        // when
         hacker.appendWarnings(failure, "unused stubbing blah");
 
-        //then
+        // then
         System.out.println(failure.getException());
     }
 }
diff --git a/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java b/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java
index bfb275a1ad..6b2c77c693 100644
--- a/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java
+++ b/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java
@@ -61,10 +61,10 @@ class EventArgumentMatcher implements ArgumentMatcher m = new CapturingMatcher();
 
-        //when
+        // when
         m.captureFrom("foo");
         m.captureFrom("bar");
 
-        //then
+        // then
         assertThat(m.getAllValues()).containsSequence("foo", "bar");
     }
 
     @Test
     public void should_know_last_captured_value() throws Exception {
-        //given
+        // given
         CapturingMatcher m = new CapturingMatcher();
 
-        //when
+        // when
         m.captureFrom("foo");
         m.captureFrom("bar");
 
-        //then
+        // then
         assertEquals("bar", m.getLastValue());
     }
 
     @Test
     public void should_scream_when_nothing_yet_captured() throws Exception {
-        //given
+        // given
         CapturingMatcher m = new CapturingMatcher();
 
         try {
-            //when
+            // when
             m.getLastValue();
-            //then
+            // then
             fail();
-        } catch (MockitoException e) {}
+        } catch (MockitoException e) {
+        }
     }
 
     @Test
     public void should_not_fail_when_used_in_concurrent_tests() throws Exception {
-        //given
+        // given
         final CapturingMatcher m = new CapturingMatcher();
 
-        //when
+        // when
         m.captureFrom("concurrent access");
         Iterator iterator = m.getAllValues().iterator();
         m.captureFrom("concurrent access");
 
-        //then
+        // then
         assertThat(iterator.hasNext()).isTrue();
-        assertThat(iterator.next()).isEqualTo("concurrent access"); // Potential ConcurrentModificationException
+        assertThat(iterator.next())
+                .isEqualTo("concurrent access"); // Potential ConcurrentModificationException
     }
-
 }
diff --git a/src/test/java/org/mockito/internal/matchers/ComparableMatchersTest.java b/src/test/java/org/mockito/internal/matchers/ComparableMatchersTest.java
index 64236c4414..583a84839e 100644
--- a/src/test/java/org/mockito/internal/matchers/ComparableMatchersTest.java
+++ b/src/test/java/org/mockito/internal/matchers/ComparableMatchersTest.java
@@ -43,8 +43,12 @@ public void testCompareEqual() {
         assertTrue(cmpEq.matches(new BigDecimal("5")));
     }
 
-    private void test(CompareTo compareTo, boolean lower, boolean higher,
-            boolean equals, String name) {
+    private void test(
+            CompareTo compareTo,
+            boolean lower,
+            boolean higher,
+            boolean equals,
+            String name) {
 
         assertEquals(lower, compareTo.matches("a"));
         assertEquals(equals, compareTo.matches("b"));
diff --git a/src/test/java/org/mockito/internal/matchers/EqualityTest.java b/src/test/java/org/mockito/internal/matchers/EqualityTest.java
index 5002701d2f..81f1f6888f 100644
--- a/src/test/java/org/mockito/internal/matchers/EqualityTest.java
+++ b/src/test/java/org/mockito/internal/matchers/EqualityTest.java
@@ -23,8 +23,8 @@ public void shouldKnowIfObjectsAreEqual() throws Exception {
         assertTrue(areEqual(new Object[10], new Object[10]));
         assertTrue(areEqual(new int[] {1}, new Integer[] {1}));
         assertTrue(areEqual(new Object[] {"1"}, new String[] {"1"}));
-        Object badequals=new BadEquals();
-        assertTrue(areEqual(badequals,badequals));
+        Object badequals = new BadEquals();
+        assertTrue(areEqual(badequals, badequals));
 
         assertFalse(areEqual(new Object[9], new Object[10]));
         assertFalse(areEqual(new int[] {1, 2}, new int[] {1}));
diff --git a/src/test/java/org/mockito/internal/matchers/EqualsTest.java b/src/test/java/org/mockito/internal/matchers/EqualsTest.java
index 072241459c..26f87c2dbc 100644
--- a/src/test/java/org/mockito/internal/matchers/EqualsTest.java
+++ b/src/test/java/org/mockito/internal/matchers/EqualsTest.java
@@ -9,7 +9,6 @@
 import org.junit.Test;
 import org.mockitoutil.TestBase;
 
-
 public class EqualsTest extends TestBase {
 
     @Test
@@ -78,29 +77,29 @@ public void shouldDescribeNull() {
 
     @Test
     public void shouldMatchTypes() throws Exception {
-        //when
+        // when
         ContainsExtraTypeInfo equals = new Equals(10);
 
-        //then
+        // then
         assertTrue(equals.typeMatches(10));
         assertFalse(equals.typeMatches(10L));
     }
 
     @Test
     public void shouldMatchTypesSafelyWhenActualIsNull() throws Exception {
-        //when
+        // when
         ContainsExtraTypeInfo equals = new Equals(null);
 
-        //then
+        // then
         assertFalse(equals.typeMatches(10));
     }
 
     @Test
     public void shouldMatchTypesSafelyWhenGivenIsNull() throws Exception {
-        //when
+        // when
         ContainsExtraTypeInfo equals = new Equals(10);
 
-        //then
+        // then
         assertFalse(equals.typeMatches(null));
     }
 }
diff --git a/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java b/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java
index bc3e37d3a8..8addef8ca0 100644
--- a/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java
+++ b/src/test/java/org/mockito/internal/matchers/InstanceOfTest.java
@@ -15,11 +15,10 @@ public class InstanceOfTest {
 
     @Test
     public void should_describe_the_matcher() {
-        assertThat(new InstanceOf(Object.class).toString()).contains("isA")
-                                                           .contains("Object");
-        assertThat(new InstanceOf(Object[].class).toString()).contains("isA")
-                                                           .contains("Object[]");
-        assertThat(new InstanceOf(Object.class, "matches something").toString()).isEqualTo("matches something");
+        assertThat(new InstanceOf(Object.class).toString()).contains("isA").contains("Object");
+        assertThat(new InstanceOf(Object[].class).toString()).contains("isA").contains("Object[]");
+        assertThat(new InstanceOf(Object.class, "matches something").toString())
+                .isEqualTo("matches something");
     }
 
     @Test
diff --git a/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java b/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
index 19e85baa9b..74cfd9dff7 100644
--- a/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
+++ b/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
@@ -21,45 +21,61 @@ public class MatchersPrinterTest extends TestBase {
 
     @Test
     public void shouldGetArgumentsLine() {
-        String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1), new Equals(2)), new PrintSettings());
+        String line =
+                printer.getArgumentsLine(
+                        (List) Arrays.asList(new Equals(1), new Equals(2)), new PrintSettings());
         assertEquals("(1, 2);", line);
     }
 
     @Test
     public void shouldGetArgumentsBlock() {
-        String line = printer.getArgumentsBlock((List) Arrays.asList(new Equals(1), new Equals(2)), new PrintSettings());
+        String line =
+                printer.getArgumentsBlock(
+                        (List) Arrays.asList(new Equals(1), new Equals(2)), new PrintSettings());
         assertEquals("(\n    1,\n    2\n);", line);
     }
 
     @Test
     public void shouldDescribeTypeInfoOnlyMarkedMatchers() {
-        //when
-        String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1L), new Equals(2)), PrintSettings.verboseMatchers(1));
-        //then
+        // when
+        String line =
+                printer.getArgumentsLine(
+                        (List) Arrays.asList(new Equals(1L), new Equals(2)),
+                        PrintSettings.verboseMatchers(1));
+        // then
         assertEquals("(1L, (Integer) 2);", line);
     }
 
     @Test
     public void shouldDescribeStringMatcher() {
-        //when
-        String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1L), new Equals("x")), PrintSettings.verboseMatchers(1));
-        //then
+        // when
+        String line =
+                printer.getArgumentsLine(
+                        (List) Arrays.asList(new Equals(1L), new Equals("x")),
+                        PrintSettings.verboseMatchers(1));
+        // then
         assertEquals("(1L, (String) \"x\");", line);
     }
 
     @Test
     public void shouldGetVerboseArgumentsInBlock() {
-        //when
-        String line = printer.getArgumentsBlock((List) Arrays.asList(new Equals(1L), new Equals(2)), PrintSettings.verboseMatchers(0, 1));
-        //then
+        // when
+        String line =
+                printer.getArgumentsBlock(
+                        (List) Arrays.asList(new Equals(1L), new Equals(2)),
+                        PrintSettings.verboseMatchers(0, 1));
+        // then
         assertEquals("(\n    (Long) 1L,\n    (Integer) 2\n);", line);
     }
 
     @Test
     public void shouldGetVerboseArgumentsEvenIfSomeMatchersAreNotVerbose() {
-        //when
-        String line = printer.getArgumentsLine((List) Arrays.asList(new Equals(1L), NotNull.NOT_NULL), PrintSettings.verboseMatchers(0));
-        //then
+        // when
+        String line =
+                printer.getArgumentsLine(
+                        (List) Arrays.asList(new Equals(1L), NotNull.NOT_NULL),
+                        PrintSettings.verboseMatchers(0));
+        // then
         assertEquals("((Long) 1L, notNull());", line);
     }
 }
diff --git a/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java b/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java
index 6c038079ae..6d243a0997 100644
--- a/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java
+++ b/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java
@@ -41,19 +41,19 @@ public void sameToStringWithChar() {
 
     @Test
     public void sameToStringWithObject() {
-        Object o = new Object() {
-            @Override
-            public String toString() {
-                return "X";
-            }
-        };
+        Object o =
+                new Object() {
+                    @Override
+                    public String toString() {
+                        return "X";
+                    }
+                };
         assertEquals("same(X)", new Same(o).toString());
     }
 
     @Test
     public void equalsToStringWithString() {
         assertEquals("\"X\"", new Equals("X").toString());
-
     }
 
     @Test
@@ -63,20 +63,21 @@ public void equalsToStringWithChar() {
 
     @Test
     public void equalsToStringWithObject() {
-        Object o = new Object() {
-            @Override
-            public String toString() {
-                return "X";
-            }
-        };
+        Object o =
+                new Object() {
+                    @Override
+                    public String toString() {
+                        return "X";
+                    }
+                };
         assertEquals("X", new Equals(o).toString());
     }
 
     @Test
     public void orToString() {
-        ArgumentMatcher m1=new Equals(1);
-        ArgumentMatcher m2=new Equals(2);
-        assertEquals("or(1, 2)", new Or(m1,m2).toString());
+        ArgumentMatcher m1 = new Equals(1);
+        ArgumentMatcher m2 = new Equals(2);
+        assertEquals("or(1, 2)", new Or(m1, m2).toString());
     }
 
     @Test
@@ -86,9 +87,9 @@ public void notToString() {
 
     @Test
     public void andToString() {
-        ArgumentMatcher m1=new Equals(1);
-        ArgumentMatcher m2=new Equals(2);
-        assertEquals("and(1, 2)", new And(m1,m2).toString());
+        ArgumentMatcher m1 = new Equals(1);
+        ArgumentMatcher m2 = new Equals(2);
+        assertEquals("and(1, 2)", new And(m1, m2).toString());
     }
 
     @Test
@@ -116,5 +117,4 @@ public void matchesToString() {
         assertEquals("matches(\"\\\\s+\")", new Matches("\\s+").toString());
         assertEquals("matches(\"\\\\s+\")", new Matches(Pattern.compile("\\s+")).toString());
     }
-
 }
diff --git a/src/test/java/org/mockito/internal/matchers/StringMatchersTest.java b/src/test/java/org/mockito/internal/matchers/StringMatchersTest.java
index 32dbc4f8f5..f3bd2ae3eb 100644
--- a/src/test/java/org/mockito/internal/matchers/StringMatchersTest.java
+++ b/src/test/java/org/mockito/internal/matchers/StringMatchersTest.java
@@ -73,5 +73,4 @@ public void doesNotMatchRegex() {
     public void nullDoesNotMatchRegex() {
         assertFalse(new Find("eleph.nt").matches(null));
     }
-
 }
diff --git a/src/test/java/org/mockito/internal/matchers/apachecommons/EqualsBuilderTest.java b/src/test/java/org/mockito/internal/matchers/apachecommons/EqualsBuilderTest.java
index 513092f220..5e2bd696bb 100644
--- a/src/test/java/org/mockito/internal/matchers/apachecommons/EqualsBuilderTest.java
+++ b/src/test/java/org/mockito/internal/matchers/apachecommons/EqualsBuilderTest.java
@@ -23,20 +23,24 @@
 public class EqualsBuilderTest extends TestBase {
 
     @Test
-    public void testname() throws Exception {
-
-    }
+    public void testname() throws Exception {}
 
     static class TestObject {
         private int a;
-        public TestObject() {
-        }
+
+        public TestObject() {}
+
         public TestObject(int a) {
             this.a = a;
         }
+
         public boolean equals(Object o) {
-            if (o == null) { return false; }
-            if (o == this) { return true; }
+            if (o == null) {
+                return false;
+            }
+            if (o == this) {
+                return true;
+            }
             if (o.getClass() != getClass()) {
                 return false;
             }
@@ -44,6 +48,7 @@ public boolean equals(Object o) {
             TestObject rhs = (TestObject) o;
             return (a == rhs.a);
         }
+
         public int hashCode() {
             return super.hashCode();
         }
@@ -59,16 +64,23 @@ public int getA() {
 
     static class TestSubObject extends TestObject {
         private int b;
+
         public TestSubObject() {
             super(0);
         }
+
         public TestSubObject(int a, int b) {
             super(a);
             this.b = b;
         }
+
         public boolean equals(Object o) {
-            if (o == null) { return false; }
-            if (o == this) { return true; }
+            if (o == null) {
+                return false;
+            }
+            if (o == this) {
+                return true;
+            }
             if (o.getClass() != getClass()) {
                 return false;
             }
@@ -76,6 +88,7 @@ public boolean equals(Object o) {
             TestSubObject rhs = (TestSubObject) o;
             return super.equals(o) && (b == rhs.b);
         }
+
         public int hashCode() {
             return 1;
         }
@@ -98,6 +111,7 @@ public TestEmptySubObject(int a) {
     @SuppressWarnings("unused")
     static class TestTSubObject extends TestObject {
         private transient int t;
+
         public TestTSubObject(int a, int t) {
             super(a);
             this.t = t;
@@ -107,6 +121,7 @@ public TestTSubObject(int a, int t) {
     @SuppressWarnings("unused")
     static class TestTTSubObject extends TestTSubObject {
         private transient int tt;
+
         public TestTTSubObject(int a, int t, int tt) {
             super(a, t);
             this.tt = tt;
@@ -116,6 +131,7 @@ public TestTTSubObject(int a, int t, int tt) {
     @SuppressWarnings("unused")
     static class TestTTLeafObject extends TestTTSubObject {
         private int leafValue;
+
         public TestTTLeafObject(int a, int t, int tt, int leafValue) {
             super(a, t, tt);
             this.leafValue = leafValue;
@@ -124,18 +140,22 @@ public TestTTLeafObject(int a, int t, int tt, int leafValue) {
 
     static class TestTSubObject2 extends TestObject {
         private transient int t;
+
         public TestTSubObject2(int a, int t) {
             super(a);
         }
+
         public int getT() {
             return t;
         }
+
         public void setT(int t) {
             this.t = t;
         }
     }
 
-    @Test public void testReflectionEquals() {
+    @Test
+    public void testReflectionEquals() {
         TestObject o1 = new TestObject(4);
         TestObject o2 = new TestObject(5);
         assertTrue(EqualsBuilder.reflectionEquals(o1, o1));
@@ -150,18 +170,29 @@ public void setT(int t) {
         assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null));
     }
 
-    @Test public void testReflectionHierarchyEquals() {
+    @Test
+    public void testReflectionHierarchyEquals() {
         testReflectionHierarchyEquals(false);
         testReflectionHierarchyEquals(true);
         // Transients
-        assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true));
-        assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), false));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 0, 0, 4), new TestTTLeafObject(1, 2, 3, 4), true));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 0), true));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true));
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true));
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), false));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestTTLeafObject(1, 0, 0, 4), new TestTTLeafObject(1, 2, 3, 4), true));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 0), true));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true));
     }
 
-  private void testReflectionHierarchyEquals(boolean testTransients) {
+    private void testReflectionHierarchyEquals(boolean testTransients) {
         TestObject to1 = new TestObject(4);
         TestObject to1Bis = new TestObject(4);
         TestObject to1Ter = new TestObject(4);
@@ -175,43 +206,79 @@ private void testReflectionHierarchyEquals(boolean testTransients) {
         TestSubObject tso1ter = new TestSubObject(1, 4);
         TestSubObject tso2 = new TestSubObject(2, 5);
 
-        testReflectionEqualsEquivalenceRelationship(to1, to1Bis, to1Ter, to2, new TestObject(), testTransients);
-        testReflectionEqualsEquivalenceRelationship(tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients);
+        testReflectionEqualsEquivalenceRelationship(
+                to1, to1Bis, to1Ter, to2, new TestObject(), testTransients);
+        testReflectionEqualsEquivalenceRelationship(
+                tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients);
 
         // More sanity checks:
 
         // same values
         assertTrue(EqualsBuilder.reflectionEquals(ttlo, ttlo, testTransients));
-        assertTrue(EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 10), testTransients));
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        new TestSubObject(1, 10), new TestSubObject(1, 10), testTransients));
         // same super values, diff sub values
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 11), testTransients));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 11), new TestSubObject(1, 10), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestSubObject(1, 10), new TestSubObject(1, 11), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestSubObject(1, 11), new TestSubObject(1, 10), testTransients));
         // diff super values, same sub values
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestSubObject(1, 10), testTransients));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(0, 10), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestSubObject(0, 10), new TestSubObject(1, 10), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestSubObject(1, 10), new TestSubObject(0, 10), testTransients));
 
         // mix super and sub types: equals
         assertTrue(EqualsBuilder.reflectionEquals(to1, teso, testTransients));
         assertTrue(EqualsBuilder.reflectionEquals(teso, to1, testTransients));
 
-        assertTrue(EqualsBuilder.reflectionEquals(to1, ttso, false)); // Force testTransients = false for this assert
-        assertTrue(EqualsBuilder.reflectionEquals(ttso, to1, false)); // Force testTransients = false for this assert
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        to1, ttso, false)); // Force testTransients = false for this assert
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        ttso, to1, false)); // Force testTransients = false for this assert
 
-        assertTrue(EqualsBuilder.reflectionEquals(to1, tttso, false)); // Force testTransients = false for this assert
-        assertTrue(EqualsBuilder.reflectionEquals(tttso, to1, false)); // Force testTransients = false for this assert
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        to1, tttso, false)); // Force testTransients = false for this assert
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        tttso, to1, false)); // Force testTransients = false for this assert
 
-        assertTrue(EqualsBuilder.reflectionEquals(ttso, tttso, false)); // Force testTransients = false for this assert
-        assertTrue(EqualsBuilder.reflectionEquals(tttso, ttso, false)); // Force testTransients = false for this assert
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        ttso, tttso, false)); // Force testTransients = false for this assert
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        tttso, ttso, false)); // Force testTransients = false for this assert
 
         // mix super and sub types: NOT equals
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestEmptySubObject(1), testTransients));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestEmptySubObject(1), new TestObject(0), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestObject(0), new TestEmptySubObject(1), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestEmptySubObject(1), new TestObject(0), testTransients));
 
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestTSubObject(1, 1), testTransients));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestTSubObject(1, 1), new TestObject(0), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestObject(0), new TestTSubObject(1, 1), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestTSubObject(1, 1), new TestObject(0), testTransients));
 
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(1), new TestSubObject(0, 10), testTransients));
-        assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestObject(1), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestObject(1), new TestSubObject(0, 10), testTransients));
+        assertTrue(
+                !EqualsBuilder.reflectionEquals(
+                        new TestSubObject(0, 10), new TestObject(1), testTransients));
 
         assertTrue(!EqualsBuilder.reflectionEquals(to1, ttlo));
         assertTrue(!EqualsBuilder.reflectionEquals(tso1, this));
@@ -233,25 +300,27 @@ private void testReflectionHierarchyEquals(boolean testTransients) {
      * @param oToChange a TestObject that will be changed
      */
     private void testReflectionEqualsEquivalenceRelationship(
-        TestObject to,
-        TestObject toBis,
-        TestObject toTer,
-        TestObject to2,
-        TestObject oToChange,
-        boolean testTransients) {
+            TestObject to,
+            TestObject toBis,
+            TestObject toTer,
+            TestObject to2,
+            TestObject oToChange,
+            boolean testTransients) {
 
         // reflection test
         assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients));
         assertTrue(EqualsBuilder.reflectionEquals(to2, to2, testTransients));
 
         // symmetry test
-        assertTrue(EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, to, testTransients));
+        assertTrue(
+                EqualsBuilder.reflectionEquals(to, toBis, testTransients)
+                        && EqualsBuilder.reflectionEquals(toBis, to, testTransients));
 
         // transitive test
         assertTrue(
-            EqualsBuilder.reflectionEquals(to, toBis, testTransients)
-                && EqualsBuilder.reflectionEquals(toBis, toTer, testTransients)
-                && EqualsBuilder.reflectionEquals(to, toTer, testTransients));
+                EqualsBuilder.reflectionEquals(to, toBis, testTransients)
+                        && EqualsBuilder.reflectionEquals(toBis, toTer, testTransients)
+                        && EqualsBuilder.reflectionEquals(to, toTer, testTransients));
 
         // consistency test
         oToChange.setA(to.getA());
@@ -275,7 +344,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null, testTransients));
     }
 
-    @Test public void testSuper() {
+    @Test
+    public void testSuper() {
         TestObject o1 = new TestObject(4);
         TestObject o2 = new TestObject(5);
         assertEquals(true, new EqualsBuilder().appendSuper(true).append(o1, o1).isEquals());
@@ -284,7 +354,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o2).isEquals());
     }
 
-    @Test public void testObject() {
+    @Test
+    public void testObject() {
         TestObject o1 = new TestObject(4);
         TestObject o2 = new TestObject(5);
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
@@ -299,70 +370,85 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append((Object) null, (Object) null).isEquals());
     }
 
-    @Test public void testLong() {
+    @Test
+    public void testLong() {
         long o1 = 1L;
         long o2 = 2L;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testInt() {
+    @Test
+    public void testInt() {
         int o1 = 1;
         int o2 = 2;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testShort() {
+    @Test
+    public void testShort() {
         short o1 = 1;
         short o2 = 2;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testChar() {
+    @Test
+    public void testChar() {
         char o1 = 1;
         char o2 = 2;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testByte() {
+    @Test
+    public void testByte() {
         byte o1 = 1;
         byte o2 = 2;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testDouble() {
+    @Test
+    public void testDouble() {
         double o1 = 1;
         double o2 = 2;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, Double.NaN).isEquals());
         assertTrue(new EqualsBuilder().append(Double.NaN, Double.NaN).isEquals());
-        assertTrue(new EqualsBuilder().append(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY).isEquals());
+        assertTrue(
+                new EqualsBuilder()
+                        .append(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
+                        .isEquals());
     }
 
-    @Test public void testFloat() {
+    @Test
+    public void testFloat() {
         float o1 = 1;
         float o2 = 2;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, Float.NaN).isEquals());
         assertTrue(new EqualsBuilder().append(Float.NaN, Float.NaN).isEquals());
-        assertTrue(new EqualsBuilder().append(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY).isEquals());
+        assertTrue(
+                new EqualsBuilder()
+                        .append(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
+                        .isEquals());
     }
 
     // https://issues.apache.org/jira/browse/LANG-393
-    @Test public void testBigDecimal() {
+    @Test
+    public void testBigDecimal() {
         BigDecimal o1 = new BigDecimal("2.0");
         BigDecimal o2 = new BigDecimal("2.00");
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testAccessors() {
+    @Test
+    public void testAccessors() {
         EqualsBuilder equalsBuilder = new EqualsBuilder();
         assertTrue(equalsBuilder.isEquals());
         equalsBuilder.setEquals(true);
@@ -371,14 +457,16 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertFalse(equalsBuilder.isEquals());
     }
 
-    @Test public void testBoolean() {
+    @Test
+    public void testBoolean() {
         boolean o1 = true;
         boolean o2 = false;
         assertTrue(new EqualsBuilder().append(o1, o1).isEquals());
         assertTrue(!new EqualsBuilder().append(o1, o2).isEquals());
     }
 
-    @Test public void testObjectArray() {
+    @Test
+    public void testObjectArray() {
         TestObject[] obj1 = new TestObject[3];
         obj1[0] = new TestObject(4);
         obj1[1] = new TestObject(5);
@@ -406,7 +494,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testLongArray() {
+    @Test
+    public void testLongArray() {
         long[] obj1 = new long[2];
         obj1[0] = 5L;
         obj1[1] = 6L;
@@ -424,7 +513,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testIntArray() {
+    @Test
+    public void testIntArray() {
         int[] obj1 = new int[2];
         obj1[0] = 5;
         obj1[1] = 6;
@@ -442,7 +532,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testShortArray() {
+    @Test
+    public void testShortArray() {
         short[] obj1 = new short[2];
         obj1[0] = 5;
         obj1[1] = 6;
@@ -460,7 +551,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testCharArray() {
+    @Test
+    public void testCharArray() {
         char[] obj1 = new char[2];
         obj1[0] = 5;
         obj1[1] = 6;
@@ -478,7 +570,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testByteArray() {
+    @Test
+    public void testByteArray() {
         byte[] obj1 = new byte[2];
         obj1[0] = 5;
         obj1[1] = 6;
@@ -496,7 +589,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testDoubleArray() {
+    @Test
+    public void testDoubleArray() {
         double[] obj1 = new double[2];
         obj1[0] = 5;
         obj1[1] = 6;
@@ -514,7 +608,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testFloatArray() {
+    @Test
+    public void testFloatArray() {
         float[] obj1 = new float[2];
         obj1[0] = 5;
         obj1[1] = 6;
@@ -532,7 +627,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testBooleanArray() {
+    @Test
+    public void testBooleanArray() {
         boolean[] obj1 = new boolean[2];
         obj1[0] = true;
         obj1[1] = false;
@@ -550,7 +646,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testMultiLongArray() {
+    @Test
+    public void testMultiLongArray() {
         long[][] array1 = new long[2][2];
         long[][] array2 = new long[2][2];
         for (int i = 0; i < array1.length; ++i) {
@@ -565,7 +662,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMultiIntArray() {
+    @Test
+    public void testMultiIntArray() {
         int[][] array1 = new int[2][2];
         int[][] array2 = new int[2][2];
         for (int i = 0; i < array1.length; ++i) {
@@ -580,7 +678,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMultiShortArray() {
+    @Test
+    public void testMultiShortArray() {
         short[][] array1 = new short[2][2];
         short[][] array2 = new short[2][2];
         for (short i = 0; i < array1.length; ++i) {
@@ -595,7 +694,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMultiCharArray() {
+    @Test
+    public void testMultiCharArray() {
         char[][] array1 = new char[2][2];
         char[][] array2 = new char[2][2];
         for (char i = 0; i < array1.length; ++i) {
@@ -610,7 +710,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMultiByteArray() {
+    @Test
+    public void testMultiByteArray() {
         byte[][] array1 = new byte[2][2];
         byte[][] array2 = new byte[2][2];
         for (byte i = 0; i < array1.length; ++i) {
@@ -624,7 +725,9 @@ private void testReflectionEqualsEquivalenceRelationship(
         array1[1][1] = 0;
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
-    @Test public void testMultiFloatArray() {
+
+    @Test
+    public void testMultiFloatArray() {
         float[][] array1 = new float[2][2];
         float[][] array2 = new float[2][2];
         for (int i = 0; i < array1.length; ++i) {
@@ -639,7 +742,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMultiDoubleArray() {
+    @Test
+    public void testMultiDoubleArray() {
         double[][] array1 = new double[2][2];
         double[][] array2 = new double[2][2];
         for (int i = 0; i < array1.length; ++i) {
@@ -654,7 +758,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMultiBooleanArray() {
+    @Test
+    public void testMultiBooleanArray() {
         boolean[][] array1 = new boolean[2][2];
         boolean[][] array2 = new boolean[2][2];
         for (int i = 0; i < array1.length; ++i) {
@@ -669,14 +774,15 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
 
         // compare 1 dim to 2.
-        boolean[] array3 = new boolean[]{true, true};
+        boolean[] array3 = new boolean[] {true, true};
         assertFalse(new EqualsBuilder().append(array1, array3).isEquals());
         assertFalse(new EqualsBuilder().append(array3, array1).isEquals());
         assertFalse(new EqualsBuilder().append(array2, array3).isEquals());
         assertFalse(new EqualsBuilder().append(array3, array2).isEquals());
     }
 
-    @Test public void testRaggedArray() {
+    @Test
+    public void testRaggedArray() {
         long[][] array1 = new long[2][];
         long[][] array2 = new long[2][];
         for (int i = 0; i < array1.length; ++i) {
@@ -693,7 +799,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testMixedArray() {
+    @Test
+    public void testMixedArray() {
         Object[] array1 = new Object[2];
         Object[] array2 = new Object[2];
         for (int i = 0; i < array1.length; ++i) {
@@ -710,7 +817,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(array1, array2).isEquals());
     }
 
-    @Test public void testObjectArrayHiddenByObject() {
+    @Test
+    public void testObjectArrayHiddenByObject() {
         TestObject[] array1 = new TestObject[2];
         array1[0] = new TestObject(4);
         array1[1] = new TestObject(5);
@@ -727,7 +835,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testLongArrayHiddenByObject() {
+    @Test
+    public void testLongArrayHiddenByObject() {
         long[] array1 = new long[2];
         array1[0] = 5L;
         array1[1] = 6L;
@@ -744,7 +853,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testIntArrayHiddenByObject() {
+    @Test
+    public void testIntArrayHiddenByObject() {
         int[] array1 = new int[2];
         array1[0] = 5;
         array1[1] = 6;
@@ -761,7 +871,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testShortArrayHiddenByObject() {
+    @Test
+    public void testShortArrayHiddenByObject() {
         short[] array1 = new short[2];
         array1[0] = 5;
         array1[1] = 6;
@@ -778,7 +889,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testCharArrayHiddenByObject() {
+    @Test
+    public void testCharArrayHiddenByObject() {
         char[] array1 = new char[2];
         array1[0] = 5;
         array1[1] = 6;
@@ -795,7 +907,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testByteArrayHiddenByObject() {
+    @Test
+    public void testByteArrayHiddenByObject() {
         byte[] array1 = new byte[2];
         array1[0] = 5;
         array1[1] = 6;
@@ -812,7 +925,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testDoubleArrayHiddenByObject() {
+    @Test
+    public void testDoubleArrayHiddenByObject() {
         double[] array1 = new double[2];
         array1[0] = 5;
         array1[1] = 6;
@@ -829,7 +943,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testFloatArrayHiddenByObject() {
+    @Test
+    public void testFloatArrayHiddenByObject() {
         float[] array1 = new float[2];
         array1[0] = 5;
         array1[1] = 6;
@@ -846,7 +961,8 @@ private void testReflectionEqualsEquivalenceRelationship(
         assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals());
     }
 
-    @Test public void testBooleanArrayHiddenByObject() {
+    @Test
+    public void testBooleanArrayHiddenByObject() {
         boolean[] array1 = new boolean[2];
         array1[0] = true;
         array1[1] = false;
@@ -882,6 +998,7 @@ public boolean equals(Object o) {
             }
             return false;
         }
+
         public int hashCode() {
             return 1;
         }
@@ -910,6 +1027,7 @@ public boolean equals(Object o) {
             }
             return false;
         }
+
         public int hashCode() {
             return 1;
         }
@@ -924,9 +1042,10 @@ public int getB() {
      * of each other and do not share a parent aside from Object.
      * See http://issues.apache.org/bugzilla/show_bug.cgi?id=33069
      */
-    @Test public void testUnrelatedClasses() {
-        Object[] x = new Object[]{new TestACanEqualB(1)};
-        Object[] y = new Object[]{new TestBCanEqualA(1)};
+    @Test
+    public void testUnrelatedClasses() {
+        Object[] x = new Object[] {new TestACanEqualB(1)};
+        Object[] y = new Object[] {new TestBCanEqualA(1)};
 
         // sanity checks:
         assertTrue(Arrays.equals(x, x));
@@ -947,16 +1066,18 @@ public int getB() {
     /**
      * Test from http://issues.apache.org/bugzilla/show_bug.cgi?id=33067
      */
-    @Test public void testNpeForNullElement() {
-        Object[] x1 = new Object[] { new Integer(1), null, new Integer(3) };
-        Object[] x2 = new Object[] { new Integer(1), new Integer(2), new Integer(3) };
+    @Test
+    public void testNpeForNullElement() {
+        Object[] x1 = new Object[] {new Integer(1), null, new Integer(3)};
+        Object[] x2 = new Object[] {new Integer(1), new Integer(2), new Integer(3)};
 
         // causes an NPE in 2.0 according to:
         // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067
         new EqualsBuilder().append(x1, x2);
     }
 
-    @Test public void testReflectionEqualsExcludeFields() throws Exception {
+    @Test
+    public void testReflectionEqualsExcludeFields() throws Exception {
         TestObjectWithMultipleFields x1 = new TestObjectWithMultipleFields(1, 2, 3);
         TestObjectWithMultipleFields x2 = new TestObjectWithMultipleFields(1, 3, 4);
 
@@ -977,7 +1098,9 @@ public int getB() {
 
         // still equal as long as both differing fields are among excluded
         assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three"}));
-        assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three", "xxx"}));
+        assertTrue(
+                EqualsBuilder.reflectionEquals(
+                        x1, x2, new String[] {"one", "two", "three", "xxx"}));
     }
 
     @SuppressWarnings("unused")
diff --git a/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java b/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java
index 04906df218..d0d7869e8b 100644
--- a/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java
+++ b/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java
@@ -22,6 +22,7 @@ static class MatcherWithDescription implements ArgumentMatcher {
         public boolean matches(Object argument) {
             return false;
         }
+
         public String toString() {
             return "*my custom description*";
         }
@@ -35,8 +36,13 @@ public boolean matches(Object argument) {
 
     @Test
     public void better_toString_for_matchers() {
-        assertEquals("", MatcherToString.toString(new MatcherWithoutDescription()));
-        assertEquals("*my custom description*", MatcherToString.toString(new MatcherWithDescription()));
-        assertEquals("*my custom description*", MatcherToString.toString(new MatcherWithInheritedDescription()));
+        assertEquals(
+                "",
+                MatcherToString.toString(new MatcherWithoutDescription()));
+        assertEquals(
+                "*my custom description*", MatcherToString.toString(new MatcherWithDescription()));
+        assertEquals(
+                "*my custom description*",
+                MatcherToString.toString(new MatcherWithInheritedDescription()));
     }
 }
diff --git a/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java b/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java
index d717a7616f..1ece06ca1e 100644
--- a/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java
+++ b/src/test/java/org/mockito/internal/matchers/text/ValuePrinterTest.java
@@ -4,7 +4,6 @@
  */
 package org.mockito.internal.matchers.text;
 
-
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.internal.matchers.text.ValuePrinter.print;
@@ -24,19 +23,30 @@ public void prints_values() {
         assertThat(print(3L)).isEqualTo("3L");
         assertThat(print(3.14d)).isEqualTo("3.14d");
         assertThat(print(3.14f)).isEqualTo("3.14f");
-        assertThat(print(new int[]{1, 2})).isEqualTo("[1, 2]");
-        assertThat(print(new LinkedHashMap() {{
-            put("foo", 2L);
-        }})).isEqualTo("{\"foo\" = 2L}");
-        assertThat(print(new LinkedHashMap() {{
-            put("int passed as hex", 0x01);
-            put("byte", (byte) 0x01);
-            put("short", (short) 2);
-            put("int", 3);
-            put("long", 4L);
-            put("float", 2.71f);
-            put("double", 3.14d);
-        }})).isEqualTo("{\"int passed as hex\" = 1, \"byte\" = (byte) 0x01, \"short\" = (short) 2, \"int\" = 3, \"long\" = 4L, \"float\" = 2.71f, \"double\" = 3.14d}");
+        assertThat(print(new int[] {1, 2})).isEqualTo("[1, 2]");
+        assertThat(
+                        print(
+                                new LinkedHashMap() {
+                                    {
+                                        put("foo", 2L);
+                                    }
+                                }))
+                .isEqualTo("{\"foo\" = 2L}");
+        assertThat(
+                        print(
+                                new LinkedHashMap() {
+                                    {
+                                        put("int passed as hex", 0x01);
+                                        put("byte", (byte) 0x01);
+                                        put("short", (short) 2);
+                                        put("int", 3);
+                                        put("long", 4L);
+                                        put("float", 2.71f);
+                                        put("double", 3.14d);
+                                    }
+                                }))
+                .isEqualTo(
+                        "{\"int passed as hex\" = 1, \"byte\" = (byte) 0x01, \"short\" = (short) 2, \"int\" = 3, \"long\" = 4L, \"float\" = 2.71f, \"double\" = 3.14d}");
         assertTrue(print(new UnsafeToString()).contains("UnsafeToString"));
         assertThat(print(new ToString())).isEqualTo("ToString");
         assertThat(print(new FormattedText("formatted"))).isEqualTo("formatted");
@@ -54,12 +64,11 @@ static class ToString {
         public String toString() {
             return "ToString";
         }
-
     }
+
     static class UnsafeToString {
         public String toString() {
             throw new RuntimeException("ka-boom!");
         }
-
     }
 }
diff --git a/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java b/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
index 8c0ab4a07f..4b812de6e5 100644
--- a/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
+++ b/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
@@ -53,15 +53,16 @@ public void shouldCheckIfVerificationWasFinished() throws Exception {
         try {
             mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
             fail();
-        } catch (MockitoException e) {}
+        } catch (MockitoException e) {
+        }
     }
 
     @Test
     public void shouldNotifyListenerSafely() throws Exception {
-        //when
+        // when
         mockingProgress.addListener(null);
 
-        //then no exception is thrown:
+        // then no exception is thrown:
         mockingProgress.mockingStarted(null, null);
     }
 
@@ -72,36 +73,39 @@ public void should_not_allow_redundant_listeners() {
 
         final Set listeners = new LinkedHashSet();
 
-        //when
+        // when
         MockingProgressImpl.addListener(listener1, listeners);
 
-        //then
-        Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
-            public void call() {
-                MockingProgressImpl.addListener(listener2, listeners);
-            }
-        }).isInstanceOf(RedundantListenerException.class);
+        // then
+        Assertions.assertThatThrownBy(
+                        new ThrowableAssert.ThrowingCallable() {
+                            public void call() {
+                                MockingProgressImpl.addListener(listener2, listeners);
+                            }
+                        })
+                .isInstanceOf(RedundantListenerException.class);
     }
 
     @Test
     public void should_clean_up_listeners_automatically() {
         MockitoListener someListener = mock(MockitoListener.class);
         MyListener cleanListener = mock(MyListener.class);
-        MyListener dirtyListener = when(mock(MyListener.class).isListenerDirty()).thenReturn(true).getMock();
+        MyListener dirtyListener =
+                when(mock(MyListener.class).isListenerDirty()).thenReturn(true).getMock();
 
         Set listeners = new LinkedHashSet();
 
-        //when
+        // when
         MockingProgressImpl.addListener(someListener, listeners);
         MockingProgressImpl.addListener(dirtyListener, listeners);
 
-        //then
+        // then
         Assertions.assertThat(listeners).containsExactlyInAnyOrder(someListener, dirtyListener);
 
-        //when
+        // when
         MockingProgressImpl.addListener(cleanListener, listeners);
 
-        //then dirty listener was removed automatically
+        // then dirty listener was removed automatically
         Assertions.assertThat(listeners).containsExactlyInAnyOrder(someListener, cleanListener);
     }
 
diff --git a/src/test/java/org/mockito/internal/progress/ThreadSafeMockingProgressTest.java b/src/test/java/org/mockito/internal/progress/ThreadSafeMockingProgressTest.java
index 183024126c..26ba1879d4 100644
--- a/src/test/java/org/mockito/internal/progress/ThreadSafeMockingProgressTest.java
+++ b/src/test/java/org/mockito/internal/progress/ThreadSafeMockingProgressTest.java
@@ -25,11 +25,11 @@ public void after() {
 
     @Test
     public void shouldShareState() throws Exception {
-        //given
+        // given
         MockingProgress p = mockingProgress();
         p.verificationStarted(new DummyVerificationMode());
 
-        //then
+        // then
         p = mockingProgress();
         assertNotNull(p.pullVerificationMode());
     }
@@ -37,11 +37,11 @@ public void shouldShareState() throws Exception {
     @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
     @Test
     public void shouldKnowWhenVerificationHasStarted() throws Exception {
-        //given
+        // given
         verify(mock(List.class));
         MockingProgress p = mockingProgress();
 
-        //then
+        // then
         assertNotNull(p.pullVerificationMode());
     }
 }
diff --git a/src/test/java/org/mockito/internal/progress/TimesTest.java b/src/test/java/org/mockito/internal/progress/TimesTest.java
index 53cb1c5574..a981e48e19 100644
--- a/src/test/java/org/mockito/internal/progress/TimesTest.java
+++ b/src/test/java/org/mockito/internal/progress/TimesTest.java
@@ -10,10 +10,8 @@
 import org.mockito.exceptions.base.MockitoException;
 import org.mockito.internal.verification.VerificationModeFactory;
 
-
-public class TimesTest  {
-    @Rule
-    public ExpectedException exception = ExpectedException.none();
+public class TimesTest {
+    @Rule public ExpectedException exception = ExpectedException.none();
 
     @Test
     public void shouldNotAllowNegativeNumberOfInvocations() throws Exception {
diff --git a/src/test/java/org/mockito/internal/progress/VerificationModeBuilder.java b/src/test/java/org/mockito/internal/progress/VerificationModeBuilder.java
index 3620887ab6..07fedacb39 100644
--- a/src/test/java/org/mockito/internal/progress/VerificationModeBuilder.java
+++ b/src/test/java/org/mockito/internal/progress/VerificationModeBuilder.java
@@ -4,7 +4,6 @@
  */
 package org.mockito.internal.progress;
 
-
 import org.mockito.internal.verification.Times;
 import org.mockito.internal.verification.VerificationModeFactory;
 
diff --git a/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java b/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java
index 123ee2965e..c8912ec223 100644
--- a/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java
+++ b/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java
@@ -26,16 +26,16 @@ public class DefaultInternalRunnerTest {
 
     private final RunListener runListener = mock(RunListener.class);
     private final MockitoTestListener mockitoTestListener = mock(MockitoTestListener.class);
-    private final Supplier supplier = new Supplier() {
-        public MockitoTestListener get() {
-            return mockitoTestListener;
-        }
-    };
+    private final Supplier supplier =
+            new Supplier() {
+                public MockitoTestListener get() {
+                    return mockitoTestListener;
+                }
+            };
 
     @Test
     public void does_not_fail_when_tests_succeeds() throws Exception {
-        new DefaultInternalRunner(SuccessTest.class, supplier)
-            .run(newNotifier(runListener));
+        new DefaultInternalRunner(SuccessTest.class, supplier).run(newNotifier(runListener));
 
         verifyTestFinishedSuccessfully();
     }
@@ -43,7 +43,7 @@ public void does_not_fail_when_tests_succeeds() throws Exception {
     @Test
     public void does_not_fail_second_test_when_first_test_fail() throws Exception {
         new DefaultInternalRunner(TestFailOnInitialization.class, supplier)
-            .run(newNotifier(runListener));
+                .run(newNotifier(runListener));
 
         verify(runListener, times(1)).testFailure(any(Failure.class));
         verify(runListener, times(1)).testFinished(any(Description.class));
@@ -51,8 +51,7 @@ public void does_not_fail_second_test_when_first_test_fail() throws Exception {
 
         reset(runListener, mockitoTestListener);
 
-        new DefaultInternalRunner(SuccessTest.class, supplier)
-            .run(newNotifier(runListener));
+        new DefaultInternalRunner(SuccessTest.class, supplier).run(newNotifier(runListener));
 
         verifyTestFinishedSuccessfully();
     }
@@ -60,7 +59,7 @@ public void does_not_fail_second_test_when_first_test_fail() throws Exception {
     @Test
     public void does_not_fail_when_rule_invokes_statement_multiple_times() throws Exception {
         new DefaultInternalRunner(TestWithRepeatingRule.class, supplier)
-            .run(newNotifier(runListener));
+                .run(newNotifier(runListener));
 
         verifyTestFinishedSuccessfully();
     }
@@ -87,8 +86,7 @@ public void this_test_is_NOT_supposed_to_fail() {
 
     public static final class TestFailOnInitialization {
 
-        @Mock
-        private System system;
+        @Mock private System system;
 
         @Test
         public void this_test_is_supposed_to_fail() {
@@ -99,12 +97,14 @@ public void this_test_is_supposed_to_fail() {
     public static final class TestWithRepeatingRule extends SuccessTest {
 
         @Rule
-        public TestRule rule = (base, description) -> new Statement() {
-            @Override
-            public void evaluate() throws Throwable {
-                base.evaluate();
-                base.evaluate();
-            }
-        };
+        public TestRule rule =
+                (base, description) ->
+                        new Statement() {
+                            @Override
+                            public void evaluate() throws Throwable {
+                                base.evaluate();
+                                base.evaluate();
+                            }
+                        };
     }
 }
diff --git a/src/test/java/org/mockito/internal/runners/util/RunnerProviderTest.java b/src/test/java/org/mockito/internal/runners/util/RunnerProviderTest.java
index 93b63228f9..da77bdc604 100644
--- a/src/test/java/org/mockito/internal/runners/util/RunnerProviderTest.java
+++ b/src/test/java/org/mockito/internal/runners/util/RunnerProviderTest.java
@@ -15,11 +15,12 @@ public class RunnerProviderTest extends TestBase {
 
     @Test
     public void shouldCreateRunnerInstance() throws Throwable {
-        //given
+        // given
         RunnerProvider provider = new RunnerProvider();
-        //when
-        InternalRunner runner = provider.newInstance(DefaultInternalRunner.class.getName(), this.getClass(), null);
-        //then
+        // when
+        InternalRunner runner =
+                provider.newInstance(DefaultInternalRunner.class.getName(), this.getClass(), null);
+        // then
         assertNotNull(runner);
     }
 }
diff --git a/src/test/java/org/mockito/internal/runners/util/TestMethodsFinderTest.java b/src/test/java/org/mockito/internal/runners/util/TestMethodsFinderTest.java
index c9b41c8dc2..18c5f6a5b3 100644
--- a/src/test/java/org/mockito/internal/runners/util/TestMethodsFinderTest.java
+++ b/src/test/java/org/mockito/internal/runners/util/TestMethodsFinderTest.java
@@ -13,7 +13,8 @@
 public class TestMethodsFinderTest extends TestBase {
 
     public static class HasTests {
-        @Test public void someTest() {}
+        @Test
+        public void someTest() {}
     }
 
     static class DoesNotHaveTests {
diff --git a/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java b/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java
index fc30d933da..19f9f31d8d 100644
--- a/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java
+++ b/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java
@@ -25,60 +25,84 @@
 
 public class DefaultMockitoSessionBuilderTest {
 
-    @After public void after() {
+    @After
+    public void after() {
         new StateMaster().clearMockitoListeners();
     }
 
-    @Test public void creates_sessions() {
-        //no configuration is legal
+    @Test
+    public void creates_sessions() {
+        // no configuration is legal
         new DefaultMockitoSessionBuilder().startMocking().finishMocking();
 
-        //passing null to configuration is legal, default value will be used
+        // passing null to configuration is legal, default value will be used
         new DefaultMockitoSessionBuilder().initMocks((Object) null).startMocking().finishMocking();
-        new DefaultMockitoSessionBuilder().initMocks((Object[]) null).startMocking().finishMocking();
-        new DefaultMockitoSessionBuilder().initMocks(null, null).strictness(null).startMocking().finishMocking();
+        new DefaultMockitoSessionBuilder()
+                .initMocks((Object[]) null)
+                .startMocking()
+                .finishMocking();
+        new DefaultMockitoSessionBuilder()
+                .initMocks(null, null)
+                .strictness(null)
+                .startMocking()
+                .finishMocking();
         new DefaultMockitoSessionBuilder().strictness(null).startMocking().finishMocking();
 
-        //happy path
+        // happy path
         new DefaultMockitoSessionBuilder().initMocks(this).startMocking().finishMocking();
         new DefaultMockitoSessionBuilder().initMocks(new Object()).startMocking().finishMocking();
-        new DefaultMockitoSessionBuilder().strictness(Strictness.LENIENT).startMocking().finishMocking();
+        new DefaultMockitoSessionBuilder()
+                .strictness(Strictness.LENIENT)
+                .startMocking()
+                .finishMocking();
     }
 
-    @Test public void creates_sessions_for_multiple_test_class_instances_for_repeated_calls() {
+    @Test
+    public void creates_sessions_for_multiple_test_class_instances_for_repeated_calls() {
         TestClass testClass = new TestClass();
         TestClass.NestedTestClass nestedTestClass = testClass.new NestedTestClass();
 
-        new DefaultMockitoSessionBuilder().initMocks(testClass).initMocks(nestedTestClass).startMocking().finishMocking();
+        new DefaultMockitoSessionBuilder()
+                .initMocks(testClass)
+                .initMocks(nestedTestClass)
+                .startMocking()
+                .finishMocking();
 
         assertNotNull(testClass.set);
         assertNotNull(nestedTestClass.list);
     }
 
-    @Test public void creates_sessions_for_multiple_test_class_instances_for_varargs_call() {
+    @Test
+    public void creates_sessions_for_multiple_test_class_instances_for_varargs_call() {
         TestClass testClass = new TestClass();
         TestClass.NestedTestClass nestedTestClass = testClass.new NestedTestClass();
 
-        new DefaultMockitoSessionBuilder().initMocks(testClass, nestedTestClass).startMocking().finishMocking();
+        new DefaultMockitoSessionBuilder()
+                .initMocks(testClass, nestedTestClass)
+                .startMocking()
+                .finishMocking();
 
         assertNotNull(testClass.set);
         assertNotNull(nestedTestClass.list);
     }
 
-    @Test public void uses_logger_and_strictness() {
+    @Test
+    public void uses_logger_and_strictness() {
         TestClass testClass = new TestClass();
 
         final List hints = new ArrayList();
-        MockitoSession session = new DefaultMockitoSessionBuilder()
-            .initMocks(testClass)
-            .strictness(WARN)
-            .logger(new MockitoSessionLogger() {
-                @Override
-                public void log(String hint) {
-                    hints.add(hint);
-                }
-            })
-            .startMocking();
+        MockitoSession session =
+                new DefaultMockitoSessionBuilder()
+                        .initMocks(testClass)
+                        .strictness(WARN)
+                        .logger(
+                                new MockitoSessionLogger() {
+                                    @Override
+                                    public void log(String hint) {
+                                        hints.add(hint);
+                                    }
+                                })
+                        .startMocking();
 
         when(testClass.set.add(1)).thenReturn(true);
 
@@ -87,24 +111,30 @@ public void log(String hint) {
         assertFalse(hints.isEmpty());
     }
 
-    @Test public void requires_finish_mocking() {
+    @Test
+    public void requires_finish_mocking() {
         new DefaultMockitoSessionBuilder().startMocking();
 
-        ThrowableAssert.assertThat(new Runnable() {
-            public void run() {
-                new DefaultMockitoSessionBuilder().startMocking();
-            }
-        }).throwsException(UnfinishedMockingSessionException.class);
+        ThrowableAssert.assertThat(
+                        new Runnable() {
+                            public void run() {
+                                new DefaultMockitoSessionBuilder().startMocking();
+                            }
+                        })
+                .throwsException(UnfinishedMockingSessionException.class);
     }
 
-    @Test public void auto_cleans_dirty_listeners() {
+    @Test
+    public void auto_cleans_dirty_listeners() {
         new DefaultMockitoSessionBuilder().startMocking();
 
-        ThrowableAssert.assertThat(new Runnable() {
-            public void run() {
-                new DefaultMockitoSessionBuilder().startMocking();
-            }
-        }).throwsException(UnfinishedMockingSessionException.class);
+        ThrowableAssert.assertThat(
+                        new Runnable() {
+                            public void run() {
+                                new DefaultMockitoSessionBuilder().startMocking();
+                            }
+                        })
+                .throwsException(UnfinishedMockingSessionException.class);
     }
 
     class TestClass {
diff --git a/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplStubbingTest.java b/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplStubbingTest.java
index 96599180ae..fafff6588f 100644
--- a/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplStubbingTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplStubbingTest.java
@@ -32,11 +32,13 @@ public void setup() {
         state = mockingProgress();
 
         invocationContainerImpl = new InvocationContainerImpl(new MockSettingsImpl());
-        invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationBuilder().toInvocationMatcher());
+        invocationContainerImpl.setInvocationForPotentialStubbing(
+                new InvocationBuilder().toInvocationMatcher());
 
         invocationContainerImplStubOnly =
-          new InvocationContainerImpl( new MockSettingsImpl().stubOnly());
-        invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationBuilder().toInvocationMatcher());
+                new InvocationContainerImpl(new MockSettingsImpl().stubOnly());
+        invocationContainerImplStubOnly.setInvocationForPotentialStubbing(
+                new InvocationBuilder().toInvocationMatcher());
 
         simpleMethod = new InvocationBuilder().simpleMethod().toInvocation();
     }
@@ -61,11 +63,13 @@ public void should_finish_stubbing_on_adding_return_value() throws Exception {
 
     @Test
     public void should_get_results_for_methods() throws Throwable {
-        invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
+        invocationContainerImpl.setInvocationForPotentialStubbing(
+                new InvocationMatcher(simpleMethod));
         invocationContainerImpl.addAnswer(new Returns("simpleMethod"), null);
 
         Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
-        invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
+        invocationContainerImpl.setInvocationForPotentialStubbing(
+                new InvocationMatcher(differentMethod));
         invocationContainerImpl.addAnswer(new ThrowsException(new MyException()), null);
 
         assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod));
@@ -73,16 +77,19 @@ public void should_get_results_for_methods() throws Throwable {
         try {
             invocationContainerImpl.answerTo(differentMethod);
             fail();
-        } catch (MyException e) {}
+        } catch (MyException e) {
+        }
     }
 
     @Test
     public void should_get_results_for_methods_stub_only() throws Throwable {
-        invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
+        invocationContainerImplStubOnly.setInvocationForPotentialStubbing(
+                new InvocationMatcher(simpleMethod));
         invocationContainerImplStubOnly.addAnswer(new Returns("simpleMethod"), null);
 
         Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
-        invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
+        invocationContainerImplStubOnly.setInvocationForPotentialStubbing(
+                new InvocationMatcher(differentMethod));
         invocationContainerImplStubOnly.addAnswer(new ThrowsException(new MyException()), null);
 
         assertEquals("simpleMethod", invocationContainerImplStubOnly.answerTo(simpleMethod));
@@ -90,7 +97,8 @@ public void should_get_results_for_methods_stub_only() throws Throwable {
         try {
             invocationContainerImplStubOnly.answerTo(differentMethod);
             fail();
-        } catch (MyException e) {}
+        } catch (MyException e) {
+        }
     }
 
     @Test
@@ -98,7 +106,8 @@ public void should_validate_throwable() throws Throwable {
         try {
             invocationContainerImpl.addAnswer(new ThrowsException(null), null);
             fail();
-        } catch (MockitoException e) {}
+        } catch (MockitoException e) {
+        }
     }
 
     @SuppressWarnings("serial")
diff --git a/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplTest.java b/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplTest.java
index 628af8cc8a..aef75eea45 100644
--- a/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/InvocationContainerImplTest.java
@@ -25,9 +25,9 @@
  */
 public class InvocationContainerImplTest {
 
-    InvocationContainerImpl container = new InvocationContainerImpl( new MockSettingsImpl());
+    InvocationContainerImpl container = new InvocationContainerImpl(new MockSettingsImpl());
     InvocationContainerImpl containerStubOnly =
-      new InvocationContainerImpl( (MockCreationSettings) new MockSettingsImpl().stubOnly());
+            new InvocationContainerImpl((MockCreationSettings) new MockSettingsImpl().stubOnly());
     Invocation invocation = new InvocationBuilder().toInvocation();
     LinkedList exceptions = new LinkedList();
 
@@ -41,40 +41,42 @@ public void should_be_thread_safe_stub_only() throws Throwable {
         doShouldBeThreadSafe(containerStubOnly);
     }
 
-    //works 50% of the time
+    // works 50% of the time
     private void doShouldBeThreadSafe(final InvocationContainerImpl c) throws Throwable {
-        //given
+        // given
         Thread[] t = new Thread[200];
         final CountDownLatch starter = new CountDownLatch(200);
-        for (int i = 0; i < t.length; i++ ) {
-            t[i] = new Thread() {
-                public void run() {
-                    try {
-                        starter.await(); //NOPMD
-                    } catch (InterruptedException e) {
-                        throw new RuntimeException(e);
-                    }
-                    c.setInvocationForPotentialStubbing(new InvocationMatcher(invocation));
-                    c.addAnswer(new Returns("foo"), null);
-                    c.findAnswerFor(invocation);
-                }
-            };
-            t[i].setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
-                public void uncaughtException(Thread t, Throwable e) {
-                    exceptions.add(e);
-                }
-            });
+        for (int i = 0; i < t.length; i++) {
+            t[i] =
+                    new Thread() {
+                        public void run() {
+                            try {
+                                starter.await(); // NOPMD
+                            } catch (InterruptedException e) {
+                                throw new RuntimeException(e);
+                            }
+                            c.setInvocationForPotentialStubbing(new InvocationMatcher(invocation));
+                            c.addAnswer(new Returns("foo"), null);
+                            c.findAnswerFor(invocation);
+                        }
+                    };
+            t[i].setUncaughtExceptionHandler(
+                    new Thread.UncaughtExceptionHandler() {
+                        public void uncaughtException(Thread t, Throwable e) {
+                            exceptions.add(e);
+                        }
+                    });
             t[i].start();
 
             starter.countDown();
         }
 
-        //when
+        // when
         for (Thread aT : t) {
             aT.join();
         }
 
-        //then
+        // then
         if (exceptions.size() != 0) {
             throw exceptions.getFirst();
         }
@@ -105,7 +107,8 @@ public void should_tell_if_has_invocation_for_potential_stubbing() throws Except
 
     @Test
     public void should_tell_if_has_invocation_for_potential_stubbing_stub_only() throws Exception {
-        containerStubOnly.setInvocationForPotentialStubbing(new InvocationBuilder().toInvocationMatcher());
+        containerStubOnly.setInvocationForPotentialStubbing(
+                new InvocationBuilder().toInvocationMatcher());
         assertTrue(containerStubOnly.hasInvocationForPotentialStubbing());
 
         containerStubOnly.addAnswer(new ReturnsEmptyValues(), null);
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java b/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java
index 8fa4d86f58..c4fa7a1820 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java
@@ -48,7 +48,8 @@ public void should_fill_in_exception_stacktrace() {
 
         Throwable throwable = Assertions.catchThrowable(() -> ate.answer(createMethodInvocation()));
         assertNotNull("Should have raised an exception.", throwable);
-        assertThat(throwable.getStackTrace()[0].getClassName()).isEqualTo(AbstractThrowsException.class.getName());
+        assertThat(throwable.getStackTrace()[0].getClassName())
+                .isEqualTo(AbstractThrowsException.class.getName());
         assertThat(throwable.getStackTrace()[0].getMethodName()).isEqualTo("answer");
     }
 
@@ -56,8 +57,9 @@ public void should_fill_in_exception_stacktrace() {
     public void should_invalidate_null_throwable() {
         AbstractThrowsException ate = instantiateFixture(null);
 
-        Throwable throwable = Assertions.catchThrowableOfType(() -> ate.validateFor(createMethodInvocation()),
-                                                              MockitoException.class);
+        Throwable throwable =
+                Assertions.catchThrowableOfType(
+                        () -> ate.validateFor(createMethodInvocation()), MockitoException.class);
         assertNotNull("Should have raised a MockitoException.", throwable);
         assertEquals(cannotStubWithNullThrowable().getMessage(), throwable.getMessage());
     }
@@ -66,10 +68,13 @@ public void should_invalidate_null_throwable() {
     public void should_throw_illegal_state_exception_if_null_answer() {
         AbstractThrowsException ate = instantiateFixture(null);
 
-        Throwable throwable = Assertions.catchThrowableOfType(() -> ate.answer(createMethodInvocation()),
-                                                              IllegalStateException.class);
+        Throwable throwable =
+                Assertions.catchThrowableOfType(
+                        () -> ate.answer(createMethodInvocation()), IllegalStateException.class);
         assertNotNull("Should have raised a IllegalStateException.", throwable);
-        assertEquals("throwable is null: you shall not call #answer if #validateFor fails!", throwable.getMessage());
+        assertEquals(
+                "throwable is null: you shall not call #answer if #validateFor fails!",
+                throwable.getMessage());
     }
 
     @Test
@@ -82,8 +87,9 @@ public void should_fail_invalid_checked_exception() {
         AbstractThrowsException ate = instantiateFixture(new IOException());
         Throwable comparison = ate.getThrowable();
 
-        Throwable throwable = Assertions.catchThrowableOfType(() -> ate.validateFor(createMethodInvocation()),
-                                                              MockitoException.class);
+        Throwable throwable =
+                Assertions.catchThrowableOfType(
+                        () -> ate.validateFor(createMethodInvocation()), MockitoException.class);
         assertNotNull("Should have raised a MockitoException.", throwable);
         assertEquals(checkedExceptionInvalid(comparison).getMessage(), throwable.getMessage());
     }
@@ -110,9 +116,7 @@ protected Throwable getThrowable() {
 
     /** Creates Invocation of a "canThrowException" method call. */
     private static Invocation createMethodInvocation() {
-        return new InvocationBuilder()
-            .method("canThrowException")
-            .toInvocation();
+        return new InvocationBuilder().method("canThrowException").toInvocation();
     }
 
     @Test
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java b/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java
index 488c1fcbc2..9f90d173df 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java
@@ -16,17 +16,26 @@
 public class AnswersWithDelayTest {
     @Test
     public void should_return_value() throws Throwable {
-        assertThat(new AnswersWithDelay(1, new Returns("value")).answer(new InvocationBuilder().method("oneArg").arg("A").toInvocation())).isEqualTo("value");
+        assertThat(
+                        new AnswersWithDelay(1, new Returns("value"))
+                                .answer(
+                                        new InvocationBuilder()
+                                                .method("oneArg")
+                                                .arg("A")
+                                                .toInvocation()))
+                .isEqualTo("value");
     }
 
     @Test(expected = MockitoException.class)
     public void should_fail_when_contained_answer_should_fail() throws Throwable {
-        new AnswersWithDelay(1, new Returns("one")).validateFor(new InvocationBuilder().method("voidMethod").toInvocation());
+        new AnswersWithDelay(1, new Returns("one"))
+                .validateFor(new InvocationBuilder().method("voidMethod").toInvocation());
     }
 
     @Test
     public void should_succeed_when_contained_answer_should_succeed() throws Throwable {
-        new AnswersWithDelay(1, new Returns("one")).validateFor(new InvocationBuilder().simpleMethod().toInvocation());
+        new AnswersWithDelay(1, new Returns("one"))
+                .validateFor(new InvocationBuilder().simpleMethod().toInvocation());
     }
 
     @Test
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/CallsRealMethodsTest.java b/src/test/java/org/mockito/internal/stubbing/answers/CallsRealMethodsTest.java
index 5f5f84d8d2..f8d904f2bb 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/CallsRealMethodsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/CallsRealMethodsTest.java
@@ -21,30 +21,34 @@ public class CallsRealMethodsTest {
 
     @Test
     public void should_delegate_to_returns_default_when_abstract_method() throws Throwable {
-        Invocation abstractMethod = new InvocationBuilder().method("booleanReturningMethod").toInvocation();
-        assertThat(new CallsRealMethods().answer(abstractMethod)).isEqualTo(RETURNS_DEFAULTS.answer(abstractMethod));
+        Invocation abstractMethod =
+                new InvocationBuilder().method("booleanReturningMethod").toInvocation();
+        assertThat(new CallsRealMethods().answer(abstractMethod))
+                .isEqualTo(RETURNS_DEFAULTS.answer(abstractMethod));
     }
 
     @Test
     public void should_fail_when_calling_real_method_on_interface() throws Throwable {
-        //given
-        Invocation invocationOnInterface = new InvocationBuilder().method("simpleMethod").toInvocation();
+        // given
+        Invocation invocationOnInterface =
+                new InvocationBuilder().method("simpleMethod").toInvocation();
         try {
-            //when
+            // when
             new CallsRealMethods().validateFor(invocationOnInterface);
-            //then
+            // then
             Assertions.fail("can not invoke interface");
-        } catch (MockitoException expected) {}
+        } catch (MockitoException expected) {
+        }
     }
 
     @Test
     public void should_be_OK_when_calling_real_method_on_concrete_class() throws Throwable {
-        //given
+        // given
         ArrayList mock = mock(ArrayList.class);
         mock.clear();
         Invocation invocationOnClass = new MockitoCore().getLastInvocation();
-        //when
+        // when
         new CallsRealMethods().validateFor(invocationOnClass);
-        //then no exception is thrown
+        // then no exception is thrown
     }
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/DefaultAnswerValidatorTest.java b/src/test/java/org/mockito/internal/stubbing/answers/DefaultAnswerValidatorTest.java
index cdfb8a5ac0..df78604bc7 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/DefaultAnswerValidatorTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/DefaultAnswerValidatorTest.java
@@ -14,14 +14,14 @@
 public class DefaultAnswerValidatorTest {
 
     @Test
-    public void should_fail_if_returned_value_of_answer_is_incompatible_with_return_type() throws Throwable {
+    public void should_fail_if_returned_value_of_answer_is_incompatible_with_return_type()
+            throws Throwable {
         // given
-        class AWrongType {
-        }
+        class AWrongType {}
         try {
             // when
-            DefaultAnswerValidator.validateReturnValueFor(new InvocationBuilder().method("toString").toInvocation(),
-                                                          new AWrongType());
+            DefaultAnswerValidator.validateReturnValueFor(
+                    new InvocationBuilder().method("toString").toInvocation(), new AWrongType());
             fail("expected validation to fail");
         } catch (WrongTypeOfReturnValue e) {
             // then
@@ -34,7 +34,7 @@ class AWrongType {
 
     @Test
     public void should_not_fail_if_returned_value_of_answer_is_null() throws Throwable {
-        DefaultAnswerValidator.validateReturnValueFor(new InvocationBuilder().method("toString").toInvocation(),
-                                                      null);
+        DefaultAnswerValidator.validateReturnValueFor(
+                new InvocationBuilder().method("toString").toInvocation(), null);
     }
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
index b03898b6c9..adb7974c61 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
@@ -16,7 +16,7 @@
 import org.mockito.invocation.Invocation;
 import org.mockitousage.IMethods;
 
-public class DoesNothingTest   {
+public class DoesNothingTest {
 
     private IMethods mock;
     private Invocation invocation_Void;
@@ -24,7 +24,7 @@ public class DoesNothingTest   {
     private Invocation invocation_String;
 
     @Before
-    public void init(){
+    public void init() {
         mock = mock(IMethods.class);
 
         mock.voidMethod();
@@ -45,12 +45,12 @@ public void answer_returnsNull() throws Throwable {
     }
 
     @Test(expected = MockitoException.class)
-    public void validateFor_nonVoidReturnType_shouldFail()   {
+    public void validateFor_nonVoidReturnType_shouldFail() {
         doesNothing().validateFor(invocation_String);
     }
 
     @Test
-    public void validateFor_voidReturnType_shouldPass()   {
+    public void validateFor_voidReturnType_shouldPass() {
         doesNothing().validateFor(invocation_void);
     }
 
@@ -70,5 +70,6 @@ T methodReturningT() {
             return null;
         }
     }
+
     static class SubclassWithGenericParameter extends SuperClassWithGenericParameter {}
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java b/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
index af193f27c3..3c9d96983d 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
@@ -20,62 +20,156 @@ public class InvocationInfoTest {
 
     @Test
     public void should_know_valid_throwables() throws Exception {
-        //when
+        // when
         Invocation invocation = new InvocationBuilder().method("canThrowException").toInvocation();
         InvocationInfo info = new InvocationInfo(invocation);
 
-        //then
+        // then
         assertThat(info.isValidException(new Exception())).isFalse();
         assertThat(info.isValidException(new CharacterCodingException())).isTrue();
     }
 
     @Test
     public void should_know_valid_return_types() throws Exception {
-        assertThat(new InvocationInfo(new InvocationBuilder().method("integerReturningMethod").toInvocation()).isValidReturnType(Integer.class)).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("integerReturningMethod").toInvocation()).isValidReturnType(int.class)).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("intReturningMethod").toInvocation()).isValidReturnType(Integer.class)).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("intReturningMethod").toInvocation()).isValidReturnType(int.class)).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("integerReturningMethod").toInvocation()).isValidReturnType(String.class)).isFalse();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("integerReturningMethod")
+                                                .toInvocation())
+                                .isValidReturnType(Integer.class))
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("integerReturningMethod")
+                                                .toInvocation())
+                                .isValidReturnType(int.class))
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("intReturningMethod")
+                                                .toInvocation())
+                                .isValidReturnType(Integer.class))
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("intReturningMethod")
+                                                .toInvocation())
+                                .isValidReturnType(int.class))
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("integerReturningMethod")
+                                                .toInvocation())
+                                .isValidReturnType(String.class))
+                .isFalse();
     }
 
     @Test
     public void should_know_when_invocation_returns_primitive() {
-        assertThat(new InvocationInfo(new InvocationBuilder().method("intReturningMethod").toInvocation()).returnsPrimitive()).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("integerReturningMethod").toInvocation()).returnsPrimitive()).isFalse();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("intReturningMethod")
+                                                .toInvocation())
+                                .returnsPrimitive())
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("integerReturningMethod")
+                                                .toInvocation())
+                                .returnsPrimitive())
+                .isFalse();
     }
 
     @Test
     public void should_know_when_invocation_returns_void() {
-        assertThat(new InvocationInfo(new InvocationBuilder().method("voidMethod").toInvocation()).isVoid()).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("integerReturningMethod").toInvocation()).isVoid()).isFalse();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder().method("voidMethod").toInvocation())
+                                .isVoid())
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("integerReturningMethod")
+                                                .toInvocation())
+                                .isVoid())
+                .isFalse();
     }
 
     @Test
     public void should_read_the_method_name() {
-        assertThat(new InvocationInfo(new InvocationBuilder().method("voidMethod").toInvocation()).getMethodName()).isEqualTo("voidMethod");
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder().method("voidMethod").toInvocation())
+                                .getMethodName())
+                .isEqualTo("voidMethod");
     }
 
     @Test
     public void should_read_the_method_return_name() {
-        assertThat(new InvocationInfo(new InvocationBuilder().method("voidMethod").toInvocation()).printMethodReturnType()).isEqualTo("void");
-        assertThat(new InvocationInfo(new InvocationBuilder().method("integerReturningMethod").toInvocation()).printMethodReturnType()).isEqualTo("Integer");
-        assertThat(new InvocationInfo(new InvocationBuilder().method("intReturningMethod").toInvocation()).printMethodReturnType()).isEqualTo("int");
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder().method("voidMethod").toInvocation())
+                                .printMethodReturnType())
+                .isEqualTo("void");
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("integerReturningMethod")
+                                                .toInvocation())
+                                .printMethodReturnType())
+                .isEqualTo("Integer");
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method("intReturningMethod")
+                                                .toInvocation())
+                                .printMethodReturnType())
+                .isEqualTo("int");
     }
 
     @Test
     public void should_know_abstract_method() throws Exception { // To be extended with Java 8
-        assertThat(new InvocationInfo(new InvocationBuilder().method(iAmAbstract()).toInvocation()).isAbstract()).isTrue();
-        assertThat(new InvocationInfo(new InvocationBuilder().method(iAmNotAbstract()).toInvocation()).isAbstract()).isFalse();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method(iAmAbstract())
+                                                .toInvocation())
+                                .isAbstract())
+                .isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method(iAmNotAbstract())
+                                                .toInvocation())
+                                .isAbstract())
+                .isFalse();
     }
 
     @Test
     public void should_know_method_is_declared_on_interface() throws Exception {
-        assertThat(new InvocationInfo(new InvocationBuilder().method(iAmAbstract()).toInvocation()).isDeclaredOnInterface()).isFalse();
-        assertThat(new InvocationInfo(new InvocationBuilder().method("voidMethod").toInvocation()).isDeclaredOnInterface()).isTrue();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder()
+                                                .method(iAmAbstract())
+                                                .toInvocation())
+                                .isDeclaredOnInterface())
+                .isFalse();
+        assertThat(
+                        new InvocationInfo(
+                                        new InvocationBuilder().method("voidMethod").toInvocation())
+                                .isDeclaredOnInterface())
+                .isTrue();
     }
 
     @Test
-    public void isVoid_invocationOnVoidMethod_returnTrue(){
+    public void isVoid_invocationOnVoidMethod_returnTrue() {
         mock(IMethods.class).voidMethod();
 
         InvocationInfo voidMethod = new InvocationInfo(getLastInvocation());
@@ -84,7 +178,7 @@ public void isVoid_invocationOnVoidMethod_returnTrue(){
     }
 
     @Test
-    public void isVoid_invocationOnVoidReturningMethod_returnTrue(){
+    public void isVoid_invocationOnVoidReturningMethod_returnTrue() {
         mock(IMethods.class).voidReturningMethod();
 
         InvocationInfo voidRetuningMethod = new InvocationInfo(getLastInvocation());
@@ -93,7 +187,7 @@ public void isVoid_invocationOnVoidReturningMethod_returnTrue(){
     }
 
     @Test
-    public void isVoid_invocationNonVoidMethod_returnFalse(){
+    public void isVoid_invocationNonVoidMethod_returnFalse() {
         mock(IMethods.class).simpleMethod();
 
         InvocationInfo stringReturningMethod = new InvocationInfo(getLastInvocation());
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
index 5675a3c9d8..be8b3159e2 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
@@ -22,8 +22,7 @@ public void should_be_able_to_return_the_first_parameter() throws Throwable {
     }
 
     @Test
-    public void should_be_able_to_return_the_second_parameter()
-            throws Throwable {
+    public void should_be_able_to_return_the_second_parameter() throws Throwable {
         assertThat(new ReturnsArgumentAt(1).answer(invocationWith("A", "B", "C"))).isEqualTo("B");
     }
 
@@ -43,100 +42,127 @@ public void should_be_able_to_return_the_specified_parameter() throws Throwable
     @Test
     public void should_identify_bad_parameter_type_for_invocation() throws Exception {
         try {
-            new ReturnsArgumentAt(1).validateFor(new InvocationBuilder().method("varargsReturningString")
-                                                                        .argTypes(Object[].class)
-                                                                        .args(new Object(), new Object(), new Object())
-                                                                        .toInvocation());
+            new ReturnsArgumentAt(1)
+                    .validateFor(
+                            new InvocationBuilder()
+                                    .method("varargsReturningString")
+                                    .argTypes(Object[].class)
+                                    .args(new Object(), new Object(), new Object())
+                                    .toInvocation());
             Assertions.fail("should scream");
-        } catch (WrongTypeOfReturnValue ignored) { }
+        } catch (WrongTypeOfReturnValue ignored) {
+        }
         try {
-            new ReturnsArgumentAt(0).validateFor(new InvocationBuilder().method("oneArray")
-                                                                        .argTypes(boolean[].class)
-                                                                        .args(true, false, false)
-                                                                        .toInvocation());
+            new ReturnsArgumentAt(0)
+                    .validateFor(
+                            new InvocationBuilder()
+                                    .method("oneArray")
+                                    .argTypes(boolean[].class)
+                                    .args(true, false, false)
+                                    .toInvocation());
             Assertions.fail("should scream");
-        } catch (WrongTypeOfReturnValue ignored) { }
+        } catch (WrongTypeOfReturnValue ignored) {
+        }
         try {
-            new ReturnsArgumentAt(0).validateFor(new InvocationBuilder().method("mixedVarargsReturningString")
-                                                                        .argTypes(Object.class, String[].class)
-                                                                        .args(new Object(), new String[]{"A", "B", "C"})
-                                                                        .toInvocation());
+            new ReturnsArgumentAt(0)
+                    .validateFor(
+                            new InvocationBuilder()
+                                    .method("mixedVarargsReturningString")
+                                    .argTypes(Object.class, String[].class)
+                                    .args(new Object(), new String[] {"A", "B", "C"})
+                                    .toInvocation());
             Assertions.fail("should scream");
-        } catch (WrongTypeOfReturnValue ignored) { }
+        } catch (WrongTypeOfReturnValue ignored) {
+        }
     }
 
     @Test
-    public void should_not_scream_when_mixed_vararg_parameter_is_compatible_with_invocation() throws Exception {
-        new ReturnsArgumentAt(1).validateFor(new InvocationBuilder().method("mixedVarargsReturningString")
-                                                                    .argTypes(Object.class, String[].class)
-                                                                    .args(new Object(), new String[]{"A", "B", "C"})
-                                                                    .toInvocation());
+    public void should_not_scream_when_mixed_vararg_parameter_is_compatible_with_invocation()
+            throws Exception {
+        new ReturnsArgumentAt(1)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("mixedVarargsReturningString")
+                                .argTypes(Object.class, String[].class)
+                                .args(new Object(), new String[] {"A", "B", "C"})
+                                .toInvocation());
     }
 
-        @Test
+    @Test
     public void should_handle_returning_vararg_as_array() throws Throwable {
-        Invocation mixedVarargsReturningStringArray = new InvocationBuilder().method("mixedVarargsReturningStringArray")
-                                                                             .argTypes(Object.class, String[].class)
-                                                                             .args(new Object(), new String[]{"A", "B", "C"})
-                                                                             .toInvocation();
+        Invocation mixedVarargsReturningStringArray =
+                new InvocationBuilder()
+                        .method("mixedVarargsReturningStringArray")
+                        .argTypes(Object.class, String[].class)
+                        .args(new Object(), new String[] {"A", "B", "C"})
+                        .toInvocation();
         new ReturnsArgumentAt(1).validateFor(mixedVarargsReturningStringArray);
-        assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningStringArray)).isEqualTo(new String[]{"A", "B", "C"});
-
-        Invocation mixedVarargsReturningObjectArray = new InvocationBuilder().method("mixedVarargsReturningStringArray")
-                                                                             .argTypes(Object.class, String[].class)
-                                                                             .args(new Object(), new String[]{"A", "B", "C"})
-                                                                             .toInvocation();
+        assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningStringArray))
+                .isEqualTo(new String[] {"A", "B", "C"});
+
+        Invocation mixedVarargsReturningObjectArray =
+                new InvocationBuilder()
+                        .method("mixedVarargsReturningStringArray")
+                        .argTypes(Object.class, String[].class)
+                        .args(new Object(), new String[] {"A", "B", "C"})
+                        .toInvocation();
         new ReturnsArgumentAt(1).validateFor(mixedVarargsReturningObjectArray);
-        assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningObjectArray)).isEqualTo(new String[]{"A", "B", "C"});
+        assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningObjectArray))
+                .isEqualTo(new String[] {"A", "B", "C"});
     }
 
     @Test
-    public void should_raise_an_exception_if_index_is_not_in_allowed_range_at_creation_time() throws Throwable {
+    public void should_raise_an_exception_if_index_is_not_in_allowed_range_at_creation_time()
+            throws Throwable {
         try {
             new ReturnsArgumentAt(-30);
             fail();
         } catch (Exception e) {
-            assertThat(e.getMessage()).containsIgnoringCase("argument index")
-                                      .containsIgnoringCase("positive number")
-                                      .contains("1")
-                                      .containsIgnoringCase("last argument");
+            assertThat(e.getMessage())
+                    .containsIgnoringCase("argument index")
+                    .containsIgnoringCase("positive number")
+                    .contains("1")
+                    .containsIgnoringCase("last argument");
         }
     }
 
     @Test
     public void should_allow_possible_argument_types() throws Exception {
-        new ReturnsArgumentAt(0).validateFor(
-                new InvocationBuilder().method("intArgumentReturningInt")
-                                       .argTypes(int.class)
-                                       .arg(1000)
-                                       .toInvocation()
-        );
-        new ReturnsArgumentAt(0).validateFor(
-                new InvocationBuilder().method("toString")
-                                       .argTypes(String.class)
-                                       .arg("whatever")
-                                       .toInvocation()
-        );
-        new ReturnsArgumentAt(2).validateFor(
-                new InvocationBuilder().method("varargsObject")
-                                       .argTypes(int.class, Object[].class)
-                                       .args(1000, "Object", "Object")
-                                       .toInvocation()
-        );
-        new ReturnsArgumentAt(1).validateFor(
-                new InvocationBuilder().method("threeArgumentMethod")
-                                       .argTypes(int.class, Object.class, String.class)
-                                       .args(1000, "Object", "String")
-                                       .toInvocation()
-        );
+        new ReturnsArgumentAt(0)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("intArgumentReturningInt")
+                                .argTypes(int.class)
+                                .arg(1000)
+                                .toInvocation());
+        new ReturnsArgumentAt(0)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("toString")
+                                .argTypes(String.class)
+                                .arg("whatever")
+                                .toInvocation());
+        new ReturnsArgumentAt(2)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("varargsObject")
+                                .argTypes(int.class, Object[].class)
+                                .args(1000, "Object", "Object")
+                                .toInvocation());
+        new ReturnsArgumentAt(1)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("threeArgumentMethod")
+                                .argTypes(int.class, Object.class, String.class)
+                                .args(1000, "Object", "String")
+                                .toInvocation());
     }
 
     @Test
     public void should_fail_if_index_is_not_in_range_for_one_arg_invocation() throws Throwable {
         try {
-            new ReturnsArgumentAt(30).validateFor(new InvocationBuilder().method("oneArg")
-                                                                         .arg("A")
-                                                                         .toInvocation());
+            new ReturnsArgumentAt(30)
+                    .validateFor(new InvocationBuilder().method("oneArg").arg("A").toInvocation());
             fail();
         } catch (MockitoException e) {
             assertThat(e.getMessage())
@@ -149,11 +175,11 @@ public void should_fail_if_index_is_not_in_range_for_one_arg_invocation() throws
     }
 
     @Test
-    public void should_fail_if_index_is_not_in_range_for_example_with_no_arg_invocation() throws Throwable {
+    public void should_fail_if_index_is_not_in_range_for_example_with_no_arg_invocation()
+            throws Throwable {
         try {
-            new ReturnsArgumentAt(ReturnsArgumentAt.LAST_ARGUMENT).validateFor(
-                    new InvocationBuilder().simpleMethod().toInvocation()
-            );
+            new ReturnsArgumentAt(ReturnsArgumentAt.LAST_ARGUMENT)
+                    .validateFor(new InvocationBuilder().simpleMethod().toInvocation());
             fail();
         } catch (MockitoException e) {
             assertThat(e.getMessage())
@@ -165,14 +191,16 @@ public void should_fail_if_index_is_not_in_range_for_example_with_no_arg_invocat
     }
 
     @Test
-    public void should_fail_if_argument_type_of_signature_is_incompatible_with_return_type() throws Throwable {
+    public void should_fail_if_argument_type_of_signature_is_incompatible_with_return_type()
+            throws Throwable {
         try {
-            new ReturnsArgumentAt(2).validateFor(
-                    new InvocationBuilder().method("varargsReturningString")
-                                           .argTypes(Object[].class)
-                                           .args("anyString", new Object(), "anyString")
-                                           .toInvocation()
-            );
+            new ReturnsArgumentAt(2)
+                    .validateFor(
+                            new InvocationBuilder()
+                                    .method("varargsReturningString")
+                                    .argTypes(Object[].class)
+                                    .args("anyString", new Object(), "anyString")
+                                    .toInvocation());
             fail();
         } catch (WrongTypeOfReturnValue e) {
             assertThat(e.getMessage())
@@ -187,19 +215,20 @@ public void should_fail_if_argument_type_of_signature_is_incompatible_with_retur
 
     @Test
     public void shouldNotFailWhenArgumentIsGenericAndCompatibleWithReturnType() throws Exception {
-        new ReturnsArgumentAt(0 ).validateFor(
-                new InvocationBuilder().method("genericToString")
-                                       .argTypes(Object.class)
-                                       .args("anyString")
-                                       .toInvocation()
-        );
+        new ReturnsArgumentAt(0)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("genericToString")
+                                .argTypes(Object.class)
+                                .args("anyString")
+                                .toInvocation());
     }
 
-
     private static InvocationOnMock invocationWith(Object... parameters) {
-        return new InvocationBuilder().method("varargsReturningString")
-                                      .argTypes(Object[].class)
-                                      .args(new Object[] { parameters }).toInvocation(); // one vararg param (sic!)
+        return new InvocationBuilder()
+                .method("varargsReturningString")
+                .argTypes(Object[].class)
+                .args(new Object[] {parameters})
+                .toInvocation(); // one vararg param (sic!)
     }
-
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java
index 5ec625946e..7c5980602c 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java
@@ -15,7 +15,14 @@
 public class ReturnsTest {
     @Test
     public void should_return_value() throws Throwable {
-        assertThat(new Returns("value").answer(new InvocationBuilder().method("oneArg").arg("A").toInvocation())).isEqualTo("value");
+        assertThat(
+                        new Returns("value")
+                                .answer(
+                                        new InvocationBuilder()
+                                                .method("oneArg")
+                                                .arg("A")
+                                                .toInvocation()))
+                .isEqualTo("value");
     }
 
     @Test(expected = MockitoException.class)
@@ -26,27 +33,52 @@ public void should_fail_when_return_Value_is_set_for_void_method() throws Throwa
     @Test
     public void should_allow_correct_type_of_return_value() throws Throwable {
         new Returns("one").validateFor(new InvocationBuilder().simpleMethod().toInvocation());
-        new Returns(false).validateFor(new InvocationBuilder().method("booleanReturningMethod").toInvocation());
-        new Returns(TRUE).validateFor(new InvocationBuilder().method("booleanObjectReturningMethod").toInvocation());
-        new Returns(1).validateFor(new InvocationBuilder().method("integerReturningMethod").toInvocation());
-        new Returns(1L).validateFor(new InvocationBuilder().method("longReturningMethod").toInvocation());
-        new Returns(1L).validateFor(new InvocationBuilder().method("longObjectReturningMethod").toInvocation());
-        new Returns(null).validateFor(new InvocationBuilder().method("objectReturningMethodNoArgs").toInvocation());
-        new Returns(1).validateFor(new InvocationBuilder().method("objectReturningMethodNoArgs").toInvocation());
+        new Returns(false)
+                .validateFor(
+                        new InvocationBuilder().method("booleanReturningMethod").toInvocation());
+        new Returns(TRUE)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("booleanObjectReturningMethod")
+                                .toInvocation());
+        new Returns(1)
+                .validateFor(
+                        new InvocationBuilder().method("integerReturningMethod").toInvocation());
+        new Returns(1L)
+                .validateFor(new InvocationBuilder().method("longReturningMethod").toInvocation());
+        new Returns(1L)
+                .validateFor(
+                        new InvocationBuilder().method("longObjectReturningMethod").toInvocation());
+        new Returns(null)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("objectReturningMethodNoArgs")
+                                .toInvocation());
+        new Returns(1)
+                .validateFor(
+                        new InvocationBuilder()
+                                .method("objectReturningMethodNoArgs")
+                                .toInvocation());
     }
 
     @Test(expected = MockitoException.class)
     public void should_fail_on_return_type_mismatch() throws Throwable {
-        new Returns("String").validateFor(new InvocationBuilder().method("booleanReturningMethod").toInvocation());
+        new Returns("String")
+                .validateFor(
+                        new InvocationBuilder().method("booleanReturningMethod").toInvocation());
     }
 
     @Test(expected = MockitoException.class)
     public void should_fail_on_wrong_primitive() throws Throwable {
-        new Returns(1).validateFor(new InvocationBuilder().method("doubleReturningMethod").toInvocation());
+        new Returns(1)
+                .validateFor(
+                        new InvocationBuilder().method("doubleReturningMethod").toInvocation());
     }
 
     @Test(expected = MockitoException.class)
     public void should_fail_on_null_with_primitive() throws Throwable {
-        new Returns(null).validateFor(new InvocationBuilder().method("booleanReturningMethod").toInvocation());
+        new Returns(null)
+                .validateFor(
+                        new InvocationBuilder().method("booleanReturningMethod").toInvocation());
     }
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java
index 9aa67d098a..ae1b8806c9 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java
@@ -12,14 +12,16 @@
 public class ThrowsExceptionForClassTypeTest {
     @Test
     public void should_return_throwable_of_expected_class() {
-        ThrowsExceptionForClassType throwsExceptionForClassType = new ThrowsExceptionForClassType(Exception.class);
+        ThrowsExceptionForClassType throwsExceptionForClassType =
+                new ThrowsExceptionForClassType(Exception.class);
 
         assertSame(Exception.class, throwsExceptionForClassType.getThrowable().getClass());
     }
 
     @Test
     public void should_return_different_throwables() {
-        ThrowsExceptionForClassType throwsExceptionForClassType = new ThrowsExceptionForClassType(Exception.class);
+        ThrowsExceptionForClassType throwsExceptionForClassType =
+                new ThrowsExceptionForClassType(Exception.class);
 
         Throwable first = throwsExceptionForClassType.getThrowable();
         Throwable second = throwsExceptionForClassType.getThrowable();
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
index 2da1e04596..9b8e799e29 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
@@ -18,15 +18,17 @@
 import org.mockito.internal.invocation.InvocationBuilder;
 import org.mockito.invocation.Invocation;
 
-
 public class ThrowsExceptionTest {
     @Test
     public void should_raise_wanted_throwable() throws Throwable {
         try {
-            new ThrowsException(new IllegalStateException("my dear throwable")).answer(createMethodInvocation());
+            new ThrowsException(new IllegalStateException("my dear throwable"))
+                    .answer(createMethodInvocation());
             Assertions.fail("should have raised wanted exception");
         } catch (Throwable throwable) {
-            assertThat(throwable).isInstanceOf(IllegalStateException.class).hasMessage("my dear throwable");
+            assertThat(throwable)
+                    .isInstanceOf(IllegalStateException.class)
+                    .hasMessage("my dear throwable");
         }
     }
 
@@ -45,8 +47,10 @@ public void should_fill_in_exception_stacktrace() throws Exception {
         // given
         Exception throwableToRaise = new Exception();
         throwableToRaise.fillInStackTrace();
-        assertThat(throwableToRaise.getStackTrace()[0].getClassName()).isEqualTo(this.getClass().getName());
-        assertThat(throwableToRaise.getStackTrace()[0].getMethodName()).isEqualTo("should_fill_in_exception_stacktrace");
+        assertThat(throwableToRaise.getStackTrace()[0].getClassName())
+                .isEqualTo(this.getClass().getName());
+        assertThat(throwableToRaise.getStackTrace()[0].getMethodName())
+                .isEqualTo("should_fill_in_exception_stacktrace");
         try {
 
             // when
@@ -55,7 +59,8 @@ public void should_fill_in_exception_stacktrace() throws Exception {
         } catch (Throwable throwable) {
             // then
             throwable.printStackTrace();
-            assertThat(throwableToRaise.getStackTrace()[0].getClassName()).isEqualTo(AbstractThrowsException.class.getName());
+            assertThat(throwableToRaise.getStackTrace()[0].getClassName())
+                    .isEqualTo(AbstractThrowsException.class.getName());
             assertThat(throwableToRaise.getStackTrace()[0].getMethodName()).isEqualTo("answer");
         }
     }
@@ -66,7 +71,8 @@ public void should_invalidate_null_throwable() throws Throwable {
             Invocation invocation = createMethodInvocation();
             new ThrowsException(null).validateFor(invocation);
             Assertions.fail("should have raised a MockitoException");
-        } catch (MockitoException expected) {}
+        } catch (MockitoException expected) {
+        }
     }
 
     @Test
@@ -114,8 +120,6 @@ public void should_return_same_throwable() {
 
     /** Creates Invocation of a "canThrowException" method call. */
     private static Invocation createMethodInvocation() {
-        return new InvocationBuilder()
-            .method("canThrowException")
-            .toInvocation();
+        return new InvocationBuilder().method("canThrowException").toInvocation();
     }
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
index e19ea5b7bb..a2a28ef60a 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
@@ -25,12 +25,17 @@ public int bar(String baz, Object... args) {
     @Test
     public void should_call_method_with_varargs() throws Throwable {
         ForwardsInvocations forwardsInvocations = new ForwardsInvocations(new FooImpl());
-        assertEquals(4, forwardsInvocations.answer(invocationOf(Foo.class, "bar", "b", new Object[] {12, "3", 4.5})));
+        assertEquals(
+                4,
+                forwardsInvocations.answer(
+                        invocationOf(Foo.class, "bar", "b", new Object[] {12, "3", 4.5})));
     }
 
     @Test
     public void should_call_method_with_empty_varargs() throws Throwable {
         ForwardsInvocations forwardsInvocations = new ForwardsInvocations(new FooImpl());
-        assertEquals(1, forwardsInvocations.answer(invocationOf(Foo.class, "bar", "b", new Object[] {})));
+        assertEquals(
+                1,
+                forwardsInvocations.answer(invocationOf(Foo.class, "bar", "b", new Object[] {})));
     }
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/HasPrimitiveMethods.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/HasPrimitiveMethods.java
index 9aaea02c06..77f3b64243 100755
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/HasPrimitiveMethods.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/HasPrimitiveMethods.java
@@ -7,11 +7,18 @@
 @SuppressWarnings("unused")
 interface HasPrimitiveMethods {
     boolean booleanMethod();
+
     char charMethod();
+
     byte byteMethod();
+
     short shortMethod();
+
     int intMethod();
+
     long longMethod();
+
     float floatMethod();
+
     double doubleMethod();
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
index 13ca291823..c80c746e8c 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
@@ -66,25 +66,25 @@ public void should_return_non_zero_for_compareTo_method() {
         d.compareTo(new Date());
         Invocation compareTo = this.getLastInvocation();
 
-        //when
+        // when
         Object result = values.answer(compareTo);
 
-        //then
+        // then
         assertTrue(result != (Object) 0);
     }
 
     @SuppressWarnings("SelfComparison")
     @Test
     public void should_return_zero_if_mock_is_compared_to_itself() {
-        //given
+        // given
         Date d = mock(Date.class);
         d.compareTo(d);
         Invocation compareTo = this.getLastInvocation();
 
-        //when
+        // when
         Object result = values.answer(compareTo);
 
-        //then
+        // then
         assertEquals(0, result);
     }
 
@@ -95,7 +95,8 @@ public void should_return_empty_Optional() throws Exception {
 
     @Test
     public void should_return_empty_OptionalDouble() throws Exception {
-        verify_empty_Optional_is_returned("java.util.stream.DoubleStream", "java.util.OptionalDouble");
+        verify_empty_Optional_is_returned(
+                "java.util.stream.DoubleStream", "java.util.OptionalDouble");
     }
 
     @Test
@@ -108,10 +109,11 @@ public void should_return_empty_OptionalLong() throws Exception {
         verify_empty_Optional_is_returned("java.util.stream.LongStream", "java.util.OptionalLong");
     }
 
-    private void verify_empty_Optional_is_returned(String streamFqcn, String optionalFqcn) throws Exception {
+    private void verify_empty_Optional_is_returned(String streamFqcn, String optionalFqcn)
+            throws Exception {
         Class streamType = getClassOrSkipTest(streamFqcn);
 
-        //given
+        // given
         Object stream = mock(streamType);
         Object optional = streamType.getMethod("findAny").invoke(stream);
         assertNotNull(optional);
@@ -119,10 +121,10 @@ private void verify_empty_Optional_is_returned(String streamFqcn, String optiona
 
         Invocation findAny = this.getLastInvocation();
 
-        //when
+        // when
         Object result = values.answer(findAny);
 
-        //then
+        // then
         assertEquals(optional, result);
     }
 
@@ -160,7 +162,7 @@ private void verify_empty_Stream_is_returned(String streamFqcn) throws Exception
 
     @Test
     public void should_return_empty_duration() throws Exception {
-        //given
+        // given
         final String fqcn = "java.time.Duration";
         final Class durationClass = getClassOrSkipTest(fqcn);
 
@@ -185,5 +187,4 @@ private Class getClassOrSkipTest(String className) {
             return null;
         }
     }
-
 }
diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
index 1d5b5f4f61..fb239c09be 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
@@ -21,11 +21,9 @@
 
 @SuppressWarnings("unused")
 public class ReturnsGenericDeepStubsTest {
-    interface ListOfInteger extends List {
-    }
+    interface ListOfInteger extends List {}
 
-    interface AnotherListOfInteger extends ListOfInteger {
-    }
+    interface AnotherListOfInteger extends ListOfInteger {}
 
     interface GenericsNest & Cloneable> extends Map> {
         Set remove(Object key); // override with fixed ParameterizedType
@@ -50,7 +48,8 @@ public void generic_deep_mock_frenzy__look_at_these_chained_calls() {
         GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
 
         Set>> entries = mock.entrySet();
-        Iterator>> entriesIterator = mock.entrySet().iterator();
+        Iterator>> entriesIterator =
+                mock.entrySet().iterator();
         Map.Entry> nextEntry = mock.entrySet().iterator().next();
 
         Cloneable cloneableKey = mock.entrySet().iterator().next().getKey();
@@ -62,17 +61,21 @@ public void generic_deep_mock_frenzy__look_at_these_chained_calls() {
     }
 
     @Test
-    public void can_create_mock_from_multiple_type_variable_bounds_when_return_type_of_parameterized_method_is_a_parameterizedType_that_is_referencing_a_typeVar_on_class() {
+    public void
+            can_create_mock_from_multiple_type_variable_bounds_when_return_type_of_parameterized_method_is_a_parameterizedType_that_is_referencing_a_typeVar_on_class() {
         GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
 
-        Cloneable cloneable_bound_that_is_declared_on_typevar_K_in_the_class_which_is_referenced_by_typevar_O_declared_on_the_method =
-            mock.paramTypeWithTypeParams().get(0);
-        Comparable comparable_bound_that_is_declared_on_typevar_K_in_the_class_which_is_referenced_by_typevar_O_declared_on_the_method =
-            mock.paramTypeWithTypeParams().get(0);
+        Cloneable
+                cloneable_bound_that_is_declared_on_typevar_K_in_the_class_which_is_referenced_by_typevar_O_declared_on_the_method =
+                        mock.paramTypeWithTypeParams().get(0);
+        Comparable
+                comparable_bound_that_is_declared_on_typevar_K_in_the_class_which_is_referenced_by_typevar_O_declared_on_the_method =
+                        mock.paramTypeWithTypeParams().get(0);
     }
 
     @Test
-    public void can_create_mock_from_multiple_type_variable_bounds_when_method_return_type_is_referencing_a_typeVar_on_class() {
+    public void
+            can_create_mock_from_multiple_type_variable_bounds_when_method_return_type_is_referencing_a_typeVar_on_class() {
         GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
 
         Cloneable cloneable_bound_of_typevar_K = mock.returningK();
@@ -80,11 +83,14 @@ public void can_create_mock_from_multiple_type_variable_bounds_when_method_retur
     }
 
     @Test
-    public void can_create_mock_from_multiple_type_variable_bounds_when_return_type_of_parameterized_method_is_a_typeVar_that_is_referencing_a_typeVar_on_class() {
+    public void
+            can_create_mock_from_multiple_type_variable_bounds_when_return_type_of_parameterized_method_is_a_typeVar_that_is_referencing_a_typeVar_on_class() {
         GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
 
-        Cloneable cloneable_bound_of_typevar_K_referenced_by_typevar_O = (Cloneable) mock.typeVarWithTypeParams();
-        Comparable comparable_bound_of_typevar_K_referenced_by_typevar_O = (Comparable) mock.typeVarWithTypeParams();
+        Cloneable cloneable_bound_of_typevar_K_referenced_by_typevar_O =
+                (Cloneable) mock.typeVarWithTypeParams();
+        Comparable comparable_bound_of_typevar_K_referenced_by_typevar_O =
+                (Comparable) mock.typeVarWithTypeParams();
     }
 
     @Test
@@ -92,7 +98,8 @@ public void can_create_mock_from_return_types_declared_with_a_bounded_wildcard()
         GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
 
         List objects = mock.returningWildcard();
-        Number type_that_is_the_upper_bound_of_the_wildcard = (Number) mock.returningWildcard().get(45);
+        Number type_that_is_the_upper_bound_of_the_wildcard =
+                (Number) mock.returningWildcard().get(45);
         type_that_is_the_upper_bound_of_the_wildcard.floatValue();
     }
 
@@ -108,20 +115,23 @@ public void can_still_work_with_raw_type_in_the_return_type() {
     public void will_return_default_value_on_non_mockable_nested_generic() {
         GenericsNest genericsNest = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
         ListOfInteger listOfInteger = mock(ListOfInteger.class, RETURNS_DEEP_STUBS);
-        AnotherListOfInteger anotherListOfInteger = mock(AnotherListOfInteger.class, RETURNS_DEEP_STUBS);
+        AnotherListOfInteger anotherListOfInteger =
+                mock(AnotherListOfInteger.class, RETURNS_DEEP_STUBS);
 
-        assertThat(genericsNest.returningNonMockableNestedGeneric().keySet().iterator().next()).isNull();
+        assertThat(genericsNest.returningNonMockableNestedGeneric().keySet().iterator().next())
+                .isNull();
         assertThat(listOfInteger.get(25)).isEqualTo(0);
         assertThat(anotherListOfInteger.get(25)).isEqualTo(0);
     }
 
     @Test(expected = ClassCastException.class)
-    public void as_expected_fail_with_a_CCE_on_call_site_when_erasure_takes_place_for_example___StringBuilder_is_subject_to_erasure() {
+    public void
+            as_expected_fail_with_a_CCE_on_call_site_when_erasure_takes_place_for_example___StringBuilder_is_subject_to_erasure() {
         GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
 
         // following assignment needed to create a ClassCastException on the call site (i.e. : here)
         StringBuilder stringBuilder_assignment_that_should_throw_a_CCE =
-            mock.twoTypeParams(new StringBuilder()).append(2).append(3);
+                mock.twoTypeParams(new StringBuilder()).append(2).append(3);
     }
 
     class WithGenerics {
@@ -130,8 +140,7 @@ T execute() {
         }
     }
 
-    class SubClass extends WithGenerics {
-    }
+    class SubClass extends WithGenerics {}
 
     class UserOfSubClass {
         SubClass generate() {
@@ -152,18 +161,19 @@ public interface TopInterface {
         T generic();
     }
 
-    public interface MiddleInterface extends TopInterface {
-    }
+    public interface MiddleInterface extends TopInterface {}
 
-    public class OwningClassWithDeclaredUpperBounds & Callable
& Closeable> { - public abstract class AbstractInner implements MiddleInterface { - } + public class OwningClassWithDeclaredUpperBounds< + T extends Iterable
& Callable
& Closeable> { + public abstract class AbstractInner implements MiddleInterface {} } @Test - public void cannot_handle_deep_stubs_with_generics_declared_upper_bounds_at_end_of_deep_invocation() throws Exception { + public void + cannot_handle_deep_stubs_with_generics_declared_upper_bounds_at_end_of_deep_invocation() + throws Exception { OwningClassWithDeclaredUpperBounds.AbstractInner mock = - mock(OwningClassWithDeclaredUpperBounds.AbstractInner.class, RETURNS_DEEP_STUBS); + mock(OwningClassWithDeclaredUpperBounds.AbstractInner.class, RETURNS_DEEP_STUBS); // It seems that while the syntax used on OwningClassWithDeclaredUpperBounds.AbstractInner // appear to be legal, the javac compiler does not follow through @@ -171,25 +181,28 @@ public void cannot_handle_deep_stubs_with_generics_declared_upper_bounds_at_end_ // extract matching data as well. assertThat(mock.generic()) - .describedAs("mock should implement first bound : 'Iterable'") - .isInstanceOf(Iterable.class); + .describedAs("mock should implement first bound : 'Iterable'") + .isInstanceOf(Iterable.class); assertThat(((Iterable
) mock.generic()).iterator()) - .describedAs("Iterable returns Iterator").isInstanceOf(Iterator.class); + .describedAs("Iterable returns Iterator") + .isInstanceOf(Iterator.class); assertThat(((Iterable
) mock.generic()).iterator().next()) - .describedAs("Cannot yet extract Type argument 'Article' so return null instead of a mock " - + "of type Object (which would raise CCE on the call-site)") - .isNull(); + .describedAs( + "Cannot yet extract Type argument 'Article' so return null instead of a mock " + + "of type Object (which would raise CCE on the call-site)") + .isNull(); assertThat(mock.generic()) - .describedAs("mock should implement second interface bound : 'Callable'") - .isInstanceOf(Callable.class); + .describedAs("mock should implement second interface bound : 'Callable'") + .isInstanceOf(Callable.class); assertThat(((Callable
) mock.generic()).call()) - .describedAs("Cannot yet extract Type argument 'Article' so return null instead of a mock " - + "of type Object (which would raise CCE on the call-site)") - .isNull(); + .describedAs( + "Cannot yet extract Type argument 'Article' so return null instead of a mock " + + "of type Object (which would raise CCE on the call-site)") + .isNull(); assertThat(mock.generic()) - .describedAs("mock should implement third interface bound : 'Closeable'") - .isInstanceOf(Closeable.class); + .describedAs("mock should implement third interface bound : 'Closeable'") + .isInstanceOf(Closeable.class); } } diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java index 758d7ea599..3691412e58 100755 --- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java +++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java @@ -19,19 +19,19 @@ public class ReturnsMocksTest extends TestBase { interface AllInterface { FooInterface getInterface(); + BarClass getNormalClass(); + Baz getFinalClass(); + WithGenerics withGenerics(); } - interface FooInterface { - } + interface FooInterface {} - class BarClass { - } + class BarClass {} - final class Baz { - } + final class Baz {} @Test public void should_return_mock_value_for_interface() throws Throwable { @@ -48,7 +48,9 @@ public void should_return_mock_value_for_class() throws Throwable { @SuppressWarnings("unchecked") @Test public void should_return_mock_value_for_generic_class() throws Throwable { - WithGenerics classMock = (WithGenerics) values.answer(invocationOf(AllInterface.class, "withGenerics")); + WithGenerics classMock = + (WithGenerics) + values.answer(invocationOf(AllInterface.class, "withGenerics")); assertTrue(MockUtil.isMock(classMock)); when(classMock.execute()).thenReturn("return"); assertEquals("return", classMock.execute()); @@ -63,10 +65,14 @@ public void should_return_null_for_final_class_if_unsupported() throws Throwable @Test public void should_return_the_usual_default_values_for_primitives() throws Throwable { ReturnsMocks answer = new ReturnsMocks(); - assertEquals(false, answer.answer(invocationOf(HasPrimitiveMethods.class, "booleanMethod"))); - assertEquals((char) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "charMethod"))); - assertEquals((byte) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "byteMethod"))); - assertEquals((short) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "shortMethod"))); + assertEquals( + false, answer.answer(invocationOf(HasPrimitiveMethods.class, "booleanMethod"))); + assertEquals( + (char) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "charMethod"))); + assertEquals( + (byte) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "byteMethod"))); + assertEquals( + (short) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "shortMethod"))); assertEquals(0, answer.answer(invocationOf(HasPrimitiveMethods.class, "intMethod"))); assertEquals(0L, answer.answer(invocationOf(HasPrimitiveMethods.class, "longMethod"))); assertEquals(0f, answer.answer(invocationOf(HasPrimitiveMethods.class, "floatMethod"))); @@ -76,12 +82,14 @@ public void should_return_the_usual_default_values_for_primitives() throws Throw @SuppressWarnings("unused") interface StringMethods { String stringMethod(); + String[] stringArrayMethod(); } @Test public void should_return_empty_array() throws Throwable { - String[] ret = (String[]) values.answer(invocationOf(StringMethods.class, "stringArrayMethod")); + String[] ret = + (String[]) values.answer(invocationOf(StringMethods.class, "stringArrayMethod")); assertTrue(ret.getClass().isArray()); assertTrue(ret.length == 0); diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java index 1cb0ac7245..870f0cee31 100644 --- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java +++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java @@ -33,24 +33,30 @@ public class ReturnsSmartNullsTest extends TestBase { @Test public void should_return_the_usual_default_values_for_primitives() throws Throwable { Answer answer = new ReturnsSmartNulls(); - assertEquals(false , answer.answer(invocationOf(HasPrimitiveMethods.class, "booleanMethod"))); - assertEquals((char) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "charMethod"))); - assertEquals((byte) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "byteMethod"))); - assertEquals((short) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "shortMethod"))); - assertEquals(0, answer.answer(invocationOf(HasPrimitiveMethods.class, "intMethod"))); - assertEquals(0L, answer.answer(invocationOf(HasPrimitiveMethods.class, "longMethod"))); - assertEquals(0f, answer.answer(invocationOf(HasPrimitiveMethods.class, "floatMethod"))); - assertEquals(0d, answer.answer(invocationOf(HasPrimitiveMethods.class, "doubleMethod"))); + assertEquals( + false, answer.answer(invocationOf(HasPrimitiveMethods.class, "booleanMethod"))); + assertEquals( + (char) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "charMethod"))); + assertEquals( + (byte) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "byteMethod"))); + assertEquals( + (short) 0, answer.answer(invocationOf(HasPrimitiveMethods.class, "shortMethod"))); + assertEquals(0, answer.answer(invocationOf(HasPrimitiveMethods.class, "intMethod"))); + assertEquals(0L, answer.answer(invocationOf(HasPrimitiveMethods.class, "longMethod"))); + assertEquals(0f, answer.answer(invocationOf(HasPrimitiveMethods.class, "floatMethod"))); + assertEquals(0d, answer.answer(invocationOf(HasPrimitiveMethods.class, "doubleMethod"))); } @SuppressWarnings("unused") interface Foo { Foo get(); + Foo withArgs(String oneArg, String otherArg); } @Test - public void should_return_an_object_that_fails_on_any_method_invocation_for_non_primitives() throws Throwable { + public void should_return_an_object_that_fails_on_any_method_invocation_for_non_primitives() + throws Throwable { Answer answer = new ReturnsSmartNulls(); Foo smartNull = (Foo) answer.answer(invocationOf(Foo.class, "get")); @@ -58,7 +64,8 @@ public void should_return_an_object_that_fails_on_any_method_invocation_for_non_ try { smartNull.get(); fail(); - } catch (SmartNullPointerException expected) {} + } catch (SmartNullPointerException expected) { + } } @Test @@ -67,9 +74,7 @@ public void should_return_an_object_that_allows_object_methods() throws Throwabl Foo smartNull = (Foo) answer.answer(invocationOf(Foo.class, "get")); - assertThat(smartNull.toString()) - .contains("SmartNull returned by") - .contains("foo.get()"); + assertThat(smartNull.toString()).contains("SmartNull returned by").contains("foo.get()"); } @Test @@ -79,13 +84,14 @@ public void should_print_the_parameters_when_calling_a_method_with_args() throws Foo smartNull = (Foo) answer.answer(invocationOf(Foo.class, "withArgs", "oompa", "lumpa")); assertThat(smartNull.toString()) - .contains("foo.withArgs") - .contains("oompa") - .contains("lumpa"); + .contains("foo.withArgs") + .contains("oompa") + .contains("lumpa"); } @Test - public void should_print_the_parameters_on_SmartNullPointerException_message() throws Throwable { + public void should_print_the_parameters_on_SmartNullPointerException_message() + throws Throwable { Answer answer = new ReturnsSmartNulls(); Foo smartNull = (Foo) answer.answer(invocationOf(Foo.class, "withArgs", "oompa", "lumpa")); @@ -94,9 +100,7 @@ public void should_print_the_parameters_on_SmartNullPointerException_message() t smartNull.get(); fail(); } catch (SmartNullPointerException e) { - assertThat(e) - .hasMessageContaining("oompa") - .hasMessageContaining("lumpa"); + assertThat(e).hasMessageContaining("oompa").hasMessageContaining("lumpa"); } } @@ -106,73 +110,77 @@ interface GenericFoo { interface GenericFooBar extends GenericFoo { I method(); + I methodWithArgs(int firstArg, I secondArg); + I methodWithVarArgs(int firstArg, I... secondArg); } @Test - public void should_return_an_object_that_has_been_defined_with_class_generic() throws Throwable { + public void should_return_an_object_that_has_been_defined_with_class_generic() + throws Throwable { Answer answer = new ReturnsSmartNulls(); Foo smartNull = (Foo) answer.answer(invocationOf(GenericFooBar.class, "get")); assertThat(smartNull.toString()) - .contains("SmartNull returned by") - .contains("genericFooBar.get()"); + .contains("SmartNull returned by") + .contains("genericFooBar.get()"); } @Test - public void should_return_an_object_that_has_been_defined_with_method_generic() throws Throwable { + public void should_return_an_object_that_has_been_defined_with_method_generic() + throws Throwable { Answer answer = new ReturnsSmartNulls(); String smartNull = (String) answer.answer(invocationOf(GenericFooBar.class, "method")); - assertThat(smartNull) - .isNull(); + assertThat(smartNull).isNull(); } - private static InterceptedInvocation invocationMethodWithArgs(final T obj) throws NoSuchMethodException { + private static InterceptedInvocation invocationMethodWithArgs(final T obj) + throws NoSuchMethodException { return new InterceptedInvocation( - new MockStrongReference(mock(GenericFooBar.class), false), - new SerializableMethod(GenericFooBar.class.getMethod("methodWithArgs", int.class, Object.class)), - new Object[]{1, obj}, - InterceptedInvocation.NO_OP, - new LocationImpl(), - 1); + new MockStrongReference(mock(GenericFooBar.class), false), + new SerializableMethod( + GenericFooBar.class.getMethod("methodWithArgs", int.class, Object.class)), + new Object[] {1, obj}, + InterceptedInvocation.NO_OP, + new LocationImpl(), + 1); } @Test - public void should_return_a_String_that_has_been_defined_with_method_generic_and_provided_in_argument() throws Throwable { + public void + should_return_a_String_that_has_been_defined_with_method_generic_and_provided_in_argument() + throws Throwable { Answer answer = new ReturnsSmartNulls(); Object smartNull = answer.answer(invocationMethodWithArgs("secondArg")); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(String.class) - .asString() - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(String.class).asString().isEmpty(); } @Test - public void should_return_a_empty_list_that_has_been_defined_with_method_generic_and_provided_in_argument() throws Throwable { + public void + should_return_a_empty_list_that_has_been_defined_with_method_generic_and_provided_in_argument() + throws Throwable { final List list = Collections.singletonList("String"); Answer answer = new ReturnsSmartNulls(); Object smartNull = answer.answer(invocationMethodWithArgs(list)); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(List.class); - assertThat((List) smartNull) - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(List.class); + assertThat((List) smartNull).isEmpty(); } @Test - public void should_return_a_empty_map_that_has_been_defined_with_method_generic_and_provided_in_argument() throws Throwable { + public void + should_return_a_empty_map_that_has_been_defined_with_method_generic_and_provided_in_argument() + throws Throwable { final Map map = new HashMap(); map.put("key-1", "value-1"); @@ -181,55 +189,54 @@ public void should_return_a_empty_map_that_has_been_defined_with_method_generic_ Object smartNull = answer.answer(invocationMethodWithArgs(map)); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(Map.class); - assertThat((Map) smartNull) - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(Map.class); + assertThat((Map) smartNull).isEmpty(); } @Test - public void should_return_a_empty_set_that_has_been_defined_with_method_generic_and_provided_in_argument() throws Throwable { + public void + should_return_a_empty_set_that_has_been_defined_with_method_generic_and_provided_in_argument() + throws Throwable { Answer answer = new ReturnsSmartNulls(); Object smartNull = - answer.answer(invocationMethodWithArgs(new HashSet(Arrays.asList("set-1", "set-2")))); + answer.answer( + invocationMethodWithArgs( + new HashSet(Arrays.asList("set-1", "set-2")))); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(Set.class); - assertThat((Set) smartNull) - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(Set.class); + assertThat((Set) smartNull).isEmpty(); } @Test - public void should_return_a_new_mock_that_has_been_defined_with_method_generic_and_provided_in_argument() throws Throwable { + public void + should_return_a_new_mock_that_has_been_defined_with_method_generic_and_provided_in_argument() + throws Throwable { Answer answer = new ReturnsSmartNulls(); final Foo mock = mock(Foo.class); Object smartNull = answer.answer(invocationMethodWithArgs(mock)); - assertThat(smartNull) - .isNotNull() - .isNotSameAs(mock); + assertThat(smartNull).isNotNull().isNotSameAs(mock); assertThat(smartNull.toString()) - .contains("SmartNull returned by") - .contains("genericFooBar.methodWithArgs("); + .contains("SmartNull returned by") + .contains("genericFooBar.methodWithArgs("); } @Test - public void should_return_an_Object_that_has_been_defined_with_method_generic_and_provided_in_argument() throws Throwable { + public void + should_return_an_Object_that_has_been_defined_with_method_generic_and_provided_in_argument() + throws Throwable { Answer answer = new ReturnsSmartNulls(); - Object smartNull = answer.answer(invocationMethodWithArgs(new Object() { - })); + Object smartNull = answer.answer(invocationMethodWithArgs(new Object() {})); assertThat(smartNull.toString()) - .contains("SmartNull returned by") - .contains("genericFooBar.methodWithArgs("); + .contains("SmartNull returned by") + .contains("genericFooBar.methodWithArgs("); } @Test @@ -238,135 +245,136 @@ public void should_throw_a_error_on_invocation_of_returned_mock() throws Throwab final Answer answer = new ReturnsSmartNulls(); final Foo mock = mock(Foo.class); - final Throwable throwable = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - ((Foo) answer.answer(invocationMethodWithArgs(mock))).get(); - } - }); + final Throwable throwable = + Assertions.catchThrowable( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + ((Foo) answer.answer(invocationMethodWithArgs(mock))).get(); + } + }); Assertions.assertThat(throwable) - .isInstanceOf(SmartNullPointerException.class) - .hasMessageContaining("genericFooBar.methodWithArgs(") - .hasMessageContaining("1") - .hasMessageContaining(mock.toString()); + .isInstanceOf(SmartNullPointerException.class) + .hasMessageContaining("genericFooBar.methodWithArgs(") + .hasMessageContaining("1") + .hasMessageContaining(mock.toString()); } - private static InterceptedInvocation invocationMethodWithVarArgs(final T[] obj) throws NoSuchMethodException { + private static InterceptedInvocation invocationMethodWithVarArgs(final T[] obj) + throws NoSuchMethodException { return new InterceptedInvocation( - new MockStrongReference(mock(GenericFooBar.class), false), - new SerializableMethod(GenericFooBar.class.getMethod("methodWithVarArgs", int.class, Object[].class)), - new Object[]{1, obj}, - InterceptedInvocation.NO_OP, - new LocationImpl(), - 1); + new MockStrongReference(mock(GenericFooBar.class), false), + new SerializableMethod( + GenericFooBar.class.getMethod( + "methodWithVarArgs", int.class, Object[].class)), + new Object[] {1, obj}, + InterceptedInvocation.NO_OP, + new LocationImpl(), + 1); } @Test - public void should_return_a_String_that_has_been_defined_with_method_generic_and_provided_in_var_args() - throws Throwable { + public void + should_return_a_String_that_has_been_defined_with_method_generic_and_provided_in_var_args() + throws Throwable { Answer answer = new ReturnsSmartNulls(); - Object smartNull = answer.answer(invocationMethodWithVarArgs(new String[]{"varArg-1", "varArg-2"})); + Object smartNull = + answer.answer(invocationMethodWithVarArgs(new String[] {"varArg-1", "varArg-2"})); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(String.class) - .asString() - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(String.class).asString().isEmpty(); } @Test - public void should_return_a_empty_list_that_has_been_defined_with_method_generic_and_provided_in_var_args() - throws Throwable { + public void + should_return_a_empty_list_that_has_been_defined_with_method_generic_and_provided_in_var_args() + throws Throwable { final List arg1 = Collections.singletonList("String"); final List arg2 = Arrays.asList("str-1", "str-2"); Answer answer = new ReturnsSmartNulls(); - Object smartNull = answer.answer(invocationMethodWithVarArgs(new List[]{arg1, arg2})); + Object smartNull = answer.answer(invocationMethodWithVarArgs(new List[] {arg1, arg2})); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(List.class); - assertThat((List) smartNull) - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(List.class); + assertThat((List) smartNull).isEmpty(); } @Test - public void should_return_a_empty_map_that_has_been_defined_with_method_generic_and_provided_in_var_args() - throws Throwable { - - final Map map1 = new HashMap() {{ - put("key-1", "value-1"); - put("key-2", "value-2"); - }}; - final Map map2 = new HashMap() {{ - put("key-3", "value-1"); - put("key-4", "value-2"); - }}; + public void + should_return_a_empty_map_that_has_been_defined_with_method_generic_and_provided_in_var_args() + throws Throwable { + + final Map map1 = + new HashMap() { + { + put("key-1", "value-1"); + put("key-2", "value-2"); + } + }; + final Map map2 = + new HashMap() { + { + put("key-3", "value-1"); + put("key-4", "value-2"); + } + }; Answer answer = new ReturnsSmartNulls(); - Object smartNull = answer.answer(invocationMethodWithVarArgs(new Map[]{map1, map2})); + Object smartNull = answer.answer(invocationMethodWithVarArgs(new Map[] {map1, map2})); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(Map.class); - assertThat((Map) smartNull) - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(Map.class); + assertThat((Map) smartNull).isEmpty(); } @Test - public void should_return_a_empty_set_that_has_been_defined_with_method_generic_and_provided_in_var_args() - throws Throwable { + public void + should_return_a_empty_set_that_has_been_defined_with_method_generic_and_provided_in_var_args() + throws Throwable { final HashSet set1 = new HashSet(Arrays.asList("set-1", "set-2")); final HashSet set2 = new HashSet(Arrays.asList("set-1", "set-2")); Answer answer = new ReturnsSmartNulls(); - Object smartNull = - answer.answer(invocationMethodWithVarArgs(new HashSet[]{set1, set2})); + Object smartNull = answer.answer(invocationMethodWithVarArgs(new HashSet[] {set1, set2})); - assertThat(smartNull) - .isNotNull() - .isInstanceOf(Set.class); - assertThat((Set) smartNull) - .isEmpty(); + assertThat(smartNull).isNotNull().isInstanceOf(Set.class); + assertThat((Set) smartNull).isEmpty(); } @Test - public void should_return_a_new_mock_that_has_been_defined_with_method_generic_and_provided_in_var_args() - throws Throwable { + public void + should_return_a_new_mock_that_has_been_defined_with_method_generic_and_provided_in_var_args() + throws Throwable { Answer answer = new ReturnsSmartNulls(); final Foo mock1 = mock(Foo.class); final Foo mock2 = mock(Foo.class); - Object smartNull = answer.answer(invocationMethodWithVarArgs(new Foo[]{mock1, mock2})); + Object smartNull = answer.answer(invocationMethodWithVarArgs(new Foo[] {mock1, mock2})); - assertThat(smartNull) - .isNotNull() - .isNotSameAs(mock1) - .isNotSameAs(mock2); + assertThat(smartNull).isNotNull().isNotSameAs(mock1).isNotSameAs(mock2); assertThat(smartNull.toString()) - .contains("SmartNull returned by") - .contains("genericFooBar.methodWithVarArgs("); + .contains("SmartNull returned by") + .contains("genericFooBar.methodWithVarArgs("); } @Test - public void should_return_an_Object_that_has_been_defined_with_method_generic_and_provided_in_var_args() - throws Throwable { + public void + should_return_an_Object_that_has_been_defined_with_method_generic_and_provided_in_var_args() + throws Throwable { Answer answer = new ReturnsSmartNulls(); - Object smartNull = answer.answer(invocationMethodWithVarArgs(new Object[]{new Object() { - }, new Object() { - }})); + Object smartNull = + answer.answer( + invocationMethodWithVarArgs( + new Object[] {new Object() {}, new Object() {}})); assertThat(smartNull.toString()) - .contains("SmartNull returned by") - .contains("genericFooBar.methodWithVarArgs("); + .contains("SmartNull returned by") + .contains("genericFooBar.methodWithVarArgs("); } - } diff --git a/src/test/java/org/mockito/internal/util/ChecksTest.java b/src/test/java/org/mockito/internal/util/ChecksTest.java index 3245b2f0ab..21d067d624 100644 --- a/src/test/java/org/mockito/internal/util/ChecksTest.java +++ b/src/test/java/org/mockito/internal/util/ChecksTest.java @@ -11,8 +11,7 @@ import org.junit.rules.ExpectedException; public class ChecksTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void checkNotNull_not_null() throws Exception { diff --git a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java index 0861f87863..f79818db41 100644 --- a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java +++ b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java @@ -36,27 +36,33 @@ public class DefaultMockingDetailsTest { @Mock private IMethods mock; @Spy private Gork gork; - @Before public void before() { + @Before + public void before() { MockitoAnnotations.initMocks(this); } @Test public void should_provide_original_mock() throws Exception { - //expect + // expect assertEquals(mockingDetails(foo).getMock(), foo); assertEquals(mockingDetails(null).getMock(), null); } @Test - public void should_know_spy(){ + public void should_know_spy() { assertTrue(mockingDetails(gork).isMock()); - assertTrue(mockingDetails(spy( new Gork())).isMock()); + assertTrue(mockingDetails(spy(new Gork())).isMock()); assertTrue(mockingDetails(spy(Gork.class)).isMock()); - assertTrue(mockingDetails(mock(Gork.class, withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS))).isMock()); + assertTrue( + mockingDetails( + mock( + Gork.class, + withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS))) + .isMock()); } @Test - public void should_know_mock(){ + public void should_know_mock() { assertTrue(mockingDetails(foo).isMock()); assertTrue(mockingDetails(mock(Foo.class)).isMock()); assertFalse(mockingDetails(foo).isSpy()); @@ -79,29 +85,31 @@ public void should_check_that_a_spy_is_also_a_mock() throws Exception { @Test public void provides_invocations() { - //when + // when mock.simpleMethod(10); mock.otherMethod(); - //then + // then assertEquals(0, mockingDetails(foo).getInvocations().size()); - assertEquals("[mock.simpleMethod(10);, mock.otherMethod();]", mockingDetails(mock).getInvocations().toString()); + assertEquals( + "[mock.simpleMethod(10);, mock.otherMethod();]", + mockingDetails(mock).getInvocations().toString()); } @Test public void manipulating_invocations_is_safe() { mock.simpleMethod(); - //when we manipulate the invocations + // when we manipulate the invocations mockingDetails(mock).getInvocations().clear(); - //then we didn't actually changed the invocations + // then we didn't actually changed the invocations assertEquals(1, mockingDetails(mock).getInvocations().size()); } @Test public void provides_mock_creation_settings() { - //smoke test some creation settings + // smoke test some creation settings assertEquals(Foo.class, mockingDetails(foo).getMockCreationSettings().getTypeToMock()); assertEquals(Bar.class, mockingDetails(bar).getMockCreationSettings().getTypeToMock()); assertEquals(0, mockingDetails(mock).getMockCreationSettings().getExtraInterfaces().size()); @@ -115,36 +123,42 @@ public void fails_when_getting_creation_settings_for_incorrect_input() { @Test public void fails_when_getting_invocations_when_null() { try { - //when + // when mockingDetails(null).getInvocations(); - //then + // then fail(); } catch (NotAMockException e) { - assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is null!", e.getMessage()); + assertEquals( + "Argument passed to Mockito.mockingDetails() should be a mock, but is null!", + e.getMessage()); } } @Test public void fails_when_getting_invocations_when_not_mock() { try { - //when + // when mockingDetails(new Object()).getInvocations(); - //then + // then fail(); } catch (NotAMockException e) { - assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", e.getMessage()); + assertEquals( + "Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", + e.getMessage()); } } @Test public void fails_when_getting_stubbings_from_non_mock() { try { - //when + // when mockingDetails(new Object()).getStubbings(); - //then + // then fail(); } catch (NotAMockException e) { - assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", e.getMessage()); + assertEquals( + "Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", + e.getMessage()); } } @@ -158,35 +172,37 @@ public void provides_stubbings_of_mock_in_declaration_order() { when(mock.simpleMethod(1)).thenReturn("1"); when(mock.otherMethod()).thenReturn("2"); - //when + // when Collection stubbings = mockingDetails(mock).getStubbings(); - //then + // then assertEquals(2, stubbings.size()); - assertEquals("[mock.simpleMethod(1); stubbed with: [Returns: 1], mock.otherMethod(); stubbed with: [Returns: 2]]", stubbings.toString()); + assertEquals( + "[mock.simpleMethod(1); stubbed with: [Returns: 1], mock.otherMethod(); stubbed with: [Returns: 2]]", + stubbings.toString()); } @Test public void manipulating_stubbings_explicitly_is_safe() { when(mock.simpleMethod(1)).thenReturn("1"); - //when somebody manipulates stubbings directly + // when somebody manipulates stubbings directly mockingDetails(mock).getStubbings().clear(); - //then it does not affect stubbings of the mock + // then it does not affect stubbings of the mock assertEquals(1, mockingDetails(mock).getStubbings().size()); } @Test public void prints_invocations() throws Exception { - //given + // given given(mock.simpleMethod("different arg")).willReturn("foo"); mock.simpleMethod("arg"); - //when + // when String log = Mockito.mockingDetails(mock).printInvocations(); - //then + // then assertThat(log).containsIgnoringCase("unused"); assertThat(log).containsIgnoringCase("mock.simpleMethod(\"arg\")"); assertThat(log).containsIgnoringCase("mock.simpleMethod(\"different arg\")"); @@ -195,16 +211,20 @@ public void prints_invocations() throws Exception { @Test public void fails_when_printin_invocations_from_non_mock() { try { - //when + // when mockingDetails(new Object()).printInvocations(); - //then + // then fail(); } catch (NotAMockException e) { - assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", e.getMessage()); + assertEquals( + "Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", + e.getMessage()); } } - public class Foo { } - public interface Bar { } - public static class Gork { } + public class Foo {} + + public interface Bar {} + + public static class Gork {} } diff --git a/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java b/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java index 1fdc7e7103..ccb134746b 100644 --- a/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java +++ b/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java @@ -23,38 +23,39 @@ public class MockCreationValidatorTest { MockCreationValidator validator = new MockCreationValidator(); @Test - public void should_not_allow_extra_interface_that_is_the_same_as_the_mocked_type() throws Exception { + public void should_not_allow_extra_interface_that_is_the_same_as_the_mocked_type() + throws Exception { try { - //when + // when validator.validateExtraInterfaces(IMethods.class, (Collection) asList(IMethods.class)); fail(); } catch (MockitoException e) { - //then + // then assertThat(e.getMessage()).contains("You mocked following type: IMethods"); } } @Test(expected = MockitoException.class) public void should_not_allow_inconsistent_types() throws Exception { - //when + // when validator.validateMockedType(List.class, new ArrayList()); - //then + // then } @Test public void should_allow_only_consistent_types() throws Exception { - //when + // when validator.validateMockedType(ArrayList.class, new ArrayList()); - //then no exception is thrown + // then no exception is thrown } @Test public void should_validation_be_safe_when_nulls_passed() throws Exception { - //when + // when validator.validateMockedType(null, new ArrayList()); - //or + // or validator.validateMockedType(ArrayList.class, null); - //then no exception is thrown + // then no exception is thrown } @Test diff --git a/src/test/java/org/mockito/internal/util/MockNameImplTest.java b/src/test/java/org/mockito/internal/util/MockNameImplTest.java index 7217eaeda4..e0bc019dc4 100644 --- a/src/test/java/org/mockito/internal/util/MockNameImplTest.java +++ b/src/test/java/org/mockito/internal/util/MockNameImplTest.java @@ -13,30 +13,31 @@ public class MockNameImplTest extends TestBase { @Test public void shouldProvideTheNameForClass() throws Exception { - //when + // when String name = new MockNameImpl(null, SomeClass.class).toString(); - //then + // then assertEquals("someClass", name); } @Test public void shouldProvideTheNameForAnonymousClass() throws Exception { - //given + // given SomeInterface anonymousInstance = new SomeInterface() {}; - //when + // when String name = new MockNameImpl(null, anonymousInstance.getClass()).toString(); - //then + // then assertEquals("someInterface", name); } @Test public void shouldProvideTheGivenName() throws Exception { - //when + // when String name = new MockNameImpl("The Hulk", SomeClass.class).toString(); - //then + // then assertEquals("The Hulk", name); } private class SomeClass {} + private class SomeInterface {} } diff --git a/src/test/java/org/mockito/internal/util/MockSettingsTest.java b/src/test/java/org/mockito/internal/util/MockSettingsTest.java index 5344937327..ab39828b10 100644 --- a/src/test/java/org/mockito/internal/util/MockSettingsTest.java +++ b/src/test/java/org/mockito/internal/util/MockSettingsTest.java @@ -18,22 +18,21 @@ public class MockSettingsTest extends TestBase { @Test public void public_api_for_creating_settings() throws Exception { - //when - MockCreationSettings settings = Mockito.withSettings() - .name("dummy") - .build(List.class); + // when + MockCreationSettings settings = + Mockito.withSettings().name("dummy").build(List.class); - //then + // then assertEquals(List.class, settings.getTypeToMock()); assertEquals("dummy", settings.getMockName().toString()); } + @Test public void test_without_annotations() throws Exception { - MockCreationSettings settings = Mockito.withSettings() - .withoutAnnotations() - .build(List.class); + MockCreationSettings settings = + Mockito.withSettings().withoutAnnotations().build(List.class); - CreationSettings copy = new CreationSettings((CreationSettings)settings); + CreationSettings copy = new CreationSettings((CreationSettings) settings); assertEquals(List.class, settings.getTypeToMock()); assertEquals(List.class, copy.getTypeToMock()); diff --git a/src/test/java/org/mockito/internal/util/MockUtilTest.java b/src/test/java/org/mockito/internal/util/MockUtilTest.java index 4eef4612ce..2e649eeaba 100644 --- a/src/test/java/org/mockito/internal/util/MockUtilTest.java +++ b/src/test/java/org/mockito/internal/util/MockUtilTest.java @@ -27,12 +27,12 @@ public void should_get_handler() { assertNotNull(MockUtil.getMockHandler(mock)); } - @Test (expected=NotAMockException.class) + @Test(expected = NotAMockException.class) public void should_scream_when_not_a_mock_passed() { MockUtil.getMockHandler(""); } - @Test (expected=MockitoException.class) + @Test(expected = MockitoException.class) public void should_scream_when_null_passed() { MockUtil.getMockHandler(null); } @@ -57,7 +57,11 @@ public void should_validate_spy() { assertTrue(MockUtil.isSpy(Mockito.spy(new ArrayList()))); assertTrue(MockUtil.isSpy(Mockito.spy(ArrayList.class))); - assertTrue(MockUtil.isSpy(Mockito.mock(ArrayList.class, withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS)))); + assertTrue( + MockUtil.isSpy( + Mockito.mock( + ArrayList.class, + withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS)))); } @Test @@ -77,7 +81,9 @@ public void should_not_redefine_MockName_if_default() { } final class FinalClass {} + class SomeClass {} + interface SomeInterface {} @Test diff --git a/src/test/java/org/mockito/internal/util/ObjectMethodsGuruTest.java b/src/test/java/org/mockito/internal/util/ObjectMethodsGuruTest.java index 016be1f61f..3f9c594a8d 100644 --- a/src/test/java/org/mockito/internal/util/ObjectMethodsGuruTest.java +++ b/src/test/java/org/mockito/internal/util/ObjectMethodsGuruTest.java @@ -15,34 +15,49 @@ public class ObjectMethodsGuruTest extends TestBase { - private interface HasCompareToButDoesNotImplementComparable { int compareTo(HasCompareToButDoesNotImplementComparable other); } private interface HasCompare extends Comparable { int foo(HasCompare other); + int compareTo(HasCompare other, String redHerring); + int compareTo(String redHerring); + int compareTo(HasCompare redHerring); } @Test public void shouldKnowToStringMethod() throws Exception { - assertFalse(ObjectMethodsGuru.isToStringMethod(Object.class.getMethod("equals", Object.class))); - assertFalse(ObjectMethodsGuru.isToStringMethod(IMethods.class.getMethod("toString", String.class))); + assertFalse( + ObjectMethodsGuru.isToStringMethod(Object.class.getMethod("equals", Object.class))); + assertFalse( + ObjectMethodsGuru.isToStringMethod( + IMethods.class.getMethod("toString", String.class))); assertTrue(ObjectMethodsGuru.isToStringMethod(IMethods.class.getMethod("toString"))); } - @Test public void shouldKnowCompareToMethod() throws Exception { assertFalse(ObjectMethodsGuru.isCompareToMethod(Date.class.getMethod("toString"))); - assertFalse(ObjectMethodsGuru.isCompareToMethod(HasCompare.class.getMethod("foo", HasCompare.class))); - assertFalse(ObjectMethodsGuru.isCompareToMethod(HasCompare.class.getMethod("compareTo", HasCompare.class, String.class))); - assertFalse(ObjectMethodsGuru.isCompareToMethod(HasCompare.class.getMethod("compareTo", String.class))); - assertFalse(ObjectMethodsGuru.isCompareToMethod(HasCompareToButDoesNotImplementComparable.class.getDeclaredMethod("compareTo", HasCompareToButDoesNotImplementComparable.class))); - - assertTrue(ObjectMethodsGuru.isCompareToMethod(HasCompare.class.getMethod("compareTo", HasCompare.class))); + assertFalse( + ObjectMethodsGuru.isCompareToMethod( + HasCompare.class.getMethod("foo", HasCompare.class))); + assertFalse( + ObjectMethodsGuru.isCompareToMethod( + HasCompare.class.getMethod("compareTo", HasCompare.class, String.class))); + assertFalse( + ObjectMethodsGuru.isCompareToMethod( + HasCompare.class.getMethod("compareTo", String.class))); + assertFalse( + ObjectMethodsGuru.isCompareToMethod( + HasCompareToButDoesNotImplementComparable.class.getDeclaredMethod( + "compareTo", HasCompareToButDoesNotImplementComparable.class))); + + assertTrue( + ObjectMethodsGuru.isCompareToMethod( + HasCompare.class.getMethod("compareTo", HasCompare.class))); } } diff --git a/src/test/java/org/mockito/internal/util/PlatformTest.java b/src/test/java/org/mockito/internal/util/PlatformTest.java index d41a5beac4..eef773dd64 100644 --- a/src/test/java/org/mockito/internal/util/PlatformTest.java +++ b/src/test/java/org/mockito/internal/util/PlatformTest.java @@ -42,17 +42,25 @@ public void const_are_initialized_from_system_properties() { @Test public void should_warn_for_jvm() throws Exception { - assertThat(Platform.warnForVM("Java HotSpot(TM) 64-Bit Server VM", - "HotSpot", "hotspot warning", - "IBM", "ibm warning")) + assertThat( + Platform.warnForVM( + "Java HotSpot(TM) 64-Bit Server VM", + "HotSpot", + "hotspot warning", + "IBM", + "ibm warning")) .isEqualTo("hotspot warning"); - assertThat(Platform.warnForVM("IBM J9 VM", - "HotSpot", "hotspot warning", - "IBM", "ibm warning")) + assertThat( + Platform.warnForVM( + "IBM J9 VM", "HotSpot", "hotspot warning", "IBM", "ibm warning")) .isEqualTo("ibm warning"); - assertThat(Platform.warnForVM("whatever", - null, "should not be returned", - null, "should not be returned")) + assertThat( + Platform.warnForVM( + "whatever", + null, + "should not be returned", + null, + "should not be returned")) .isEqualTo(""); } @@ -63,29 +71,35 @@ public void should_parse_open_jdk_string_and_report_wether_below_or_nut_update_4 // - http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html // - http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html // - http://www.oracle.com/technetwork/java/javase/jdk8-naming-2157130.html - // - http://stackoverflow.com/questions/35844985/how-do-we-get-sr-and-fp-of-ibm-jre-using-java - // - http://www.ibm.com/support/knowledgecenter/SSYKE2_6.0.0/com.ibm.java.doc.user.win32.60/user/java_version_check.html - Map versions = new HashMap() {{ - put("1.8.0_92-b14", false); - put("1.8.0-b24", true); - put("1.8.0_5", true); - put("1.8.0b5_u44", true); - put("1.8.0b5_u92", false); - put("1.7.0_4", false); - put("1.4.0_03-b04", false); - put("1.4.0_03-ea-b01", false); - put("pxi3270_27sr4-20160303_03 (SR4)", false); - put("pwi3260sr11-20120412_01 (SR11)", false); - put("pwa6480sr1fp10-20150711_01 (SR1 FP10)", false); - put("null", false); - }}; + // - + // http://stackoverflow.com/questions/35844985/how-do-we-get-sr-and-fp-of-ibm-jre-using-java + // - + // http://www.ibm.com/support/knowledgecenter/SSYKE2_6.0.0/com.ibm.java.doc.user.win32.60/user/java_version_check.html + Map versions = + new HashMap() { + { + put("1.8.0_92-b14", false); + put("1.8.0-b24", true); + put("1.8.0_5", true); + put("1.8.0b5_u44", true); + put("1.8.0b5_u92", false); + put("1.7.0_4", false); + put("1.4.0_03-b04", false); + put("1.4.0_03-ea-b01", false); + put("pxi3270_27sr4-20160303_03 (SR4)", false); + put("pwi3260sr11-20120412_01 (SR11)", false); + put("pwa6480sr1fp10-20150711_01 (SR1 FP10)", false); + put("null", false); + } + }; assertPlatformParsesCorrectlyVariousVersionScheme(versions); } @Test public void should_parse_open_jdk9_string() { - // The tested method targets Java 8 but should be able to parse other Java version numbers including Java 9 + // The tested method targets Java 8 but should be able to parse other Java version numbers + // including Java 9 // Given // Sources : @@ -120,21 +134,24 @@ public void should_parse_open_jdk9_string() { // java.specification.version 1.9 9 // java.vm.specification.version 1.9 9 // - Map versions = new HashMap() {{ - put("9-ea+73", false); - put("9+100", false); - put("9.1.2+62", false); - put("9.0.1+20", false); - }}; + Map versions = + new HashMap() { + { + put("9-ea+73", false); + put("9+100", false); + put("9.1.2+62", false); + put("9.0.1+20", false); + } + }; assertPlatformParsesCorrectlyVariousVersionScheme(versions); } - private void assertPlatformParsesCorrectlyVariousVersionScheme(Map versions) { for (Map.Entry version : versions.entrySet()) { - assertThat(Platform.isJava8BelowUpdate45(version.getKey())).describedAs(version.getKey()) - .isEqualTo(version.getValue()); + assertThat(Platform.isJava8BelowUpdate45(version.getKey())) + .describedAs(version.getKey()) + .isEqualTo(version.getValue()); } } } diff --git a/src/test/java/org/mockito/internal/util/PrimitivesTest.java b/src/test/java/org/mockito/internal/util/PrimitivesTest.java index b42bde8b07..214a7ec568 100644 --- a/src/test/java/org/mockito/internal/util/PrimitivesTest.java +++ b/src/test/java/org/mockito/internal/util/PrimitivesTest.java @@ -10,7 +10,6 @@ import org.junit.Test; - public class PrimitivesTest { @Test public void should_not_return_null_for_primitives_wrappers() throws Exception { diff --git a/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java b/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java index 2d6edae6fe..2c735fb3a0 100644 --- a/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java +++ b/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java @@ -29,7 +29,8 @@ public SimpleMockitoLogger clear() { public void assertEmpty() { if (loggedInfo.length() != 0) { - throw new AssertionError("Expected the logger to be empty but it has:\n" + loggedInfo.toString()); + throw new AssertionError( + "Expected the logger to be empty but it has:\n" + loggedInfo.toString()); } } } diff --git a/src/test/java/org/mockito/internal/util/SimpleMockitoLoggerTest.java b/src/test/java/org/mockito/internal/util/SimpleMockitoLoggerTest.java index 03b024aa94..a12d4daef9 100644 --- a/src/test/java/org/mockito/internal/util/SimpleMockitoLoggerTest.java +++ b/src/test/java/org/mockito/internal/util/SimpleMockitoLoggerTest.java @@ -13,11 +13,11 @@ public class SimpleMockitoLoggerTest extends TestBase { @Test public void shouldLog() throws Exception { - //given + // given SimpleMockitoLogger logger = new SimpleMockitoLogger(); - //when + // when logger.log("foo"); - //then + // then assertEquals("foo", logger.getLoggedInfo()); } } diff --git a/src/test/java/org/mockito/internal/util/StringUtilTest.java b/src/test/java/org/mockito/internal/util/StringUtilTest.java index d7f1168a17..e9c40538bc 100644 --- a/src/test/java/org/mockito/internal/util/StringUtilTest.java +++ b/src/test/java/org/mockito/internal/util/StringUtilTest.java @@ -12,14 +12,17 @@ import org.junit.Test; -public class StringUtilTest { +public class StringUtilTest { @Test public void decamelizes_matcher() throws Exception { - assertEquals("", StringUtil.decamelizeMatcher("SentenceWithStrongLanguage")); + assertEquals( + "", + StringUtil.decamelizeMatcher("SentenceWithStrongLanguage")); assertEquals("", StringUtil.decamelizeMatcher("WEIRDO1")); assertEquals("<_>", StringUtil.decamelizeMatcher("_")); - assertEquals("", StringUtil.decamelizeMatcher("HasExactly3Elements")); + assertEquals( + "", StringUtil.decamelizeMatcher("HasExactly3Elements")); assertEquals("", StringUtil.decamelizeMatcher("")); } @@ -36,7 +39,7 @@ public void joins_single_line() throws Exception { @Test public void joins_two_lines() throws Exception { - assertThat(StringUtil.join("line1","line2")).hasLineCount(3); + assertThat(StringUtil.join("line1", "line2")).hasLineCount(3); } @Test @@ -51,8 +54,7 @@ public void removes_first_line() throws Exception { @Test public void joins_with_line_prefix() throws Exception { - assertEquals("Hey!\n" + - " - a\n" + - " - b", StringUtil.join("Hey!\n", " - ", asList("a", "b"))); + assertEquals( + "Hey!\n" + " - a\n" + " - b", StringUtil.join("Hey!\n", " - ", asList("a", "b"))); } } diff --git a/src/test/java/org/mockito/internal/util/TimerTest.java b/src/test/java/org/mockito/internal/util/TimerTest.java index 8a4a173e02..f12efd83c5 100644 --- a/src/test/java/org/mockito/internal/util/TimerTest.java +++ b/src/test/java/org/mockito/internal/util/TimerTest.java @@ -12,32 +12,31 @@ import org.mockitoutil.TestBase; public class TimerTest extends TestBase { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void should_return_true_if_task_is_in_acceptable_time_bounds() { - //given + // given long duration = 10000L; Timer timer = new Timer(duration); - //when + // when timer.start(); - //then + // then Assertions.assertThat(timer.isCounting()).isTrue(); } @Test public void should_return_false_when_time_run_out() throws Exception { - //given + // given Timer timer = new Timer(0); timer.start(); - //when + // when oneMillisecondPasses(); - //then + // then Assertions.assertThat(timer.isCounting()).isFalse(); } diff --git a/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java b/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java index 031a654dd1..5085260a96 100644 --- a/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java +++ b/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java @@ -21,10 +21,8 @@ public class HashCodeAndEqualsSafeSetTest { - @Rule - public MockitoRule r = MockitoJUnit.rule(); - @Mock - private UnmockableHashCodeAndEquals mock1; + @Rule public MockitoRule r = MockitoJUnit.rule(); + @Mock private UnmockableHashCodeAndEquals mock1; @Test public void can_add_mock_that_have_failing_hashCode_method() throws Exception { @@ -57,12 +55,9 @@ public void can_remove() throws Exception { assertThat(mocks.isEmpty()).isTrue(); } - @Test public void can_add_a_collection() throws Exception { - HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of( - mock1, - mock(Observer.class)); + HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); HashCodeAndEqualsSafeSet workingSet = new HashCodeAndEqualsSafeSet(); @@ -73,9 +68,7 @@ public void can_add_a_collection() throws Exception { @Test public void can_retain_a_collection() throws Exception { - HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of( - mock1, - mock(Observer.class)); + HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); HashCodeAndEqualsSafeSet workingSet = new HashCodeAndEqualsSafeSet(); @@ -88,9 +81,7 @@ public void can_retain_a_collection() throws Exception { @Test public void can_remove_a_collection() throws Exception { - HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of( - mock1, - mock(Observer.class)); + HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); HashCodeAndEqualsSafeSet workingSet = new HashCodeAndEqualsSafeSet(); @@ -103,9 +94,7 @@ public void can_remove_a_collection() throws Exception { @Test public void can_iterate() throws Exception { - HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of( - mock1, - mock(Observer.class)); + HashCodeAndEqualsSafeSet mocks = HashCodeAndEqualsSafeSet.of(mock1, mock(Observer.class)); LinkedList accumulator = new LinkedList(); for (Object mock : mocks) { @@ -123,8 +112,8 @@ public void toArray_just_work() throws Exception { assertThat(mocks.toArray(new UnmockableHashCodeAndEquals[0])[0]).isSameAs(mock1); } - @Test(expected=CloneNotSupportedException.class) - public void cloneIsNotSupported() throws CloneNotSupportedException{ + @Test(expected = CloneNotSupportedException.class) + public void cloneIsNotSupported() throws CloneNotSupportedException { HashCodeAndEqualsSafeSet.of().clone(); } @@ -137,26 +126,26 @@ public void isEmptyAfterClear() throws Exception { } @Test - public void isEqualToItself(){ + public void isEqualToItself() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set).isEqualTo(set); } @Test - public void isNotEqualToAnOtherTypeOfSetWithSameContent(){ + public void isNotEqualToAnOtherTypeOfSetWithSameContent() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(); assertThat(set).isNotEqualTo(new HashSet()); } @Test - public void isNotEqualWhenContentIsDifferent(){ + public void isNotEqualWhenContentIsDifferent() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set).isNotEqualTo(HashCodeAndEqualsSafeSet.of()); } @Test - public void hashCodeIsEqualIfContentIsEqual(){ + public void hashCodeIsEqualIfContentIsEqual() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); assertThat(set.hashCode()).isEqualTo(HashCodeAndEqualsSafeSet.of(mock1).hashCode()); } @@ -178,11 +167,13 @@ public void removeByIterator() throws Exception { } private static class UnmockableHashCodeAndEquals { - @Override public final int hashCode() { + @Override + public final int hashCode() { throw new NullPointerException("I'm failing on hashCode and I don't care"); } - @Override public final boolean equals(Object obj) { + @Override + public final boolean equals(Object obj) { throw new NullPointerException("I'm failing on equals and I don't care"); } } diff --git a/src/test/java/org/mockito/internal/util/collections/IdentitySetTest.java b/src/test/java/org/mockito/internal/util/collections/IdentitySetTest.java index 5c44ee9846..1a44ba6ee8 100644 --- a/src/test/java/org/mockito/internal/util/collections/IdentitySetTest.java +++ b/src/test/java/org/mockito/internal/util/collections/IdentitySetTest.java @@ -8,18 +8,17 @@ import org.junit.Test; - public class IdentitySetTest { IdentitySet set = new IdentitySet(); @Test public void shouldWork() throws Exception { - //when + // when Object o = new Object(); set.add(o); - //then + // then assertTrue(set.contains(o)); assertFalse(set.contains(new Object())); } @@ -34,16 +33,15 @@ public boolean equals(Object obj) { @Test public void shouldWorkEvenIfEqualsTheSame() throws Exception { - //given + // given assertEquals(new Fake(), new Fake()); Fake fake = new Fake(); - //when + // when set.add(fake); - //then + // then assertTrue(set.contains(fake)); assertFalse(set.contains(new Fake())); } - } diff --git a/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java b/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java index ea8ad66bb9..6f47fe29b5 100644 --- a/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java +++ b/src/test/java/org/mockito/internal/util/collections/ListUtilTest.java @@ -21,11 +21,14 @@ public class ListUtilTest extends TestBase { @Test public void shouldFilterList() throws Exception { List list = asList("one", "x", "two", "x", "three"); - List filtered = ListUtil.filter(list, new Filter() { - public boolean isOut(String object) { - return object == "x"; - } - }); + List filtered = + ListUtil.filter( + list, + new Filter() { + public boolean isOut(String object) { + return object == "x"; + } + }); Assertions.assertThat(filtered).containsSequence("one", "two", "three"); } diff --git a/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java b/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java index b1af50258e..032cb53770 100644 --- a/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java @@ -29,9 +29,7 @@ public void safelyDisableAccess_should_fail_when_enableAccess_not_called() throw new AccessibilityChanger().safelyDisableAccess(field("whatever")); } - private Field field(String fieldName) throws NoSuchFieldException { return this.getClass().getDeclaredField(fieldName); } - } diff --git a/src/test/java/org/mockito/internal/util/reflection/BeanPropertySetterTest.java b/src/test/java/org/mockito/internal/util/reflection/BeanPropertySetterTest.java index 1bdd7de107..66d25c2171 100644 --- a/src/test/java/org/mockito/internal/util/reflection/BeanPropertySetterTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/BeanPropertySetterTest.java @@ -14,7 +14,6 @@ import org.assertj.core.api.Assertions; import org.junit.Test; - public class BeanPropertySetterTest { @Test @@ -34,7 +33,8 @@ public void use_the_correct_setter_on_the_target() throws Exception { } @Test - public void use_the_setter_on_the_target_when_field_name_begins_by_at_least_2_caps() throws Exception { + public void use_the_setter_on_the_target_when_field_name_begins_by_at_least_2_caps() + throws Exception { // given BeanWithWeirdFields someBean = new BeanWithWeirdFields(); Field theField = someBean.getClass().getDeclaredField("UUID"); @@ -50,7 +50,8 @@ public void use_the_setter_on_the_target_when_field_name_begins_by_at_least_2_ca } @Test - public void should_not_fail_if_bean_class_declares_only_the_setter_for_the_property() throws Exception { + public void should_not_fail_if_bean_class_declares_only_the_setter_for_the_property() + throws Exception { // given SomeBeanWithJustASetter someBean = new SomeBeanWithJustASetter(); Field theField = someBean.getClass().getDeclaredField("theField"); @@ -65,7 +66,8 @@ public void should_not_fail_if_bean_class_declares_only_the_setter_for_the_prope } @Test - public void should_fail_if_matching_setter_cannot_be_found_and_if_report_failure_is_true() throws Exception { + public void should_fail_if_matching_setter_cannot_be_found_and_if_report_failure_is_true() + throws Exception { // given SomeBeanWithNoSetterMatchingFieldType bean = new SomeBeanWithNoSetterMatchingFieldType(); Field theField = bean.getClass().getDeclaredField("theField"); @@ -96,7 +98,8 @@ public void return_false_if_no_setter_was_found() throws Exception { } @Test - public void return_false_if_no_setter_was_found_and_if_reportNoSetterFound_is_false() throws Exception { + public void return_false_if_no_setter_was_found_and_if_reportNoSetterFound_is_false() + throws Exception { // given SomeBeanWithNoSetterMatchingFieldType bean = new SomeBeanWithNoSetterMatchingFieldType(); Field theField = bean.getClass().getDeclaredField("theField"); @@ -132,6 +135,7 @@ public void setTheField(final File theField) { this.theField = theField; } } + static class SomeBeanWithJustAGetter { private File theField; @@ -158,5 +162,4 @@ public void setUUID(UUID UUID) { this.UUID = UUID; } } - } diff --git a/src/test/java/org/mockito/internal/util/reflection/DummyClassForTests.java b/src/test/java/org/mockito/internal/util/reflection/DummyClassForTests.java index 17d71ad3fa..51cb5f938b 100644 --- a/src/test/java/org/mockito/internal/util/reflection/DummyClassForTests.java +++ b/src/test/java/org/mockito/internal/util/reflection/DummyClassForTests.java @@ -4,6 +4,4 @@ */ package org.mockito.internal.util.reflection; -public class DummyClassForTests extends DummyParentClassForTests { - -} +public class DummyClassForTests extends DummyParentClassForTests {} diff --git a/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java b/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java index 6967c02c8a..a701dc96e7 100644 --- a/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java +++ b/src/test/java/org/mockito/internal/util/reflection/DummyParentClassForTests.java @@ -6,6 +6,6 @@ public class DummyParentClassForTests { - @SuppressWarnings("unused")//I know, I know. We're doing nasty reflection hacks here... + @SuppressWarnings("unused") // I know, I know. We're doing nasty reflection hacks here... private String somePrivateField; } diff --git a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java index 8fbe6ee0b2..aecdcb4fb0 100644 --- a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java @@ -17,8 +17,6 @@ import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver; - - public class FieldInitializerTest { private StaticClass alreadyInstantiated = new StaticClass(); @@ -31,13 +29,14 @@ public class FieldInitializerTest { private Interface interfaceType; private InnerClassType innerClassType; private AbstractStaticClass instantiatedAbstractType = new ConcreteStaticClass(); - private Interface instantiatedInterfaceType = new ConcreteStaticClass(); + private Interface instantiatedInterfaceType = new ConcreteStaticClass(); private InnerClassType instantiatedInnerClassType = new InnerClassType(); @Test public void should_keep_same_instance_if_field_initialized() throws Exception { final StaticClass backupInstance = alreadyInstantiated; - FieldInitializer fieldInitializer = new FieldInitializer(this, field("alreadyInstantiated")); + FieldInitializer fieldInitializer = + new FieldInitializer(this, field("alreadyInstantiated")); FieldInitializationReport report = fieldInitializer.initialize(); assertSame(backupInstance, report.fieldInstance()); @@ -67,7 +66,8 @@ public void should_instantiate_field_with_default_constructor() throws Exception @Test public void should_instantiate_field_with_private_default_constructor() throws Exception { - FieldInitializer fieldInitializer = new FieldInitializer(this, field("privateDefaultConstructor")); + FieldInitializer fieldInitializer = + new FieldInitializer(this, field("privateDefaultConstructor")); FieldInitializationReport report = fieldInitializer.initialize(); assertNotNull(report.fieldInstance()); @@ -77,13 +77,16 @@ public void should_instantiate_field_with_private_default_constructor() throws E @Test(expected = MockitoException.class) public void should_fail_to_instantiate_field_if_no_default_constructor() throws Exception { - FieldInitializer fieldInitializer = new FieldInitializer(this, field("noDefaultConstructor")); + FieldInitializer fieldInitializer = + new FieldInitializer(this, field("noDefaultConstructor")); fieldInitializer.initialize(); } @Test - public void should_fail_to_instantiate_field_if_default_constructor_throws_exception() throws Exception { - FieldInitializer fieldInitializer = new FieldInitializer(this, field("throwingExDefaultConstructor")); + public void should_fail_to_instantiate_field_if_default_constructor_throws_exception() + throws Exception { + FieldInitializer fieldInitializer = + new FieldInitializer(this, field("throwingExDefaultConstructor")); try { fieldInitializer.initialize(); fail(); @@ -117,7 +120,7 @@ public void should_not_fail_if_interface_field_is_instantiated() throws Exceptio @Test(expected = MockitoException.class) public void should_fail_for_local_type_field() throws Exception { // when - class LocalType { } + class LocalType {} class TheTestWithLocalType { @InjectMocks LocalType field; @@ -126,13 +129,14 @@ class TheTestWithLocalType { TheTestWithLocalType testWithLocalType = new TheTestWithLocalType(); // when - new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field")); + new FieldInitializer( + testWithLocalType, testWithLocalType.getClass().getDeclaredField("field")); } @Test public void should_not_fail_if_local_type_field_is_instantiated() throws Exception { // when - class LocalType { } + class LocalType {} class TheTestWithLocalType { @InjectMocks LocalType field = new LocalType(); @@ -141,7 +145,8 @@ class TheTestWithLocalType { TheTestWithLocalType testWithLocalType = new TheTestWithLocalType(); // when - new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field")); + new FieldInitializer( + testWithLocalType, testWithLocalType.getClass().getDeclaredField("field")); } @Test(expected = MockitoException.class) @@ -156,8 +161,12 @@ public void should_not_fail_if_inner_class_field_is_instantiated() throws Except @Test public void can_instantiate_class_with_parameterized_constructor() throws Exception { - ConstructorArgumentResolver resolver = given(mock(ConstructorArgumentResolver.class).resolveTypeInstances(any(Class.class))) - .willReturn(new Object[]{null}).getMock(); + ConstructorArgumentResolver resolver = + given( + mock(ConstructorArgumentResolver.class) + .resolveTypeInstances(any(Class.class))) + .willReturn(new Object[] {null}) + .getMock(); new FieldInitializer(this, field("noDefaultConstructor"), resolver).initialize(); @@ -168,19 +177,18 @@ private Field field(String fieldName) throws NoSuchFieldException { return this.getClass().getDeclaredField(fieldName); } - static class StaticClass { - } + static class StaticClass {} static class StaticClassWithDefaultConstructor { - StaticClassWithDefaultConstructor() { } + StaticClassWithDefaultConstructor() {} } static class StaticClassWithPrivateDefaultConstructor { - private StaticClassWithPrivateDefaultConstructor() { } + private StaticClassWithPrivateDefaultConstructor() {} } static class StaticClassWithoutDefaultConstructor { - private StaticClassWithoutDefaultConstructor(String param) { } + private StaticClassWithoutDefaultConstructor(String param) {} } static class StaticClassThrowingExceptionDefaultConstructor { @@ -189,19 +197,15 @@ static class StaticClassThrowingExceptionDefaultConstructor { } } - static abstract class AbstractStaticClass { + abstract static class AbstractStaticClass { public AbstractStaticClass() {} } - interface Interface { + interface Interface {} - } - - static class ConcreteStaticClass extends AbstractStaticClass implements Interface { - } + static class ConcreteStaticClass extends AbstractStaticClass implements Interface {} class InnerClassType { - InnerClassType() { } + InnerClassType() {} } - } diff --git a/src/test/java/org/mockito/internal/util/reflection/FieldReaderTest.java b/src/test/java/org/mockito/internal/util/reflection/FieldReaderTest.java index 2eae0c34e9..2e9aeb82d6 100644 --- a/src/test/java/org/mockito/internal/util/reflection/FieldReaderTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/FieldReaderTest.java @@ -20,17 +20,17 @@ class Foo { @Test public void shouldKnowWhenNull() throws Exception { - //when + // when FieldReader reader = new FieldReader(new Foo(), Foo.class.getDeclaredField("isNull")); - //then + // then assertTrue(reader.isNull()); } @Test public void shouldKnowWhenNotNull() throws Exception { - //when + // when FieldReader reader = new FieldReader(new Foo(), Foo.class.getDeclaredField("notNull")); - //then + // then assertFalse(reader.isNull()); } } diff --git a/src/test/java/org/mockito/internal/util/reflection/FieldsTest.java b/src/test/java/org/mockito/internal/util/reflection/FieldsTest.java index 897cc2a218..270cfaefdf 100644 --- a/src/test/java/org/mockito/internal/util/reflection/FieldsTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/FieldsTest.java @@ -15,58 +15,69 @@ public class FieldsTest { @Test public void fields_should_return_all_declared_fields_in_hierarchy() throws Exception { - assertThat(Fields.allDeclaredFieldsOf(new HierarchyOfClasses()).filter(syntheticField()).names()) + assertThat( + Fields.allDeclaredFieldsOf(new HierarchyOfClasses()) + .filter(syntheticField()) + .names()) .containsOnly("a", "b", "static_a", "static_b"); } @Test public void fields_should_return_declared_fields() throws Exception { - assertThat(Fields.declaredFieldsOf(new HierarchyOfClasses()).filter(syntheticField()).names()) + assertThat( + Fields.declaredFieldsOf(new HierarchyOfClasses()) + .filter(syntheticField()) + .names()) .containsOnly("b", "static_b"); } @Test public void can_filter_not_null_fields() throws Exception { - assertThat(Fields.declaredFieldsOf(new NullOrNotNullFields()).notNull().filter(syntheticField()).names()) + assertThat( + Fields.declaredFieldsOf(new NullOrNotNullFields()) + .notNull() + .filter(syntheticField()) + .names()) .containsOnly("c"); } @Test public void can_get_values_of_instance_fields() throws Exception { - assertThat(Fields.declaredFieldsOf(new ValuedFields()).filter(syntheticField()).assignedValues()) + assertThat( + Fields.declaredFieldsOf(new ValuedFields()) + .filter(syntheticField()) + .assignedValues()) .containsOnly("a", "b"); } - @Test public void can_get_list_of_InstanceField() throws Exception { ValuedFields instance = new ValuedFields(); assertThat(Fields.declaredFieldsOf(instance).filter(syntheticField()).instanceFields()) - .containsOnly(new InstanceField(field("a", instance), instance), - new InstanceField(field("b", instance), instance) - ); + .containsOnly( + new InstanceField(field("a", instance), instance), + new InstanceField(field("b", instance), instance)); } private Field field(String name, Object instance) throws NoSuchFieldException { return instance.getClass().getDeclaredField(name); } - interface AnInterface { int someStaticInInterface = 0; - } + public static class ParentClass implements AnInterface { static int static_a; int a; - } + public static class HierarchyOfClasses extends ParentClass { static int static_b; int b = 1; - } + public static class NullOrNotNullFields { static Object static_b; Object b; diff --git a/src/test/java/org/mockito/internal/util/reflection/GenericArrayReturnTypeTest.java b/src/test/java/org/mockito/internal/util/reflection/GenericArrayReturnTypeTest.java index 42c15f3289..d5a7459be6 100644 --- a/src/test/java/org/mockito/internal/util/reflection/GenericArrayReturnTypeTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/GenericArrayReturnTypeTest.java @@ -16,7 +16,7 @@ public class GenericArrayReturnTypeTest { @Test public void toArrayTypedDoesNotWork() throws Exception { Container container = mock(Container.class, Answers.RETURNS_DEEP_STUBS); - container.getInnerContainer().getTheProblem().toArray(new String[]{}); + container.getInnerContainer().getTheProblem().toArray(new String[] {}); } class Container { @@ -36,5 +36,4 @@ public Set getTheProblem() { return theProblem; } } - } diff --git a/src/test/java/org/mockito/internal/util/reflection/GenericMasterTest.java b/src/test/java/org/mockito/internal/util/reflection/GenericMasterTest.java index bd43a06d60..2e77d582e2 100644 --- a/src/test/java/org/mockito/internal/util/reflection/GenericMasterTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/GenericMasterTest.java @@ -24,16 +24,27 @@ public class GenericMasterTest { List>> multiNested; public interface ListSet extends List> {} + public interface MapNumberString extends Map {} + public class HashMapNumberString extends HashMap {} - public List numberList() { return null; } - public Comparable numberComparable() { return null; } - @SuppressWarnings("rawtypes") - public List rawList() { return null; } - public List typeList() { return null; } + public List numberList() { + return null; + } + + public Comparable numberComparable() { + return null; + } + @SuppressWarnings("rawtypes") + public List rawList() { + return null; + } + public List typeList() { + return null; + } @Test public void should_find_generic_class() throws Exception { @@ -56,5 +67,4 @@ public void should_deal_with_nested_generics() throws Exception { private Field field(String fieldName) throws SecurityException, NoSuchFieldException { return this.getClass().getDeclaredField(fieldName); } - } diff --git a/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java b/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java index 15574acf46..6c6333cd56 100644 --- a/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java @@ -37,20 +37,15 @@ interface UpperBoundedTypeWithInterfaces & Cloneable> { E get(); } - interface ListOfNumbers extends List { - } + interface ListOfNumbers extends List {} - interface AnotherListOfNumbers extends ListOfNumbers { - } + interface AnotherListOfNumbers extends ListOfNumbers {} - abstract class ListOfNumbersImpl implements ListOfNumbers { - } + abstract class ListOfNumbersImpl implements ListOfNumbers {} - abstract class AnotherListOfNumbersImpl extends ListOfNumbersImpl { - } + abstract class AnotherListOfNumbersImpl extends ListOfNumbersImpl {} - interface ListOfAnyNumbers extends List { - } + interface ListOfAnyNumbers extends List {} interface GenericsNest & Cloneable> extends Map> { Set remove(Object key); // override with fixed ParameterizedType @@ -70,29 +65,29 @@ interface GenericsNest & Cloneable> extends Map O typeVar_with_type_params(); } - static class StringList extends ArrayList { - } + static class StringList extends ArrayList {} public interface TopInterface { T generic(); } - public interface MiddleInterface extends TopInterface { - } + public interface MiddleInterface extends TopInterface {} - public class OwningClassWithDeclaredUpperBounds & Comparable & Cloneable> { - public abstract class AbstractInner implements MiddleInterface { - } + public class OwningClassWithDeclaredUpperBounds< + T extends List & Comparable & Cloneable> { + public abstract class AbstractInner implements MiddleInterface {} } public class OwningClassWithNoDeclaredUpperBounds { - public abstract class AbstractInner implements MiddleInterface { - } + public abstract class AbstractInner implements MiddleInterface {} } @Test public void typeVariable_of_self_type() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class)); + GenericMetadataSupport genericMetadata = + inferFrom(GenericsSelfReference.class) + .resolveGenericReturnType( + firstNamedMethod("self", GenericsSelfReference.class)); assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class); } @@ -107,18 +102,31 @@ public void can_get_raw_type_from_Class() { @Test public void can_get_raw_type_from_ParameterizedType() { - assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class); - assertThat(inferFrom(ListOfNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class); - assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).rawType()).isEqualTo(Map.class); - assertThat(inferFrom(StringList.class.getGenericSuperclass()).rawType()).isEqualTo(ArrayList.class); + assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).rawType()) + .isEqualTo(List.class); + assertThat(inferFrom(ListOfNumbers.class.getGenericInterfaces()[0]).rawType()) + .isEqualTo(List.class); + assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).rawType()) + .isEqualTo(Map.class); + assertThat(inferFrom(StringList.class.getGenericSuperclass()).rawType()) + .isEqualTo(ArrayList.class); } @Test public void can_get_type_variables_from_Class() { - assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("K"); + assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()) + .hasSize(1) + .extracting("name") + .contains("K"); assertThat(inferFrom(ListOfNumbers.class).actualTypeArguments().keySet()).isEmpty(); - assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("N"); - assertThat(inferFrom(Map.class).actualTypeArguments().keySet()).hasSize(2).extracting("name").contains("K", "V"); + assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()) + .hasSize(1) + .extracting("name") + .contains("N"); + assertThat(inferFrom(Map.class).actualTypeArguments().keySet()) + .hasSize(2) + .extracting("name") + .contains("K", "V"); assertThat(inferFrom(Serializable.class).actualTypeArguments().keySet()).isEmpty(); assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty(); } @@ -126,116 +134,201 @@ public void can_get_type_variables_from_Class() { @Test public void can_resolve_type_variables_from_ancestors() throws Exception { Method listGet = List.class.getMethod("get", int.class); - assertThat(inferFrom(AnotherListOfNumbers.class).resolveGenericReturnType(listGet).rawType()).isEqualTo(Number.class); - assertThat(inferFrom(AnotherListOfNumbersImpl.class).resolveGenericReturnType(listGet).rawType()).isEqualTo(Number.class); + assertThat( + inferFrom(AnotherListOfNumbers.class) + .resolveGenericReturnType(listGet) + .rawType()) + .isEqualTo(Number.class); + assertThat( + inferFrom(AnotherListOfNumbersImpl.class) + .resolveGenericReturnType(listGet) + .rawType()) + .isEqualTo(Number.class); } @Test public void can_get_type_variables_from_ParameterizedType() { - assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).extracting("name").contains("K", "V"); - assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("E"); - assertThat(inferFrom(Integer.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).extracting("name").contains("T"); - assertThat(inferFrom(StringBuilder.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).isEmpty(); + assertThat( + inferFrom(GenericsNest.class.getGenericInterfaces()[0]) + .actualTypeArguments() + .keySet()) + .hasSize(2) + .extracting("name") + .contains("K", "V"); + assertThat( + inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]) + .actualTypeArguments() + .keySet()) + .hasSize(1) + .extracting("name") + .contains("E"); + assertThat( + inferFrom(Integer.class.getGenericInterfaces()[0]) + .actualTypeArguments() + .keySet()) + .hasSize(1) + .extracting("name") + .contains("T"); + assertThat( + inferFrom(StringBuilder.class.getGenericInterfaces()[0]) + .actualTypeArguments() + .keySet()) + .isEmpty(); assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty(); } @Test - public void typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() { - GenericMetadataSupport genericMetadata = inferFrom(StringList.class).resolveGenericReturnType(firstNamedMethod("iterator", StringList.class)); + public void + typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() { + GenericMetadataSupport genericMetadata = + inferFrom(StringList.class) + .resolveGenericReturnType(firstNamedMethod("iterator", StringList.class)); assertThat(genericMetadata.rawType()).isEqualTo(Iterator.class); assertThat(genericMetadata.actualTypeArguments().values()).contains(String.class); } @Test - public void typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class)); + public void + typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Set.class); assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class); } @Test - public void bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returningK", GenericsNest.class)); + public void + bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType( + firstNamedMethod("returningK", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class); - GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0)); + GenericMetadataSupport extraInterface_0 = + inferFrom(genericMetadata.extraInterfaces().get(0)); assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class); } @Test - public void fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class)); + public void + fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Set.class); assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class); } @Test - public void paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class)); + public void + paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Collection.class); - GenericMetadataSupport fromTypeVariableE = inferFrom(typeVariableValue(genericMetadata.actualTypeArguments(), "E")); + GenericMetadataSupport fromTypeVariableE = + inferFrom(typeVariableValue(genericMetadata.actualTypeArguments(), "E")); assertThat(fromTypeVariableE.rawType()).isEqualTo(Set.class); assertThat(fromTypeVariableE.actualTypeArguments().values()).contains(Number.class); } @Test - public void paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("paramType_with_type_params", GenericsNest.class)); + public void + paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType( + firstNamedMethod("paramType_with_type_params", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); - Type firstBoundOfE = ((GenericMetadataSupport.TypeVarBoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E")).firstBound(); + Type firstBoundOfE = + ((GenericMetadataSupport.TypeVarBoundedType) + typeVariableValue(genericMetadata.actualTypeArguments(), "E")) + .firstBound(); assertThat(inferFrom(firstBoundOfE).rawType()).isEqualTo(Comparable.class); } @Test - public void typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("typeVar_with_type_params", GenericsNest.class)); + public void + typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType( + firstNamedMethod("typeVar_with_type_params", GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class); - GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0)); + GenericMetadataSupport extraInterface_0 = + inferFrom(genericMetadata.extraInterfaces().get(0)); assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class); } @Test public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() { - GenericMetadataSupport genericMetadata = inferFrom(StringBuilder.class).resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class)); + GenericMetadataSupport genericMetadata = + inferFrom(StringBuilder.class) + .resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class)); assertThat(genericMetadata.rawType()).isEqualTo(StringBuilder.class); assertThat(genericMetadata.actualTypeArguments()).isEmpty(); } - @Test - public void paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_class_lower_bound", GenericsNest.class)); + public void + paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType( + firstNamedMethod( + "returning_wildcard_with_class_lower_bound", + GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); - GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E"); + GenericMetadataSupport.BoundedType boundedType = + (GenericMetadataSupport.BoundedType) + typeVariableValue(genericMetadata.actualTypeArguments(), "E"); assertThat(boundedType.firstBound()).isEqualTo(Integer.class); assertThat(boundedType.interfaceBounds()).isEmpty(); } @Test - public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_lower_bound", GenericsNest.class)); + public void + paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType( + firstNamedMethod( + "returning_wildcard_with_typeVar_lower_bound", + GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); - GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E"); + GenericMetadataSupport.BoundedType boundedType = + (GenericMetadataSupport.BoundedType) + typeVariableValue(genericMetadata.actualTypeArguments(), "E"); assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class); assertThat(boundedType.interfaceBounds()).contains(Cloneable.class); } @Test - public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() { - GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_upper_bound", GenericsNest.class)); + public void + paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() { + GenericMetadataSupport genericMetadata = + inferFrom(GenericsNest.class) + .resolveGenericReturnType( + firstNamedMethod( + "returning_wildcard_with_typeVar_upper_bound", + GenericsNest.class)); assertThat(genericMetadata.rawType()).isEqualTo(List.class); - GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E"); + GenericMetadataSupport.BoundedType boundedType = + (GenericMetadataSupport.BoundedType) + typeVariableValue(genericMetadata.actualTypeArguments(), "E"); assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class); assertThat(boundedType.interfaceBounds()).contains(Cloneable.class); @@ -243,37 +336,62 @@ public void paramType_with_wildcard_return_type_of____returning_wildcard_with_ty @Test public void can_extract_raw_type_from_bounds_on_terminal_typeVariable() { - assertThat(inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class) - .resolveGenericReturnType(firstNamedMethod("generic", OwningClassWithDeclaredUpperBounds.AbstractInner.class)) - .rawType() - ).isEqualTo(List.class); - assertThat(inferFrom(OwningClassWithNoDeclaredUpperBounds.AbstractInner.class) - .resolveGenericReturnType(firstNamedMethod("generic", OwningClassWithNoDeclaredUpperBounds.AbstractInner.class)) - .rawType() - ).isEqualTo(Object.class); + assertThat( + inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class) + .resolveGenericReturnType( + firstNamedMethod( + "generic", + OwningClassWithDeclaredUpperBounds.AbstractInner + .class)) + .rawType()) + .isEqualTo(List.class); + assertThat( + inferFrom(OwningClassWithNoDeclaredUpperBounds.AbstractInner.class) + .resolveGenericReturnType( + firstNamedMethod( + "generic", + OwningClassWithNoDeclaredUpperBounds.AbstractInner + .class)) + .rawType()) + .isEqualTo(Object.class); } @Test public void can_extract_interface_type_from_bounds_on_terminal_typeVariable() { - assertThat(inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class) - .resolveGenericReturnType(firstNamedMethod("generic", OwningClassWithDeclaredUpperBounds.AbstractInner.class)) - .rawExtraInterfaces() - ).containsExactly(Comparable.class, Cloneable.class); - assertThat(inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class) - .resolveGenericReturnType(firstNamedMethod("generic", OwningClassWithDeclaredUpperBounds.AbstractInner.class)) - .extraInterfaces() - ).containsExactly(parameterizedTypeOf(Comparable.class, null, String.class), - Cloneable.class); - - assertThat(inferFrom(OwningClassWithNoDeclaredUpperBounds.AbstractInner.class) - .resolveGenericReturnType(firstNamedMethod("generic", OwningClassWithNoDeclaredUpperBounds.AbstractInner.class)) - .extraInterfaces() - ).isEmpty(); - } - - @SuppressWarnings("EqualsHashCode") - private ParameterizedType parameterizedTypeOf(final Class rawType, final Class ownerType, final Type... actualTypeArguments) { + assertThat( + inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class) + .resolveGenericReturnType( + firstNamedMethod( + "generic", + OwningClassWithDeclaredUpperBounds.AbstractInner + .class)) + .rawExtraInterfaces()) + .containsExactly(Comparable.class, Cloneable.class); + assertThat( + inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class) + .resolveGenericReturnType( + firstNamedMethod( + "generic", + OwningClassWithDeclaredUpperBounds.AbstractInner + .class)) + .extraInterfaces()) + .containsExactly( + parameterizedTypeOf(Comparable.class, null, String.class), Cloneable.class); + + assertThat( + inferFrom(OwningClassWithNoDeclaredUpperBounds.AbstractInner.class) + .resolveGenericReturnType( + firstNamedMethod( + "generic", + OwningClassWithNoDeclaredUpperBounds.AbstractInner + .class)) + .extraInterfaces()) + .isEmpty(); + } + + private ParameterizedType parameterizedTypeOf( + final Class rawType, final Class ownerType, final Type... actualTypeArguments) { return new ParameterizedType() { @Override public Type[] getActualTypeArguments() { @@ -290,6 +408,7 @@ public Type getOwnerType() { return ownerType; } + @SuppressWarnings("EqualsHashCode") public boolean equals(Object other) { if (other instanceof ParameterizedType) { ParameterizedType otherParamType = (ParameterizedType) other; @@ -297,8 +416,10 @@ public boolean equals(Object other) { return true; } else { return equals(ownerType, otherParamType.getOwnerType()) - && equals(rawType, otherParamType.getRawType()) - && Arrays.equals(actualTypeArguments, otherParamType.getActualTypeArguments()); + && equals(rawType, otherParamType.getRawType()) + && Arrays.equals( + actualTypeArguments, + otherParamType.getActualTypeArguments()); } } else { return false; @@ -311,7 +432,8 @@ private boolean equals(Object a, Object b) { }; } - private Type typeVariableValue(Map, Type> typeVariables, String typeVariableName) { + private Type typeVariableValue( + Map, Type> typeVariables, String typeVariableName) { for (Map.Entry, Type> typeVariableTypeEntry : typeVariables.entrySet()) { if (typeVariableTypeEntry.getKey().getName().equals(typeVariableName)) { return typeVariableTypeEntry.getValue(); @@ -324,11 +446,18 @@ private Type typeVariableValue(Map, Type> typeVariables, String private Method firstNamedMethod(String methodName, Class clazz) { for (Method method : clazz.getMethods()) { - boolean protect_against_different_jdk_ordering_avoiding_bridge_methods = !method.isBridge(); - if (method.getName().contains(methodName) && protect_against_different_jdk_ordering_avoiding_bridge_methods) { + boolean protect_against_different_jdk_ordering_avoiding_bridge_methods = + !method.isBridge(); + if (method.getName().contains(methodName) + && protect_against_different_jdk_ordering_avoiding_bridge_methods) { return method; } } - throw new IllegalStateException("The method : '" + methodName + "' do not exist in '" + clazz.getSimpleName() + "'"); + throw new IllegalStateException( + "The method : '" + + methodName + + "' do not exist in '" + + clazz.getSimpleName() + + "'"); } } diff --git a/src/test/java/org/mockito/internal/util/reflection/GenericTypeExtractorTest.java b/src/test/java/org/mockito/internal/util/reflection/GenericTypeExtractorTest.java index d5f270de19..94abf86121 100644 --- a/src/test/java/org/mockito/internal/util/reflection/GenericTypeExtractorTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/GenericTypeExtractorTest.java @@ -17,47 +17,74 @@ public class GenericTypeExtractorTest extends TestBase { class Base {} + static class StaticBase {} + interface IBase {} + interface StaticIBase {} class IntImpl extends Base {} + static class StaticIntImpl extends StaticBase {} + class NestedImpl extends Base> {} + class NonGeneric extends Base {} - class IIntImpl implements IBase{} - class INestedImpl implements IBase>{} + class IIntImpl implements IBase {} + + class INestedImpl implements IBase> {} + class INonGeneric implements IBase {} + class Mixed extends Base implements IBase {} class Deeper extends IntImpl implements Serializable {} + class EvenDeeper extends Deeper implements Cloneable {} + interface Iface extends IBase {} + interface IDeeper extends Serializable, Iface, Cloneable {} interface Crazy extends Serializable, IDeeper, Cloneable {} + class Crazier extends EvenDeeper implements Crazy {} + class SecondGeneric implements Serializable, IBase {} - @Test public void finds_generic_type() { + @Test + public void finds_generic_type() { assertEquals(Integer.class, genericTypeOf(IntImpl.class, Base.class, IBase.class)); - assertEquals(Integer.class, genericTypeOf(StaticIntImpl.class, StaticBase.class, IBase.class)); + assertEquals( + Integer.class, genericTypeOf(StaticIntImpl.class, StaticBase.class, IBase.class)); assertEquals(Object.class, genericTypeOf(NestedImpl.class, Base.class, IBase.class)); assertEquals(Object.class, genericTypeOf(NonGeneric.class, Base.class, IBase.class)); assertEquals(Object.class, genericTypeOf(String.class, Base.class, IBase.class)); assertEquals(Object.class, genericTypeOf(String.class, List.class, Map.class)); - assertEquals(String.class, genericTypeOf(new Base() {}.getClass(), Base.class, IBase.class)); - assertEquals(String.class, genericTypeOf(new IBase() {}.getClass(), Base.class, IBase.class)); - assertEquals(String.class, genericTypeOf(new StaticBase() {}.getClass(), StaticBase.class, IBase.class)); - assertEquals(String.class, genericTypeOf(new StaticIBase() {}.getClass(), Base.class, StaticIBase.class)); + assertEquals( + String.class, + genericTypeOf(new Base() {}.getClass(), Base.class, IBase.class)); + assertEquals( + String.class, + genericTypeOf(new IBase() {}.getClass(), Base.class, IBase.class)); + assertEquals( + String.class, + genericTypeOf( + new StaticBase() {}.getClass(), StaticBase.class, IBase.class)); + assertEquals( + String.class, + genericTypeOf( + new StaticIBase() {}.getClass(), Base.class, StaticIBase.class)); assertEquals(Integer.class, genericTypeOf(Mixed.class, Base.class, IBase.class)); assertEquals(Integer.class, genericTypeOf(IIntImpl.class, Base.class, IBase.class)); assertEquals(Object.class, genericTypeOf(INestedImpl.class, Base.class, IBase.class)); - assertEquals(Object.class, genericTypeOf(INonGeneric.class, IBase.class, INonGeneric.class)); + assertEquals( + Object.class, genericTypeOf(INonGeneric.class, IBase.class, INonGeneric.class)); assertEquals(Integer.class, genericTypeOf(Deeper.class, Base.class, IBase.class)); assertEquals(Integer.class, genericTypeOf(EvenDeeper.class, Base.class, IBase.class)); diff --git a/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java b/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java index c880e04bbc..76ebd337b9 100644 --- a/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java @@ -29,6 +29,7 @@ public static class SomeObject extends InheritMe { @SuppressWarnings("unused") // required because static fields needs to be excluded from copying private static int staticField = -100; + private int privateField = -100; private transient int privateTransientField = -100; String defaultField = "-100"; @@ -41,8 +42,7 @@ public SomeObject(int finalField) { } } - public static class SomeOtherObject { - } + public static class SomeOtherObject {} private SomeObject from = new SomeObject(100); private SomeObject to = mock(SomeObject.class); @@ -113,48 +113,49 @@ public void shouldShallowCopyFieldValuesIntoMock() throws Exception { @Test public void shouldCopyValuesOfInheritedFields() throws Exception { - //given + // given ((InheritMe) from).privateInherited = "foo"; ((InheritMe) from).protectedInherited = "bar"; - assertThat(((InheritMe) to).privateInherited).isNotEqualTo(((InheritMe) from).privateInherited); + assertThat(((InheritMe) to).privateInherited) + .isNotEqualTo(((InheritMe) from).privateInherited); - //when + // when tool.copyToMock(from, to); - //then + // then assertEquals(((InheritMe) from).privateInherited, ((InheritMe) to).privateInherited); } @Test public void shouldEnableAndThenDisableAccessibility() throws Exception { - //given + // given Field privateField = SomeObject.class.getDeclaredField("privateField"); assertFalse(privateField.isAccessible()); - //when + // when tool.copyToMock(from, to); - //then + // then privateField = SomeObject.class.getDeclaredField("privateField"); assertFalse(privateField.isAccessible()); } @Test public void shouldContinueEvenIfThereAreProblemsCopyingSingleFieldValue() throws Exception { - //given + // given tool.fieldCopier = mock(FieldCopier.class); - doNothing(). - doThrow(new IllegalAccessException()). - doNothing(). - when(tool.fieldCopier). - copyValue(anyObject(), anyObject(), any(Field.class)); + doNothing() + .doThrow(new IllegalAccessException()) + .doNothing() + .when(tool.fieldCopier) + .copyValue(anyObject(), anyObject(), any(Field.class)); - //when + // when tool.copyToMock(from, to); - //then + // then verify(tool.fieldCopier, atLeast(3)).copyValue(any(), any(), any(Field.class)); } @@ -180,6 +181,5 @@ public void shouldBeAbleToCopyFromRealObjectToRealObject() throws Exception { assertEquals(from.privateTransientField, to.privateTransientField); assertEquals(from.protectedField, to.protectedField); assertEquals(from.protectedInherited, to.protectedInherited); - } } diff --git a/src/test/java/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java b/src/test/java/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java index f3f3a48527..cb7549601c 100644 --- a/src/test/java/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java @@ -4,7 +4,6 @@ */ package org.mockito.internal.util.reflection; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; @@ -27,7 +26,6 @@ import org.mockito.internal.util.reflection.FieldInitializer.ParameterizedConstructorInstantiator; import org.mockito.junit.MockitoJUnitRunner; - @SuppressWarnings("unchecked") @RunWith(MockitoJUnitRunner.class) public class ParameterizedConstructorInstantiatorTest { @@ -56,12 +54,18 @@ public void should_be_created_with_an_argument_resolver() throws Exception { } @Test - public void should_fail_if_no_parameterized_constructor_found___excluding_inner_and_others_kind_of_types() throws Exception { + public void + should_fail_if_no_parameterized_constructor_found___excluding_inner_and_others_kind_of_types() + throws Exception { try { - new ParameterizedConstructorInstantiator(this, field("withNoArgConstructor"), resolver).instantiate(); + new ParameterizedConstructorInstantiator(this, field("withNoArgConstructor"), resolver) + .instantiate(); fail(); } catch (MockitoException me) { - assertThat(me.getMessage()).contains("no parameterized constructor").contains("withNoArgConstructor").contains("NoArgConstructor"); + assertThat(me.getMessage()) + .contains("no parameterized constructor") + .contains("withNoArgConstructor") + .contains("NoArgConstructor"); } } @@ -69,9 +73,11 @@ public void should_fail_if_no_parameterized_constructor_found___excluding_inner_ public void should_instantiate_type_if_resolver_provide_matching_types() throws Exception { Observer observer = mock(Observer.class); Map map = mock(Map.class); - given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())).willReturn(new Object[]{ observer, map }); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())) + .willReturn(new Object[] {observer, map}); - new ParameterizedConstructorInstantiator(this, field("withMultipleConstructor"), resolver).instantiate(); + new ParameterizedConstructorInstantiator(this, field("withMultipleConstructor"), resolver) + .instantiate(); assertNotNull(withMultipleConstructor); assertNotNull(withMultipleConstructor.observer); @@ -79,13 +85,17 @@ public void should_instantiate_type_if_resolver_provide_matching_types() throws } @Test - public void should_fail_if_an_argument_instance_type_do_not_match_wanted_type() throws Exception { + public void should_fail_if_an_argument_instance_type_do_not_match_wanted_type() + throws Exception { Observer observer = mock(Observer.class); Set wrongArg = mock(Set.class); - given(resolver.resolveTypeInstances(ArgumentMatchers.[]>any())).willReturn(new Object[]{ observer, wrongArg }); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>any())) + .willReturn(new Object[] {observer, wrongArg}); try { - new ParameterizedConstructorInstantiator(this, field("withMultipleConstructor"), resolver).instantiate(); + new ParameterizedConstructorInstantiator( + this, field("withMultipleConstructor"), resolver) + .instantiate(); fail(); } catch (MockitoException e) { assertThat(e.getMessage()).contains("argResolver").contains("incorrect types"); @@ -94,10 +104,13 @@ public void should_fail_if_an_argument_instance_type_do_not_match_wanted_type() @Test public void should_report_failure_if_constructor_throws_exception() throws Exception { - given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())).willReturn(new Object[]{ null }); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())) + .willReturn(new Object[] {null}); try { - new ParameterizedConstructorInstantiator(this, field("withThrowingConstructor"), resolver).instantiate(); + new ParameterizedConstructorInstantiator( + this, field("withThrowingConstructor"), resolver) + .instantiate(); fail(); } catch (MockitoException e) { assertThat(e.getMessage()).contains("constructor").contains("raised an exception"); @@ -106,10 +119,12 @@ public void should_report_failure_if_constructor_throws_exception() throws Excep @Test public void should_instantiate_type_with_vararg_constructor() throws Exception { - Observer[] vararg = new Observer[] { }; - given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())).willReturn(new Object[]{ "", vararg}); + Observer[] vararg = new Observer[] {}; + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())) + .willReturn(new Object[] {"", vararg}); - new ParameterizedConstructorInstantiator(this, field("withVarargConstructor"), resolver).instantiate(); + new ParameterizedConstructorInstantiator(this, field("withVarargConstructor"), resolver) + .instantiate(); assertNotNull(withVarargConstructor); } @@ -121,22 +136,27 @@ private Field field(String fieldName) throws NoSuchFieldException { } private static class NoArgConstructor { - NoArgConstructor() { } + NoArgConstructor() {} } private static class OneConstructor { - public OneConstructor(Observer observer) { } + public OneConstructor(Observer observer) {} } private static class ThrowingConstructor { - public ThrowingConstructor(Observer observer) throws IOException { throw new IOException(); } + public ThrowingConstructor(Observer observer) throws IOException { + throw new IOException(); + } } private static class MultipleConstructor extends OneConstructor { Observer observer; Map map; - public MultipleConstructor(Observer observer) { this(observer, null); } + public MultipleConstructor(Observer observer) { + this(observer, null); + } + public MultipleConstructor(Observer observer, Map map) { super(observer); this.observer = observer; @@ -145,6 +165,6 @@ public MultipleConstructor(Observer observer, Map map) { } private static class VarargConstructor { - VarargConstructor(String whatever, Observer... observers) { } + VarargConstructor(String whatever, Observer... observers) {} } } diff --git a/src/test/java/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java b/src/test/java/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java index 3cf76c61cb..ea50b4e2c1 100644 --- a/src/test/java/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/SuperTypesLastSorterTest.java @@ -18,21 +18,22 @@ public class SuperTypesLastSorterTest { * A Comparator that behaves like the old one, so the existing tests * continue to work. */ - private static Comparator cmp = new Comparator() { - public int compare(Field o1, Field o2) { - if (o1.equals(o2)) { - return 0; - } - - List l = sortSuperTypesLast(Arrays.asList(o1, o2)); - - if (l.get(0) == o1) { - return -1; - } else { - return 1; - } - } - }; + private static Comparator cmp = + new Comparator() { + public int compare(Field o1, Field o2) { + if (o1.equals(o2)) { + return 0; + } + + List l = sortSuperTypesLast(Arrays.asList(o1, o2)); + + if (l.get(0) == o1) { + return -1; + } else { + return 1; + } + } + }; private Object objectA; private Object objectB; @@ -49,7 +50,6 @@ public int compare(Field o1, Field o2) { private Iterable yIterable; private Integer zInteger; - @Test public void when_same_type_the_order_is_based_on_field_name() throws Exception { assertThat(cmp.compare(field("objectA"), field("objectB"))).isEqualTo(-1); @@ -65,50 +65,45 @@ public void when_type_is_different_the_supertype_comes_last() throws Exception { @Test public void using_Collections_dot_sort() throws Exception { - List unsortedFields = Arrays.asList( - field("objectB"), - field("integerB"), - field("numberA"), - field("numberB"), - field("objectA"), - field("integerA") - ); - - List sortedFields = sortSuperTypesLast(unsortedFields); - - assertThat(sortedFields).containsSequence( - field("integerA"), - field("integerB"), - field("numberA"), - field("numberB"), - field("objectA"), - field("objectB") - ); + List unsortedFields = + Arrays.asList( + field("objectB"), + field("integerB"), + field("numberA"), + field("numberB"), + field("objectA"), + field("integerA")); + + List sortedFields = sortSuperTypesLast(unsortedFields); + + assertThat(sortedFields) + .containsSequence( + field("integerA"), + field("integerB"), + field("numberA"), + field("numberB"), + field("objectA"), + field("objectB")); } - @Test public void issue_352_order_was_different_between_JDK6_and_JDK7() throws Exception { - List unsortedFields = Arrays.asList( - field("objectB"), - field("objectA") - ); + List unsortedFields = Arrays.asList(field("objectB"), field("objectA")); Collections.sort(unsortedFields, cmp); - assertThat(unsortedFields).containsSequence( - field("objectA"), - field("objectB") - ); + assertThat(unsortedFields).containsSequence(field("objectA"), field("objectB")); } @Test - public void fields_sort_consistently_when_interfaces_are_included() throws NoSuchFieldException { + public void fields_sort_consistently_when_interfaces_are_included() + throws NoSuchFieldException { assertSortConsistently(field("iterableA"), field("numberA"), field("integerA")); } @Test - public void fields_sort_consistently_when_names_and_type_indicate_different_order() throws NoSuchFieldException { + public void fields_sort_consistently_when_names_and_type_indicate_different_order() + throws NoSuchFieldException { assertSortConsistently(field("xNumber"), field("yIterable"), field("zInteger")); } @@ -118,12 +113,12 @@ public void fields_sort_consistently_when_names_and_type_indicate_different_orde */ private static void assertSortConsistently(Field a, Field b, Field c) { Field[][] initialOrderings = { - {a, b, c}, - {a, c, b}, - {b, a, c}, - {b, c, a}, - {c, a, b}, - {c, b, a} + {a, b, c}, + {a, c, b}, + {b, a, c}, + {b, c, a}, + {c, a, b}, + {c, b, a} }; Set> results = new HashSet>(); diff --git a/src/test/java/org/mockito/internal/verification/DescriptionTest.java b/src/test/java/org/mockito/internal/verification/DescriptionTest.java index ff6a2705bc..5444ca342f 100644 --- a/src/test/java/org/mockito/internal/verification/DescriptionTest.java +++ b/src/test/java/org/mockito/internal/verification/DescriptionTest.java @@ -19,11 +19,9 @@ public class DescriptionTest { - @Mock - private VerificationMode mockVerificationMode; + @Mock private VerificationMode mockVerificationMode; - @Mock - private VerificationData mockVerificationData; + @Mock private VerificationData mockVerificationData; @Before public void setUp() { diff --git a/src/test/java/org/mockito/internal/verification/DummyVerificationMode.java b/src/test/java/org/mockito/internal/verification/DummyVerificationMode.java index db8651192d..92b3b640d4 100644 --- a/src/test/java/org/mockito/internal/verification/DummyVerificationMode.java +++ b/src/test/java/org/mockito/internal/verification/DummyVerificationMode.java @@ -8,8 +8,7 @@ import org.mockito.verification.VerificationMode; public class DummyVerificationMode implements VerificationMode { - public void verify(VerificationData data) { - } + public void verify(VerificationData data) {} public VerificationMode description(String description) { return new DummyVerificationMode(); diff --git a/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java b/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java index 4c04a014a1..7c628cd8e8 100644 --- a/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java +++ b/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java @@ -21,23 +21,21 @@ public class NoInteractionsTest extends TestBase { @Test public void noInteractionsExceptionMessageShouldDescribeMock() { - //given + // given NoInteractions n = new NoInteractions(); IMethods mock = mock(IMethods.class, "a mock"); InvocationMatcher i = new InvocationBuilder().mock(mock).toInvocationMatcher(); - InvocationContainerImpl invocations = - new InvocationContainerImpl(new MockSettingsImpl()); + InvocationContainerImpl invocations = new InvocationContainerImpl(new MockSettingsImpl()); invocations.setInvocationForPotentialStubbing(i); try { - //when + // when n.verify(new VerificationDataImpl(invocations, null)); - //then + // then fail(); } catch (NoInteractionsWanted e) { Assertions.assertThat(e.toString()).contains(mock.toString()); } } - } diff --git a/src/test/java/org/mockito/internal/verification/NoMoreInteractionsTest.java b/src/test/java/org/mockito/internal/verification/NoMoreInteractionsTest.java index d5d4a86f1a..e75898f62f 100644 --- a/src/test/java/org/mockito/internal/verification/NoMoreInteractionsTest.java +++ b/src/test/java/org/mockito/internal/verification/NoMoreInteractionsTest.java @@ -28,75 +28,76 @@ public class NoMoreInteractionsTest extends TestBase { @Test public void shouldVerifyInOrder() { - //given + // given NoMoreInteractions n = new NoMoreInteractions(); Invocation i = new InvocationBuilder().toInvocation(); assertFalse(context.isVerified(i)); try { - //when + // when n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null)); - //then + // then fail(); - } catch(VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test public void shouldVerifyInOrderAndPass() { - //given + // given NoMoreInteractions n = new NoMoreInteractions(); Invocation i = new InvocationBuilder().toInvocation(); context.markVerified(i); assertTrue(context.isVerified(i)); - //when + // when n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null)); - //then no exception is thrown + // then no exception is thrown } @Test public void shouldVerifyInOrderMultipleInvoctions() { - //given + // given NoMoreInteractions n = new NoMoreInteractions(); Invocation i = new InvocationBuilder().seq(1).toInvocation(); Invocation i2 = new InvocationBuilder().seq(2).toInvocation(); - //when + // when context.markVerified(i2); - //then no exception is thrown + // then no exception is thrown n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i, i2), null)); } @Test public void shouldVerifyInOrderMultipleInvoctionsAndThrow() { - //given + // given NoMoreInteractions n = new NoMoreInteractions(); Invocation i = new InvocationBuilder().seq(1).toInvocation(); Invocation i2 = new InvocationBuilder().seq(2).toInvocation(); try { - //when + // when n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i, i2), null)); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test public void noMoreInteractionsExceptionMessageShouldDescribeMock() { - //given + // given NoMoreInteractions n = new NoMoreInteractions(); IMethods mock = mock(IMethods.class, "a mock"); InvocationMatcher i = new InvocationBuilder().mock(mock).toInvocationMatcher(); - InvocationContainerImpl invocations = - new InvocationContainerImpl( new MockSettingsImpl()); + InvocationContainerImpl invocations = new InvocationContainerImpl(new MockSettingsImpl()); invocations.setInvocationForPotentialStubbing(i); try { - //when + // when n.verify(new VerificationDataImpl(invocations, null)); - //then + // then fail(); } catch (NoInteractionsWanted e) { Assertions.assertThat(e.toString()).contains(mock.toString()); @@ -105,15 +106,15 @@ public void noMoreInteractionsExceptionMessageShouldDescribeMock() { @Test public void noMoreInteractionsInOrderExceptionMessageShouldDescribeMock() { - //given + // given NoMoreInteractions n = new NoMoreInteractions(); IMethods mock = mock(IMethods.class, "a mock"); Invocation i = new InvocationBuilder().mock(mock).toInvocation(); try { - //when + // when n.verifyInOrder(new VerificationDataInOrderImpl(context, asList(i), null)); - //then + // then fail(); } catch (VerificationInOrderFailure e) { Assertions.assertThat(e.toString()).contains(mock.toString()); diff --git a/src/test/java/org/mockito/internal/verification/OnlyTest.java b/src/test/java/org/mockito/internal/verification/OnlyTest.java index 60b9a082cf..c269e3bff5 100644 --- a/src/test/java/org/mockito/internal/verification/OnlyTest.java +++ b/src/test/java/org/mockito/internal/verification/OnlyTest.java @@ -46,30 +46,33 @@ public InvocationMatcher getWanted() { @Test public void shouldMarkAsVerified() { - //given + // given Invocation invocation = new InvocationBuilder().toInvocation(); assertFalse(invocation.isVerified()); - //when + // when only.verify(new VerificationDataStub(new InvocationMatcher(invocation), invocation)); - //then + // then assertTrue(invocation.isVerified()); } @Test public void shouldNotMarkAsVerifiedWhenAssertionFailed() { - //given + // given Invocation invocation = new InvocationBuilder().toInvocation(); assertFalse(invocation.isVerified()); - //when + // when try { - only.verify(new VerificationDataStub(new InvocationBuilder().toInvocationMatcher(), invocation)); + only.verify( + new VerificationDataStub( + new InvocationBuilder().toInvocationMatcher(), invocation)); fail(); - } catch (MockitoAssertionError e) {} + } catch (MockitoAssertionError e) { + } - //then + // then assertFalse(invocation.isVerified()); } } diff --git a/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java b/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java index d786762a8d..645cb29d8a 100644 --- a/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java +++ b/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java @@ -22,7 +22,10 @@ public class SmartPrinterTest extends TestBase { @Before public void setup() throws Exception { - mock.varargs("first very long argument", "second very long argument", "another very long argument"); + mock.varargs( + "first very long argument", + "second very long argument", + "another very long argument"); multi = new InvocationMatcher(getLastInvocation()); mock.varargs("short arg"); @@ -31,10 +34,10 @@ public void setup() throws Exception { @Test public void shouldPrintBothInMultilinesWhenFirstIsMulti() { - //when + // when SmartPrinter printer = new SmartPrinter(multi, shortie.getInvocation()); - //then + // then assertThat(printer.getWanted()).contains("\n"); for (String actual : printer.getActuals()) { assertThat(actual).contains("\n"); @@ -43,10 +46,10 @@ public void shouldPrintBothInMultilinesWhenFirstIsMulti() { @Test public void shouldPrintBothInMultilinesWhenSecondIsMulti() { - //when + // when SmartPrinter printer = new SmartPrinter(shortie, multi.getInvocation()); - //then + // then assertThat(printer.getWanted()).contains("\n"); for (String actual : printer.getActuals()) { assertThat(actual).contains("\n"); @@ -55,10 +58,10 @@ public void shouldPrintBothInMultilinesWhenSecondIsMulti() { @Test public void shouldPrintBothInMultilinesWhenBothAreMulti() { - //when + // when SmartPrinter printer = new SmartPrinter(multi, multi.getInvocation()); - //then + // then assertThat(printer.getWanted()).contains("\n"); for (String actual : printer.getActuals()) { assertThat(actual).contains("\n"); @@ -67,10 +70,10 @@ public void shouldPrintBothInMultilinesWhenBothAreMulti() { @Test public void shouldPrintBothInSingleLineWhenBothAreShort() { - //when + // when SmartPrinter printer = new SmartPrinter(shortie, shortie.getInvocation()); - //then + // then assertThat(printer.getWanted()).doesNotContain("\n"); for (String actual : printer.getActuals()) { assertThat(actual).doesNotContain("\n"); diff --git a/src/test/java/org/mockito/internal/verification/VerificationDataImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationDataImplTest.java index 1fb775a62d..2364102ffc 100644 --- a/src/test/java/org/mockito/internal/verification/VerificationDataImplTest.java +++ b/src/test/java/org/mockito/internal/verification/VerificationDataImplTest.java @@ -16,10 +16,12 @@ public class VerificationDataImplTest extends TestBase { @Test public void shouldToStringBeNotVerifiable() throws Exception { - InvocationMatcher toString = new InvocationBuilder().method("toString").toInvocationMatcher(); + InvocationMatcher toString = + new InvocationBuilder().method("toString").toInvocationMatcher(); try { new VerificationDataImpl(null, toString); fail(); - } catch (MockitoException e) {} + } catch (MockitoException e) { + } } } diff --git a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java index 82cceeaea7..e8bf2f80be 100644 --- a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java +++ b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java @@ -19,12 +19,10 @@ import org.mockito.verification.VerificationMode; public class VerificationOverTimeImplTest { - @Mock - private VerificationMode delegate; + @Mock private VerificationMode delegate; private VerificationOverTimeImpl impl; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); @Before public void setUp() { diff --git a/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java b/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java index ced6a5b226..b188e8ffd2 100644 --- a/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java +++ b/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java @@ -19,8 +19,7 @@ public class VerificationWithDescriptionTest { - @Mock - private List mock; + @Mock private List mock; @Before public void setUp() { diff --git a/src/test/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingToolTest.java b/src/test/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingToolTest.java index 893e3158c1..d54c7f4cbc 100644 --- a/src/test/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingToolTest.java +++ b/src/test/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingToolTest.java @@ -17,7 +17,7 @@ import org.mockito.internal.matchers.Equals; import org.mockitoutil.TestBase; -@SuppressWarnings({ "unchecked", "serial" }) +@SuppressWarnings({"unchecked", "serial"}) public class ArgumentMatchingToolTest extends TestBase { @Test @@ -26,7 +26,9 @@ public void shouldNotFindAnySuspiciousMatchersWhenNumberOfArgumentsDoesntMatch() List matchers = (List) Arrays.asList(new Equals(1)); // when - Integer[] suspicious = ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(matchers, new Object[] { 10, 20 }); + Integer[] suspicious = + ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes( + matchers, new Object[] {10, 20}); // then assertEquals(0, suspicious.length); @@ -38,7 +40,9 @@ public void shouldNotFindAnySuspiciousMatchersWhenArgumentsMatch() { List matchers = (List) Arrays.asList(new Equals(10), new Equals(20)); // when - Integer[] suspicious = ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(matchers, new Object[] { 10, 20 }); + Integer[] suspicious = + ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes( + matchers, new Object[] {10, 20}); // then assertEquals(0, suspicious.length); @@ -52,7 +56,9 @@ public void shouldFindSuspiciousMatchers() { // when List matchers = (List) Arrays.asList(new Equals(10), matcherInt20); - Integer[] suspicious = ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(matchers, new Object[] { 10, longPretendingAnInt }); + Integer[] suspicious = + ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes( + matchers, new Object[] {10, longPretendingAnInt}); // then assertEquals(1, suspicious.length); @@ -62,15 +68,18 @@ public void shouldFindSuspiciousMatchers() { @Test public void shouldNotFindSuspiciousMatchersWhenTypesAreTheSame() { // given - Equals matcherWithBadDescription = new Equals(20) { - public String toString() { - return "10"; - } - }; + Equals matcherWithBadDescription = + new Equals(20) { + public String toString() { + return "10"; + } + }; Integer argument = 10; // when - Integer[] suspicious = ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes((List) Arrays.asList(matcherWithBadDescription), new Object[] { argument }); + Integer[] suspicious = + ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes( + (List) Arrays.asList(matcherWithBadDescription), new Object[] {argument}); // then assertEquals(0, suspicious.length); @@ -79,7 +88,9 @@ public String toString() { @Test public void shouldWorkFineWhenGivenArgIsNull() { // when - Integer[] suspicious = ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes((List) Arrays.asList(new Equals(20)), new Object[] { null }); + Integer[] suspicious = + ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes( + (List) Arrays.asList(new Equals(20)), new Object[] {null}); // then assertEquals(0, suspicious.length); @@ -88,8 +99,10 @@ public void shouldWorkFineWhenGivenArgIsNull() { @Test @SuppressWarnings("rawtypes") public void shouldUseMatchersSafely() { - // This matcher is evil cause typeMatches(Object) returns true for every passed type but matches(T) - // method accepts only Strings. When a Integer is passed (thru the matches(Object) bridge method ) a + // This matcher is evil cause typeMatches(Object) returns true for every passed type but + // matches(T) + // method accepts only Strings. When a Integer is passed (thru the matches(Object) bridge + // method ) a // ClassCastException will be thrown. class StringMatcher implements ArgumentMatcher, ContainsExtraTypeInfo { @Override @@ -112,10 +125,11 @@ public boolean typeMatches(Object target) { List matchers = (List) singletonList(new StringMatcher()); // when - Integer[] suspicious = ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(matchers, new Object[] { 10 }); + Integer[] suspicious = + ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes( + matchers, new Object[] {10}); // then assertEquals(0, suspicious.length); } - } diff --git a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java index 466b5c1a3c..3f47758eb6 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java @@ -20,29 +20,29 @@ import org.mockito.internal.verification.api.InOrderContext; import org.mockito.invocation.Invocation; -public class AtLeastXNumberOfInvocationsCheckerTest { +public class AtLeastXNumberOfInvocationsCheckerTest { - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); @Test public void shouldMarkActualInvocationsAsVerifiedInOrder() { InOrderContext context = new InOrderContextImpl(); - //given + // given Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation(); Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation(); - //when - checkAtLeastNumberOfInvocations(asList(invocation, invocationTwo), new InvocationMatcher(invocation), 1, context); + // when + checkAtLeastNumberOfInvocations( + asList(invocation, invocationTwo), new InvocationMatcher(invocation), 1, context); - //then + // then assertThat(invocation.isVerified()).isTrue(); } @Test public void shouldReportTooFewInvocationsInOrder() { InOrderContext context = new InOrderContextImpl(); - //given + // given Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation(); Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation(); @@ -51,28 +51,28 @@ public void shouldReportTooFewInvocationsInOrder() { exception.expectMessage("Wanted *at least* 2 times"); exception.expectMessage("But was 1 time"); - //when - checkAtLeastNumberOfInvocations(asList(invocation, invocationTwo), new InvocationMatcher(invocation), 2, context); - - + // when + checkAtLeastNumberOfInvocations( + asList(invocation, invocationTwo), new InvocationMatcher(invocation), 2, context); } @Test public void shouldMarkActualInvocationsAsVerified() { - //given + // given Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation(); Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation(); - //when - checkAtLeastNumberOfInvocations(asList(invocation, invocationTwo), new InvocationMatcher(invocation), 1); + // when + checkAtLeastNumberOfInvocations( + asList(invocation, invocationTwo), new InvocationMatcher(invocation), 1); - //then + // then assertThat(invocation.isVerified()).isTrue(); } @Test public void shouldReportTooFewInvocations() { - //given + // given Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation(); Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation(); @@ -81,7 +81,8 @@ public void shouldReportTooFewInvocations() { exception.expectMessage("Wanted *at least* 2 times"); exception.expectMessage("But was 1 time"); - //when - checkAtLeastNumberOfInvocations(asList(invocation, invocationTwo), new InvocationMatcher(invocation), 2); + // when + checkAtLeastNumberOfInvocations( + asList(invocation, invocationTwo), new InvocationMatcher(invocation), 2); } } diff --git a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java index 14d7dd9109..99c6a7af29 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java @@ -29,11 +29,9 @@ public class MissingInvocationCheckerTest extends TestBase { private InvocationMatcher wanted; private List invocations; - @Mock - private IMethods mock; + @Mock private IMethods mock; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); @Test public void shouldPassBecauseActualInvocationFound() { @@ -75,7 +73,9 @@ public void shouldReportWantedInvocationDiffersFromActual() { @Test public void shouldReportUsingInvocationDescription() { wanted = buildIntArgMethod(new CustomInvocationBuilder()).arg(2222).toInvocationMatcher(); - invocations = singletonList(buildIntArgMethod(new CustomInvocationBuilder()).arg(1111).toInvocation()); + invocations = + singletonList( + buildIntArgMethod(new CustomInvocationBuilder()).arg(1111).toInvocation()); exception.expect(ArgumentsAreDifferent.class); @@ -101,24 +101,31 @@ private InvocationBuilder buildDifferentMethod() { static class CustomInvocationBuilder extends InvocationBuilder { @Override - protected Invocation createInvocation(MockReference mockRef, MockitoMethod mockitoMethod, final Object[] arguments, - RealMethod realMethod, Location location, int sequenceNumber) { - return new InterceptedInvocation(mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber) { + protected Invocation createInvocation( + MockReference mockRef, + MockitoMethod mockitoMethod, + final Object[] arguments, + RealMethod realMethod, + Location location, + int sequenceNumber) { + return new InterceptedInvocation( + mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber) { @Override public List getArgumentsAsMatchers() { List matchers = new ArrayList(); for (final Object argument : getRawArguments()) { - matchers.add(new ArgumentMatcher() { - @Override - public boolean matches(Object a) { - return a == argument; - } - - @Override - public String toString() { - return "MyCoolPrint(" + argument + ")"; - } - }); + matchers.add( + new ArgumentMatcher() { + @Override + public boolean matches(Object a) { + return a == argument; + } + + @Override + public String toString() { + return "MyCoolPrint(" + argument + ")"; + } + }); } return matchers; } diff --git a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java index 87c60d3fbc..7ce7907ef7 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java @@ -27,25 +27,21 @@ import org.mockito.junit.MockitoRule; import org.mockitousage.IMethods; -public class MissingInvocationInOrderCheckerTest { +public class MissingInvocationInOrderCheckerTest { private InvocationMatcher wanted; private List invocations; - @Mock - private IMethods mock; + @Mock private IMethods mock; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); private InOrderContext context = new InOrderContextImpl(); @Before - public void setup() { - } + public void setup() {} @Test public void shouldPassWhenMatchingInteractionFound() throws Exception { @@ -81,8 +77,7 @@ public void shouldReportArgumentsAreDifferent() throws Exception { exception.expectMessage("mock.intArgumentMethod(1111);"); checkMissingInvocation(invocations, wanted, context); - - } + } @Test public void shouldReportWantedDiffersFromActual() throws Exception { @@ -91,7 +86,7 @@ public void shouldReportWantedDiffersFromActual() throws Exception { Invocation invocation2 = buildIntArgMethod().arg(2222).toInvocation(); context.markVerified(invocation2); - invocations = asList(invocation1,invocation2); + invocations = asList(invocation1, invocation2); wanted = buildIntArgMethod().arg(2222).toInvocationMatcher(); exception.expect(VerificationInOrderFailure.class); @@ -116,6 +111,4 @@ private InvocationBuilder buildSimpleMethod() { private InvocationBuilder buildDifferentMethod() { return new InvocationBuilder().mock(mock).differentMethod(); } - - } diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java index f6f4bb5121..b92bb4dd1c 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java @@ -36,19 +36,17 @@ public class NumberOfInvocationsCheckerTest { private List invocations; - @Mock - private IMethods mock; + @Mock private IMethods mock; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); - @Rule - public TestName testName = new TestName(); + @Rule public TestName testName = new TestName(); @Test public void shouldReportTooFewActual() throws Exception { wanted = buildSimpleMethod().toInvocationMatcher(); - invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); + invocations = + asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); exception.expect(TooFewActualInvocations.class); exception.expectMessage("mock.simpleMethod()"); @@ -61,7 +59,8 @@ public void shouldReportTooFewActual() throws Exception { @Test public void shouldReportAllInvocationsStackTrace() throws Exception { wanted = buildSimpleMethod().toInvocationMatcher(); - invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); + invocations = + asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); exception.expect(TooFewActualInvocations.class); exception.expectMessage("mock.simpleMethod()"); @@ -177,6 +176,5 @@ public boolean matchesSafely(String text) { public void describeTo(Description description) { description.appendText("containing '" + expected + "' exactly " + amount + " times"); } - } } diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java index ca318bd19e..aae3b812a2 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java @@ -35,14 +35,12 @@ public class NumberOfInvocationsInOrderCheckerTest { private IMethods mock; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); @Before public void setup() { context = new InOrderContextImpl(); mock = mock(IMethods.class, "mock"); - } @Test @@ -91,7 +89,8 @@ public void shouldMarkAsVerifiedInOrder() throws Exception { @Test public void shouldReportTooFewActual() throws Exception { wanted = buildSimpleMethod().toInvocationMatcher(); - invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); + invocations = + asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); exception.expect(VerificationInOrderFailure.class); exception.expectMessage("mock.simpleMethod()"); @@ -104,7 +103,8 @@ public void shouldReportTooFewActual() throws Exception { @Test public void shouldReportWithAllInvocationsStackTrace() throws Exception { wanted = buildSimpleMethod().toInvocationMatcher(); - invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); + invocations = + asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); exception.expect(VerificationInOrderFailure.class); exception.expectMessage("mock.simpleMethod()"); @@ -113,7 +113,6 @@ public void shouldReportWithAllInvocationsStackTrace() throws Exception { exception.expectMessage(containsTimes("-> at", 3)); NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context); - } @Test @@ -218,7 +217,6 @@ public boolean matchesSafely(String text) { public void describeTo(Description description) { description.appendText("containing '" + expected + "' exactly " + amount + " times"); } - } private InvocationBuilder buildSimpleMethod() { diff --git a/src/test/java/org/mockito/junit/TestableJUnitRunner.java b/src/test/java/org/mockito/junit/TestableJUnitRunner.java index 0b13d9f065..a8b04f099d 100644 --- a/src/test/java/org/mockito/junit/TestableJUnitRunner.java +++ b/src/test/java/org/mockito/junit/TestableJUnitRunner.java @@ -16,18 +16,27 @@ public class TestableJUnitRunner extends MockitoJUnitRunner { - private final static ThreadLocal LOGGER = new ThreadLocal() { - protected SimpleMockitoLogger initialValue() { - return new SimpleMockitoLogger(); - } - }; + private static final ThreadLocal LOGGER = + new ThreadLocal() { + protected SimpleMockitoLogger initialValue() { + return new SimpleMockitoLogger(); + } + }; - public TestableJUnitRunner(Class klass) throws InvocationTargetException, InitializationError { - super(new StrictRunner(new RunnerFactory().create(klass, new Supplier() { - public MockitoTestListener get() { - return new MismatchReportingTestListener(LOGGER.get()); - } - }), klass)); + public TestableJUnitRunner(Class klass) + throws InvocationTargetException, InitializationError { + super( + new StrictRunner( + new RunnerFactory() + .create( + klass, + new Supplier() { + public MockitoTestListener get() { + return new MismatchReportingTestListener( + LOGGER.get()); + } + }), + klass)); } public static SimpleMockitoLogger refreshedLogger() { diff --git a/src/test/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunnerTest.java b/src/test/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunnerTest.java index 5bbabb8f30..a9b487c137 100644 --- a/src/test/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunnerTest.java +++ b/src/test/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunnerTest.java @@ -31,22 +31,25 @@ public void setup() throws InitializationError { notifier = new RunNotifier(); } - //TODO add sensible tests + // TODO add sensible tests @Test public void shouldDelegateToGetDescription() throws Exception { - //given + // given final Description expectedDescription = Description.createSuiteDescription(this.getClass()); - runner = new ConsoleSpammingMockitoJUnitRunner(loggerStub, new InternalRunnerStub() { - public Description getDescription() { - return expectedDescription; - } - }); - - //when + runner = + new ConsoleSpammingMockitoJUnitRunner( + loggerStub, + new InternalRunnerStub() { + public Description getDescription() { + return expectedDescription; + } + }); + + // when Description description = runner.getDescription(); - //then + // then assertEquals(expectedDescription, description); } @@ -70,11 +73,8 @@ public Description getDescription() { return null; } - public void run(RunNotifier notifier) { - } - - public void filter(Filter filter) throws NoTestsRemainException { - } + public void run(RunNotifier notifier) {} + public void filter(Filter filter) throws NoTestsRemainException {} } } diff --git a/src/test/java/org/mockito/verification/NegativeDurationTest.java b/src/test/java/org/mockito/verification/NegativeDurationTest.java index ddfe31aa2e..79530081cf 100644 --- a/src/test/java/org/mockito/verification/NegativeDurationTest.java +++ b/src/test/java/org/mockito/verification/NegativeDurationTest.java @@ -11,8 +11,7 @@ import org.mockito.exceptions.misusing.FriendlyReminderException; public class NegativeDurationTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); + @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void should_throw_exception_when_duration_is_negative_for_timeout_method() { diff --git a/src/test/java/org/mockito/verification/TimeoutTest.java b/src/test/java/org/mockito/verification/TimeoutTest.java index ae6e5d2e84..b4c1ada177 100644 --- a/src/test/java/org/mockito/verification/TimeoutTest.java +++ b/src/test/java/org/mockito/verification/TimeoutTest.java @@ -17,12 +17,9 @@ public class TimeoutTest extends TestBase { - @Mock - VerificationMode mode; - @Mock - VerificationDataImpl data; - @Mock - Timer timer; + @Mock VerificationMode mode; + @Mock VerificationDataImpl data; + @Mock Timer timer; private final MockitoAssertionError error = new MockitoAssertionError(""); @@ -45,15 +42,13 @@ public void should_fail_because_verification_fails() { Timeout t = new Timeout(1, mode, timer); when(timer.isCounting()).thenReturn(true, true, true, false); - doThrow(error). - doThrow(error). - doThrow(error). - when(mode).verify(data); + doThrow(error).doThrow(error).doThrow(error).when(mode).verify(data); try { t.verify(data); fail(); - } catch (MockitoAssertionError e) {} + } catch (MockitoAssertionError e) { + } verify(timer, times(4)).isCounting(); } @@ -63,10 +58,7 @@ public void should_pass_even_if_first_verification_fails() { Timeout t = new Timeout(1, mode, timer); when(timer.isCounting()).thenReturn(true, true, true, false); - doThrow(error). - doThrow(error). - doNothing(). - when(mode).verify(data); + doThrow(error).doThrow(error).doNothing().when(mode).verify(data); t.verify(data); verify(timer, times(3)).isCounting(); @@ -82,9 +74,9 @@ public void should_try_to_verify_correct_number_of_times() { try { t.verify(data); fail(); - } catch (MockitoAssertionError e) {} + } catch (MockitoAssertionError e) { + } verify(mode, times(5)).verify(data); } - } diff --git a/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java b/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java index fa840602f9..342007122c 100644 --- a/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java +++ b/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java @@ -20,19 +20,21 @@ public class NoByteCodeDependenciesTest { @Test public void pure_mockito_should_not_depend_bytecode_libraries() throws Exception { - ClassLoader classLoader_without_bytecode_libraries = ClassLoaders.excludingClassLoader() - .withCodeSourceUrlOf( - Mockito.class, - Matcher.class - ) - .withCodeSourceUrlOf(coverageTool()) - .without("net.bytebuddy", "org.objenesis") - .build(); - - Set pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_bytecode_libraries).omit( - "bytebuddy", "runners", "junit", "JUnit", "opentest4j").listOwnedClasses(); - pureMockitoAPIClasses.remove("org.mockito.internal.creation.instance.DefaultInstantiatorProvider"); - pureMockitoAPIClasses.remove("org.mockito.internal.creation.instance.ObjenesisInstantiator"); + ClassLoader classLoader_without_bytecode_libraries = + ClassLoaders.excludingClassLoader() + .withCodeSourceUrlOf(Mockito.class, Matcher.class) + .withCodeSourceUrlOf(coverageTool()) + .without("net.bytebuddy", "org.objenesis") + .build(); + + Set pureMockitoAPIClasses = + ClassLoaders.in(classLoader_without_bytecode_libraries) + .omit("bytebuddy", "runners", "junit", "JUnit", "opentest4j") + .listOwnedClasses(); + pureMockitoAPIClasses.remove( + "org.mockito.internal.creation.instance.DefaultInstantiatorProvider"); + pureMockitoAPIClasses.remove( + "org.mockito.internal.creation.instance.ObjenesisInstantiator"); // Remove classes that trigger plugin-loading, since bytebuddy plugins are the default. pureMockitoAPIClasses.remove("org.mockito.internal.debugging.LocationImpl"); @@ -44,12 +46,16 @@ public void pure_mockito_should_not_depend_bytecode_libraries() throws Exception } } - private void checkDependency(ClassLoader classLoader, String pureMockitoAPIClass) throws ClassNotFoundException { + private void checkDependency(ClassLoader classLoader, String pureMockitoAPIClass) + throws ClassNotFoundException { try { Class.forName(pureMockitoAPIClass, true, classLoader); } catch (Throwable e) { e.printStackTrace(); - throw new AssertionError(String.format("'%s' has some dependency to Byte Buddy or Objenesis", pureMockitoAPIClass)); + throw new AssertionError( + String.format( + "'%s' has some dependency to Byte Buddy or Objenesis", + pureMockitoAPIClass)); } } } diff --git a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java index 89336ba2a7..9cd47da864 100644 --- a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java +++ b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java @@ -22,37 +22,47 @@ public class NoJUnitDependenciesTest { @Test public void pure_mockito_should_not_depend_JUnit___ByteBuddy() throws Exception { - Assume.assumeTrue("ByteBuddyMockMaker".equals(Plugins.getMockMaker().getClass().getSimpleName())); - - ClassLoader classLoader_without_JUnit = ClassLoaders.excludingClassLoader() - .withCodeSourceUrlOf( - Mockito.class, - Matcher.class, - ByteBuddy.class, - ByteBuddyAgent.class, - Objenesis.class - ) - .withCodeSourceUrlOf(coverageTool()) - .without("junit", "org.junit", "org.opentest4j") - .build(); - - Set pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit", "opentest4j").listOwnedClasses(); - - // The later class is required to be initialized before any inline mock maker classes can be loaded. - checkDependency(classLoader_without_JUnit, "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker"); - pureMockitoAPIClasses.remove("org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker"); + Assume.assumeTrue( + "ByteBuddyMockMaker".equals(Plugins.getMockMaker().getClass().getSimpleName())); + + ClassLoader classLoader_without_JUnit = + ClassLoaders.excludingClassLoader() + .withCodeSourceUrlOf( + Mockito.class, + Matcher.class, + ByteBuddy.class, + ByteBuddyAgent.class, + Objenesis.class) + .withCodeSourceUrlOf(coverageTool()) + .without("junit", "org.junit", "org.opentest4j") + .build(); + + Set pureMockitoAPIClasses = + ClassLoaders.in(classLoader_without_JUnit) + .omit("runners", "junit", "JUnit", "opentest4j") + .listOwnedClasses(); + + // The later class is required to be initialized before any inline mock maker classes can be + // loaded. + checkDependency( + classLoader_without_JUnit, + "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker"); + pureMockitoAPIClasses.remove( + "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker"); for (String pureMockitoAPIClass : pureMockitoAPIClasses) { checkDependency(classLoader_without_JUnit, pureMockitoAPIClass); } } - private void checkDependency(ClassLoader classLoader_without_JUnit, String pureMockitoAPIClass) throws ClassNotFoundException { + private void checkDependency(ClassLoader classLoader_without_JUnit, String pureMockitoAPIClass) + throws ClassNotFoundException { try { Class.forName(pureMockitoAPIClass, true, classLoader_without_JUnit); } catch (Throwable e) { e.printStackTrace(); - throw new AssertionError(String.format("'%s' has some dependency to JUnit", pureMockitoAPIClass)); + throw new AssertionError( + String.format("'%s' has some dependency to JUnit", pureMockitoAPIClass)); } } } diff --git a/src/test/java/org/mockitousage/CompilationWarningsTest.java b/src/test/java/org/mockitousage/CompilationWarningsTest.java index 0731aaff76..faf019f094 100644 --- a/src/test/java/org/mockitousage/CompilationWarningsTest.java +++ b/src/test/java/org/mockitousage/CompilationWarningsTest.java @@ -11,94 +11,180 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; - public class CompilationWarningsTest { @Before - public void pay_attention_to_compilation_warnings_and_JDK_version() { - } + public void pay_attention_to_compilation_warnings_and_JDK_version() {} @Test public void no_warnings_for_most_common_api() throws Exception { doReturn(null).when(mock(IMethods.class)).objectReturningMethodNoArgs(); doReturn("a", 12).when(mock(IMethods.class)).objectReturningMethodNoArgs(); doReturn(1000).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doThrow(new NullPointerException()).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doThrow(new NullPointerException(), new IllegalArgumentException()).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doThrow(NullPointerException.class).when(mock(IMethods.class)).objectReturningMethodNoArgs(); + doThrow(new NullPointerException()) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + doThrow(new NullPointerException(), new IllegalArgumentException()) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + doThrow(NullPointerException.class) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); doAnswer(ignore()).doReturn(null).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doAnswer(ignore()).doReturn("a", 12).when(mock(IMethods.class)).objectReturningMethodNoArgs(); + doAnswer(ignore()) + .doReturn("a", 12) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); doAnswer(ignore()).doReturn(1000).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doAnswer(ignore()).doThrow(new NullPointerException()).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doAnswer(ignore()).doThrow(new NullPointerException(), new IllegalArgumentException()).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doAnswer(ignore()).doThrow(NullPointerException.class).when(mock(IMethods.class)).objectReturningMethodNoArgs(); + doAnswer(ignore()) + .doThrow(new NullPointerException()) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + doAnswer(ignore()) + .doThrow(new NullPointerException(), new IllegalArgumentException()) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + doAnswer(ignore()) + .doThrow(NullPointerException.class) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn(null); when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn("a", 12L); when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn(1000); - when(mock(IMethods.class).objectReturningMethodNoArgs()).thenThrow(new NullPointerException()); - when(mock(IMethods.class).objectReturningMethodNoArgs()).thenThrow(new NullPointerException(), new IllegalArgumentException()); - when(mock(IMethods.class).objectReturningMethodNoArgs()).thenThrow(NullPointerException.class); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .thenThrow(new NullPointerException()); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .thenThrow(new NullPointerException(), new IllegalArgumentException()); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .thenThrow(NullPointerException.class); when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenReturn(null); - when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenReturn("a", 12L); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .then(ignore()) + .thenReturn("a", 12L); when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenReturn(1000); - when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenThrow(new NullPointerException()); - when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenThrow(new NullPointerException(), new IllegalArgumentException()); - when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenThrow(NullPointerException.class); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .then(ignore()) + .thenThrow(new NullPointerException()); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .then(ignore()) + .thenThrow(new NullPointerException(), new IllegalArgumentException()); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .then(ignore()) + .thenThrow(NullPointerException.class); willReturn(null).given(mock(IMethods.class)).objectReturningMethodNoArgs(); willReturn("a", 12).given(mock(IMethods.class)).objectReturningMethodNoArgs(); willReturn(1000).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willThrow(new NullPointerException()).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willThrow(new NullPointerException(), new IllegalArgumentException()).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willThrow(NullPointerException.class).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - - willAnswer(ignore()).willReturn(null).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willAnswer(ignore()).willReturn("a", 12).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willAnswer(ignore()).willReturn(1000).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willAnswer(ignore()).willThrow(new NullPointerException()).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willAnswer(ignore()).willThrow(new NullPointerException(), new IllegalArgumentException()).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - willAnswer(ignore()).willThrow(NullPointerException.class).given(mock(IMethods.class)).objectReturningMethodNoArgs(); + willThrow(new NullPointerException()) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willThrow(new NullPointerException(), new IllegalArgumentException()) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willThrow(NullPointerException.class) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + + willAnswer(ignore()) + .willReturn(null) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willAnswer(ignore()) + .willReturn("a", 12) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willAnswer(ignore()) + .willReturn(1000) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willAnswer(ignore()) + .willThrow(new NullPointerException()) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willAnswer(ignore()) + .willThrow(new NullPointerException(), new IllegalArgumentException()) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + willAnswer(ignore()) + .willThrow(NullPointerException.class) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn(null); given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn("a", 12L); given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn(1000); - given(mock(IMethods.class).objectReturningMethodNoArgs()).willThrow(new NullPointerException()); - given(mock(IMethods.class).objectReturningMethodNoArgs()).willThrow(new NullPointerException(), new IllegalArgumentException()); - given(mock(IMethods.class).objectReturningMethodNoArgs()).willThrow(NullPointerException.class); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .willThrow(new NullPointerException()); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .willThrow(new NullPointerException(), new IllegalArgumentException()); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .willThrow(NullPointerException.class); given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willReturn(null); - given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willReturn("a", 12L); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .will(ignore()) + .willReturn("a", 12L); given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willReturn(1000); - given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willThrow(new NullPointerException()); - given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willThrow(new NullPointerException(), new IllegalArgumentException()); - given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willThrow(NullPointerException.class); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .will(ignore()) + .willThrow(new NullPointerException()); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .will(ignore()) + .willThrow(new NullPointerException(), new IllegalArgumentException()); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .will(ignore()) + .willThrow(NullPointerException.class); } @Test @SuppressWarnings("unchecked") - public void heap_pollution_JDK7plus_warning_avoided_BUT_now_unchecked_generic_array_creation_warnings_ON_JDK5plus_environment() throws Exception { - doThrow(NullPointerException.class, IllegalArgumentException.class).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - when(mock(IMethods.class).objectReturningMethodNoArgs()).thenThrow(NullPointerException.class, IllegalArgumentException.class); - doAnswer(ignore()).doThrow(NullPointerException.class, IllegalArgumentException.class).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - - willThrow(NullPointerException.class, IllegalArgumentException.class).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - given(mock(IMethods.class).objectReturningMethodNoArgs()).willThrow(NullPointerException.class, IllegalArgumentException.class); - willAnswer(ignore()).willThrow(NullPointerException.class, IllegalArgumentException.class).given(mock(IMethods.class)).objectReturningMethodNoArgs(); + public void + heap_pollution_JDK7plus_warning_avoided_BUT_now_unchecked_generic_array_creation_warnings_ON_JDK5plus_environment() + throws Exception { + doThrow(NullPointerException.class, IllegalArgumentException.class) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .thenThrow(NullPointerException.class, IllegalArgumentException.class); + doAnswer(ignore()) + .doThrow(NullPointerException.class, IllegalArgumentException.class) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + + willThrow(NullPointerException.class, IllegalArgumentException.class) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .willThrow(NullPointerException.class, IllegalArgumentException.class); + willAnswer(ignore()) + .willThrow(NullPointerException.class, IllegalArgumentException.class) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); } @Test public void unchecked_confusing_null_argument_warnings() throws Exception { doReturn(null, (Object[]) null).when(mock(IMethods.class)).objectReturningMethodNoArgs(); - doAnswer(ignore()).doReturn(null, (Object[]) null).when(mock(IMethods.class)).objectReturningMethodNoArgs(); + doAnswer(ignore()) + .doReturn(null, (Object[]) null) + .when(mock(IMethods.class)) + .objectReturningMethodNoArgs(); when(mock(IMethods.class).objectReturningMethodNoArgs()).thenReturn(null, (Object[]) null); - when(mock(IMethods.class).objectReturningMethodNoArgs()).then(ignore()).thenReturn(null, (Object[]) null); + when(mock(IMethods.class).objectReturningMethodNoArgs()) + .then(ignore()) + .thenReturn(null, (Object[]) null); willReturn(null, (Object[]) null).given(mock(IMethods.class)).objectReturningMethodNoArgs(); given(mock(IMethods.class).objectReturningMethodNoArgs()).willReturn(null, (Object[]) null); - willAnswer(ignore()).willReturn(null, (Object[]) null).given(mock(IMethods.class)).objectReturningMethodNoArgs(); - given(mock(IMethods.class).objectReturningMethodNoArgs()).will(ignore()).willReturn(null, (Object[]) null); + willAnswer(ignore()) + .willReturn(null, (Object[]) null) + .given(mock(IMethods.class)) + .objectReturningMethodNoArgs(); + given(mock(IMethods.class).objectReturningMethodNoArgs()) + .will(ignore()) + .willReturn(null, (Object[]) null); } private static Answer ignore() { diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java index 69d1d039e8..5a12b47ba9 100644 --- a/src/test/java/org/mockitousage/IMethods.java +++ b/src/test/java/org/mockitousage/IMethods.java @@ -42,7 +42,7 @@ public interface IMethods { Double doubleObjectReturningMethod(); - Object objectReturningMethod(Object ... objects); + Object objectReturningMethod(Object... objects); Object objectReturningMethodNoArgs(); @@ -124,7 +124,8 @@ public interface IMethods { String simpleMethod(String one, Integer two, Integer three, Integer four, Integer five); - String simpleMethod(String one, Integer two, Integer three, Integer four, Integer five, Integer six); + String simpleMethod( + String one, Integer two, Integer three, Integer four, Integer five, Integer six); String simpleMethod(String one, String[] two); @@ -166,21 +167,21 @@ public interface IMethods { void varargsbyte(byte... bytes); - int varargs(Object ... object); + int varargs(Object... object); - String varargsReturningString(Object ... object); + String varargsReturningString(Object... object); - int varargs(String ... string); + int varargs(String... string); - void mixedVarargs(Object i, String ... string); + void mixedVarargs(Object i, String... string); - String mixedVarargsReturningString(Object i, String ... string); + String mixedVarargsReturningString(Object i, String... string); - String[] mixedVarargsReturningStringArray(Object i, String ... string); + String[] mixedVarargsReturningStringArray(Object i, String... string); - Object[] mixedVarargsReturningObjectArray(Object i, String ... string); + Object[] mixedVarargsReturningObjectArray(Object i, String... string); - List listReturningMethod(Object ... objects); + List listReturningMethod(Object... objects); LinkedList linkedListReturningMethod(); diff --git a/src/test/java/org/mockitousage/MethodsImpl.java b/src/test/java/org/mockitousage/MethodsImpl.java index d538dd1dcf..eafb91b093 100644 --- a/src/test/java/org/mockitousage/MethodsImpl.java +++ b/src/test/java/org/mockitousage/MethodsImpl.java @@ -237,7 +237,8 @@ public String simpleMethod(String one, Integer two, Integer three, Integer four, return null; } - public String simpleMethod(String one, Integer two, Integer three, Integer four, Integer five, Integer six) { + public String simpleMethod( + String one, Integer two, Integer three, Integer four, Integer five, Integer six) { return null; } @@ -253,17 +254,14 @@ public String threeArgumentMethodWithStrings(int valueOne, String valueTwo, Stri return null; } - public String fourArgumentMethod(int valueOne, String valueTwo, String valueThree, boolean[] array) { + public String fourArgumentMethod( + int valueOne, String valueTwo, String valueThree, boolean[] array) { return null; } - public void twoArgumentMethod(int one, int two) { + public void twoArgumentMethod(int one, int two) {} - } - - public void arrayMethod(String[] strings) { - - } + public void arrayMethod(String[] strings) {} public String oneArray(boolean[] array) { return null; @@ -309,9 +307,7 @@ public String oneArray(String[] array) { return null; } - public void varargsString(int i, String... string) { - - } + public void varargsString(int i, String... string) {} public Object varargsObject(int i, Object... object) { return null; @@ -329,8 +325,7 @@ public int varargs(String... string) { return -1; } - public void mixedVarargs(Object i, String... string) { - } + public void mixedVarargs(Object i, String... string) {} public String mixedVarargsReturningString(Object i, String... string) { return null; @@ -344,8 +339,7 @@ public Object[] mixedVarargsReturningObjectArray(Object i, String... string) { return null; } - public void varargsbyte(byte... bytes) { - } + public void varargsbyte(byte... bytes) {} public List listReturningMethod(Object... objects) { return null; @@ -359,9 +353,7 @@ public String toString(String foo) { return null; } - public void voidMethod() { - - } + public void voidMethod() {} public String forList(List list) { return null; @@ -415,13 +407,9 @@ public Object setArgMethod(Set set) { return null; } - public void longArg(long longArg) { + public void longArg(long longArg) {} - } - - public void intArgumentMethod(int i) { - - } + public void intArgumentMethod(int i) {} public int intArgumentReturningInt(int i) { return 0; diff --git a/src/test/java/org/mockitousage/PlaygroundTest.java b/src/test/java/org/mockitousage/PlaygroundTest.java index b8aa49bfde..33c20368f0 100644 --- a/src/test/java/org/mockitousage/PlaygroundTest.java +++ b/src/test/java/org/mockitousage/PlaygroundTest.java @@ -21,12 +21,12 @@ protected String getStuff() { } class Boo { - final public Object withLong(long y) { - return ""; + public final Object withLong(long y) { + return ""; } public Object foo() { - return ""; + return ""; } } @@ -34,70 +34,68 @@ public Object foo() { @Mock IMethods mockTwo; @Test - public void spyInAction() { - - } + public void spyInAction() {} @Test public void partialMockInAction() { -// mock = mock(Foo.class, withSettings() -// .defaultBehavior(CALLS_REAL_METHODS); - -// mock = mock(Foo.class, withSettings() -// .defaultMockAnswer(CALLS_REAL_METHODS); - -// mock = mock(Foo.class, withSettings() -// .defaultAnswer(CALLS_REAL_METHODS); - -// mock = mock(Foo.class, CALLS_REAL_METHODS); - -// mock = mock(Foo.class, withSettings() -// .defaultBehavior(CALLS_REAL_METHODS) -// .createUsingDefaultConstructor(); -// -// mock = mock(Foo.class, withSettings() -// .defaultBehavior(CALLS_REAL_METHODS) -// .createPassingArguments("some arg", 1); -// -// spy = spy(Foo.class, "some arg", 1); -// -// .withName("foo") -// .withDefaultBehavior(RETURNS_SMART_NULLS) -// .withInterfaces(Bar.class); -// -// mock = mock(Foo.class) -// .name("foo") -// .defaultBehavior(RETURNS_SMART_NULLS) -// .interfaces(Bar.class); -// -// mock = mock(Foo.class) -// .named("foo") -// .byDefault(RETURNS_SMART_NULLS) -// .alsoImplements(Bar.class, Bar2.class); -// -// mock = mock(Foo.class) -// hasName("foo"); - -// when(mock.getStuff()).thenReturn("aha!"); -// when(mock.doSomeThing()).thenCallRealMethod(); -// - -// mock.doSomeThing(); + // mock = mock(Foo.class, withSettings() + // .defaultBehavior(CALLS_REAL_METHODS); + + // mock = mock(Foo.class, withSettings() + // .defaultMockAnswer(CALLS_REAL_METHODS); + + // mock = mock(Foo.class, withSettings() + // .defaultAnswer(CALLS_REAL_METHODS); + + // mock = mock(Foo.class, CALLS_REAL_METHODS); + + // mock = mock(Foo.class, withSettings() + // .defaultBehavior(CALLS_REAL_METHODS) + // .createUsingDefaultConstructor(); + // + // mock = mock(Foo.class, withSettings() + // .defaultBehavior(CALLS_REAL_METHODS) + // .createPassingArguments("some arg", 1); + // + // spy = spy(Foo.class, "some arg", 1); + // + // .withName("foo") + // .withDefaultBehavior(RETURNS_SMART_NULLS) + // .withInterfaces(Bar.class); + // + // mock = mock(Foo.class) + // .name("foo") + // .defaultBehavior(RETURNS_SMART_NULLS) + // .interfaces(Bar.class); + // + // mock = mock(Foo.class) + // .named("foo") + // .byDefault(RETURNS_SMART_NULLS) + // .alsoImplements(Bar.class, Bar2.class); + // + // mock = mock(Foo.class) + // hasName("foo"); + + // when(mock.getStuff()).thenReturn("aha!"); + // when(mock.doSomeThing()).thenCallRealMethod(); + // + + // mock.doSomeThing(); } -// interface Colored { -// -// } -// -// interface Bar { -// T getColoredPoint(); -// } -// -// @Test -// public void testname() throws Exception { -// when(mock.get()).then(returnArgument()); -// -// Bar mock = mock(Bar.class); -// when(mock.getColoredPoint()).thenReturn(new Foo()); -// } + // interface Colored { + // + // } + // + // interface Bar { + // T getColoredPoint(); + // } + // + // @Test + // public void testname() throws Exception { + // when(mock.get()).then(returnArgument()); + // + // Bar mock = mock(Bar.class); + // when(mock.getColoredPoint()).thenReturn(new Foo()); + // } } diff --git a/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java b/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java index 0bece8c10c..e3289f344f 100644 --- a/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java +++ b/src/test/java/org/mockitousage/PlaygroundWithDemoOfUnclonedParametersProblemTest.java @@ -35,46 +35,52 @@ public void setUp() throws Exception { @Test public void shouldIncludeInitialLog() { - //given + // given int importType = 0; Date currentDate = new GregorianCalendar(2009, 10, 12).getTime(); ImportLogBean initialLog = new ImportLogBean(currentDate, importType); initialLog.setStatus(1); - given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate)).willReturn(false); - willAnswer(byCheckingLogEquals(initialLog)).given(importLogDao).include(any(ImportLogBean.class)); + given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate)) + .willReturn(false); + willAnswer(byCheckingLogEquals(initialLog)) + .given(importLogDao) + .include(any(ImportLogBean.class)); - //when + // when importManager.startImportProcess(importType, currentDate); - //then + // then verify(importLogDao).include(any(ImportLogBean.class)); } @Test public void shouldAlterFinalLog() { - //given + // given int importType = 0; Date currentDate = new GregorianCalendar(2009, 10, 12).getTime(); ImportLogBean finalLog = new ImportLogBean(currentDate, importType); finalLog.setStatus(9); - given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate)).willReturn(false); - willAnswer(byCheckingLogEquals(finalLog)).given(importLogDao).alter(any(ImportLogBean.class)); + given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate)) + .willReturn(false); + willAnswer(byCheckingLogEquals(finalLog)) + .given(importLogDao) + .alter(any(ImportLogBean.class)); - //when + // when importManager.startImportProcess(importType, currentDate); - //then + // then verify(importLogDao).alter(any(ImportLogBean.class)); } private Answer byCheckingLogEquals(final ImportLogBean status) { return new Answer() { public Object answer(InvocationOnMock invocation) throws Throwable { - ImportLogBean bean = invocation.getArgument(0); + ImportLogBean bean = invocation.getArgument(0); assertEquals(status, bean); return null; } @@ -97,7 +103,8 @@ public void startImportProcess(int importType, Date date) { importLogBean = createResume(importType, date); if (isOkToImport(importType, date)) { // get the right handler - //importLogBean = ImportHandlerFactory.singleton().getImportHandler(importType).processImport(importLogBean); + // importLogBean = + // ImportHandlerFactory.singleton().getImportHandler(importType).processImport(importLogBean); // 2 = ok importLogBean.setStatus(2); } else { @@ -106,11 +113,9 @@ public void startImportProcess(int importType, Date date) { } } catch (Exception e) { // 9 = failed - exception - if (importLogBean != null) - importLogBean.setStatus(9); + if (importLogBean != null) importLogBean.setStatus(9); } finally { - if (importLogBean != null) - finalizeResume(importLogBean); + if (importLogBean != null) finalizeResume(importLogBean); } } @@ -119,8 +124,7 @@ private boolean isOkToImport(int importType, Date date) { } private ImportLogBean createResume(int importType, Date date) { - ImportLogBean importLogBean = new ImportLogBean(date, - importType); + ImportLogBean importLogBean = new ImportLogBean(date, importType); // 1 = running importLogBean.setStatus(1); importLogDao.include(importLogBean); @@ -140,8 +144,7 @@ private interface ImportLogDao { void alter(ImportLogBean importLogBean); } - private class IImportHandler { - } + private class IImportHandler {} private class ImportLogBean { private Date currentDate; @@ -166,7 +169,9 @@ public boolean equals(Object o) { if (importType != that.importType) return false; if (status != that.status) return false; - if (currentDate != null ? !currentDate.equals(that.currentDate) : that.currentDate != null) return false; + if (currentDate != null + ? !currentDate.equals(that.currentDate) + : that.currentDate != null) return false; return true; } diff --git a/src/test/java/org/mockitousage/annotation/AnnotationsTest.java b/src/test/java/org/mockitousage/annotation/AnnotationsTest.java index 59785b90d4..8ec83c1523 100644 --- a/src/test/java/org/mockitousage/annotation/AnnotationsTest.java +++ b/src/test/java/org/mockitousage/annotation/AnnotationsTest.java @@ -58,7 +58,8 @@ public void shouldScreamWhenInitializingMocksForNullClass() throws Exception { MockitoAnnotations.initMocks(null); fail(); } catch (MockitoException e) { - assertEquals("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class", + assertEquals( + "testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class", e.getMessage()); } } @@ -73,11 +74,19 @@ public void shouldLookForAnnotatedMocksInSuperClasses() throws Exception { assertNotNull(sub.getSuperBaseMock()); } - @Mock(answer = Answers.RETURNS_MOCKS, name = "i have a name") IMethods namedAndReturningMocks; - @Mock(answer = Answers.RETURNS_DEFAULTS) IMethods returningDefaults; - @Mock(extraInterfaces = {List.class}) IMethods hasExtraInterfaces; + @Mock(answer = Answers.RETURNS_MOCKS, name = "i have a name") + IMethods namedAndReturningMocks; + + @Mock(answer = Answers.RETURNS_DEFAULTS) + IMethods returningDefaults; + + @Mock(extraInterfaces = {List.class}) + IMethods hasExtraInterfaces; + @Mock() IMethods noExtraConfig; - @Mock(stubOnly=true) IMethods stubOnly; + + @Mock(stubOnly = true) + IMethods stubOnly; @Test public void shouldInitMocksWithGivenSettings() throws Exception { diff --git a/src/test/java/org/mockitousage/annotation/CaptorAnnotationBasicTest.java b/src/test/java/org/mockitousage/annotation/CaptorAnnotationBasicTest.java index 6d3799fb0d..6f8dc66e59 100644 --- a/src/test/java/org/mockitousage/annotation/CaptorAnnotationBasicTest.java +++ b/src/test/java/org/mockitousage/annotation/CaptorAnnotationBasicTest.java @@ -51,10 +51,10 @@ private void createPerson(String name, String surname) { @Test public void shouldUseCaptorInOrdinaryWay() { - //when + // when createPerson("Wes", "Williams"); - //then + // then ArgumentCaptor captor = ArgumentCaptor.forClass(Person.class); verify(peopleRepository).save(captor.capture()); assertEquals("Wes", captor.getValue().getName()); @@ -65,24 +65,25 @@ public void shouldUseCaptorInOrdinaryWay() { @Test public void shouldUseAnnotatedCaptor() { - //when + // when createPerson("Wes", "Williams"); - //then + // then verify(peopleRepository).save(captor.capture()); assertEquals("Wes", captor.getValue().getName()); assertEquals("Williams", captor.getValue().getSurname()); } @SuppressWarnings("rawtypes") - @Captor ArgumentCaptor genericLessCaptor; + @Captor + ArgumentCaptor genericLessCaptor; @Test public void shouldUseGenericlessAnnotatedCaptor() { - //when + // when createPerson("Wes", "Williams"); - //then + // then verify(peopleRepository).save((Person) genericLessCaptor.capture()); assertEquals("Wes", ((Person) genericLessCaptor.getValue()).getName()); assertEquals("Williams", ((Person) genericLessCaptor.getValue()).getSurname()); @@ -93,14 +94,14 @@ public void shouldUseGenericlessAnnotatedCaptor() { @Test public void shouldCaptureGenericList() { - //given + // given List list = new LinkedList(); mock.listArgMethod(list); - //when + // when verify(mock).listArgMethod(genericListCaptor.capture()); - //then + // then assertSame(list, genericListCaptor.getValue()); } } diff --git a/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java b/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java index 4dbbe88ef5..08480c202d 100644 --- a/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java +++ b/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java @@ -22,24 +22,19 @@ public class CaptorAnnotationTest extends TestBase { @Retention(RetentionPolicy.RUNTIME) - public @interface NotAMock { - } + public @interface NotAMock {} - @Captor - final ArgumentCaptor finalCaptor = ArgumentCaptor.forClass(String.class); + @Captor final ArgumentCaptor finalCaptor = ArgumentCaptor.forClass(String.class); - @Captor - ArgumentCaptor>> genericsCaptor; + @Captor ArgumentCaptor>> genericsCaptor; @SuppressWarnings("rawtypes") @Captor ArgumentCaptor nonGenericCaptorIsAllowed; - @Mock - MockInterface mockInterface; + @Mock MockInterface mockInterface; - @NotAMock - Set notAMock; + @NotAMock Set notAMock; public interface MockInterface { void testMe(String simple, List> genericList); @@ -66,12 +61,10 @@ public void testNormalUsage() { assertEquals(argForFinalCaptor, finalCaptor.getValue()); assertEquals(argForGenericsCaptor, genericsCaptor.getValue()); - } public static class WrongType { - @Captor - List wrongType; + @Captor List wrongType; } @Test @@ -79,13 +72,12 @@ public void shouldScreamWhenWrongTypeForCaptor() { try { MockitoAnnotations.initMocks(new WrongType()); fail(); - } catch (MockitoException e) {} + } catch (MockitoException e) { + } } public static class ToManyAnnotations { - @Captor - @Mock - ArgumentCaptor missingGenericsField; + @Captor @Mock ArgumentCaptor missingGenericsField; } @Test @@ -95,8 +87,8 @@ public void shouldScreamWhenMoreThanOneMockitoAnnotation() { fail(); } catch (MockitoException e) { assertThat(e) - .hasMessageContaining("missingGenericsField") - .hasMessageContaining("multiple Mockito annotations"); + .hasMessageContaining("missingGenericsField") + .hasMessageContaining("multiple Mockito annotations"); } } @@ -120,8 +112,7 @@ public void shouldLookForAnnotatedCaptorsInSuperClasses() throws Exception { } class SuperBase { - @Captor - private ArgumentCaptor mock; + @Captor private ArgumentCaptor mock; public ArgumentCaptor getSuperBaseCaptor() { return mock; @@ -129,8 +120,7 @@ public ArgumentCaptor getSuperBaseCaptor() { } class Base extends SuperBase { - @Captor - private ArgumentCaptor mock; + @Captor private ArgumentCaptor mock; public ArgumentCaptor getBaseCaptor() { return mock; @@ -138,8 +128,7 @@ public ArgumentCaptor getBaseCaptor() { } class Sub extends Base { - @Captor - private ArgumentCaptor mock; + @Captor private ArgumentCaptor mock; public ArgumentCaptor getCaptor() { return mock; diff --git a/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java b/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java index 15e9f6c18a..ccc6184b67 100644 --- a/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java +++ b/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java @@ -23,20 +23,20 @@ public class CaptorAnnotationUnhappyPathTest extends TestBase { @Before @Override public void init() { - //we need to get rid of parent implementation this time + // we need to get rid of parent implementation this time } @Test public void shouldFailIfCaptorHasWrongType() throws Exception { try { - //when + // when MockitoAnnotations.initMocks(this); fail(); } catch (MockitoException e) { - //then + // then assertThat(e) - .hasMessageContaining("notACaptorField") - .hasMessageContaining("wrong type"); + .hasMessageContaining("notACaptorField") + .hasMessageContaining("wrong type"); } } } diff --git a/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java b/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java index 11f3255fca..eb0bd896c1 100644 --- a/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java +++ b/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java @@ -31,6 +31,7 @@ class SimpleTestCase { class Tested { Dependency dependency; + public void setDependency(Dependency dependency) { this.dependency = dependency; } @@ -40,15 +41,15 @@ class Dependency {} @Test public void shouldInjectMocksIfThereIsNoUserDefinedEngine() throws Exception { - //given + // given AnnotationEngine defaultEngine = new DefaultMockitoConfiguration().getAnnotationEngine(); ConfigurationAccess.getConfig().overrideAnnotationEngine(defaultEngine); SimpleTestCase test = new SimpleTestCase(); - //when + // when MockitoAnnotations.initMocks(test); - //then + // then assertNotNull(test.mock); assertNotNull(test.tested.dependency); assertSame(test.mock, test.tested.dependency); @@ -56,15 +57,17 @@ public void shouldInjectMocksIfThereIsNoUserDefinedEngine() throws Exception { @Test public void shouldRespectUsersEngine() throws Exception { - //given - AnnotationEngine customizedEngine = new IndependentAnnotationEngine() { /**/ }; + // given + AnnotationEngine customizedEngine = new IndependentAnnotationEngine() { + /**/ + }; ConfigurationAccess.getConfig().overrideAnnotationEngine(customizedEngine); SimpleTestCase test = new SimpleTestCase(); - //when + // when MockitoAnnotations.initMocks(test); - //then + // then assertNotNull(test.mock); assertNull(test.tested.dependency); } diff --git a/src/test/java/org/mockitousage/annotation/InjectionOfInlinedMockDeclarationTest.java b/src/test/java/org/mockitousage/annotation/InjectionOfInlinedMockDeclarationTest.java index ef5e3d5487..defb88a93a 100644 --- a/src/test/java/org/mockitousage/annotation/InjectionOfInlinedMockDeclarationTest.java +++ b/src/test/java/org/mockitousage/annotation/InjectionOfInlinedMockDeclarationTest.java @@ -44,7 +44,6 @@ public void named_mocks_should_be_resolved_with_their_name() throws Exception { assertSame(antenna, receiver.dvbtAntenna); } - @Test public void inject_mocks_even_in_declared_spy() throws Exception { assertNotNull(spiedReceiver.oldAntenna); @@ -58,10 +57,12 @@ static class Receiver { Antenna dvbtAntenna; Tuner tuner; - public boolean tune() { return true; } + public boolean tune() { + return true; + } } - private static class Antenna { } - private static class Tuner { } + private static class Antenna {} + private static class Tuner {} } diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java index b2a222057e..0e5c67f02c 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorIssue421Test.java @@ -30,16 +30,14 @@ static class Issue421 { private ArticleCalculator calculator; - public Issue421(int a) { - } + public Issue421(int a) {} public Issue421(ArticleCalculator calculator) { this.calculator = calculator; } - public void checkIfMockIsInjected(){ + public void checkIfMockIsInjected() { assertThat(MockUtil.isMock(calculator)).isTrue(); } } - } diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java index 8523ff662a..6d60a321fd 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java @@ -42,10 +42,10 @@ public class MockInjectionUsingConstructorTest { @InjectMocks private ArticleManager articleManager; @Spy @InjectMocks private ArticleManager spiedArticleManager; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); - @Before public void before() { + @Before + public void before() { MockitoAnnotations.initMocks(this); } @@ -87,18 +87,21 @@ public void objects_created_with_constructor_initialization_can_be_spied() throw } @Test - public void should_report_failure_only_when_object_initialization_throws_exception() throws Exception { + public void should_report_failure_only_when_object_initialization_throws_exception() + throws Exception { try { MockitoAnnotations.initMocks(new ATest()); fail(); } catch (MockitoException e) { - assertThat(e.getMessage()).contains("failingConstructor").contains("constructor").contains("threw an exception"); + assertThat(e.getMessage()) + .contains("failingConstructor") + .contains("constructor") + .contains("threw an exception"); assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); } } - @RunWith(MockitoJUnitRunner.class) public static class junit_test_with_3_tests_methods { private static int constructor_instantiation = 0; @@ -106,9 +109,14 @@ public static class junit_test_with_3_tests_methods { @Mock List some_collaborator; @InjectMocks some_class_with_parametered_constructor should_be_initialized_3_times; - @Test public void test_1() { } - @Test public void test_2() { } - @Test public void test_3() { } + @Test + public void test_1() {} + + @Test + public void test_2() {} + + @Test + public void test_3() {} private static class some_class_with_parametered_constructor { public some_class_with_parametered_constructor(List collaborator) { @@ -129,17 +137,15 @@ private static class ATest { @InjectMocks FailingConstructor failingConstructor; } - @Test public void injectMocksMustFailWithInterface() throws Exception { class TestCase { - @InjectMocks - IMethods f; + @InjectMocks IMethods f; } exception.expect(MockitoException.class); - exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'IMethods' is an interface"); - + exception.expectMessage( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'IMethods' is an interface"); initMocks(new TestCase()); } @@ -147,12 +153,12 @@ class TestCase { @Test public void injectMocksMustFailWithEnum() throws Exception { class TestCase { - @InjectMocks - TimeUnit f; + @InjectMocks TimeUnit f; } exception.expect(MockitoException.class); - exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'TimeUnit' is an enum"); + exception.expectMessage( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'TimeUnit' is an enum"); initMocks(new TestCase()); } @@ -160,12 +166,12 @@ class TestCase { @Test public void injectMocksMustFailWithAbstractClass() throws Exception { class TestCase { - @InjectMocks - AbstractCollection f; + @InjectMocks AbstractCollection f; } exception.expect(MockitoException.class); - exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'AbstractCollection' is an abstract class"); + exception.expectMessage( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'AbstractCollection' is an abstract class"); initMocks(new TestCase()); } @@ -174,23 +180,23 @@ class TestCase { public void injectMocksMustFailWithNonStaticInnerClass() throws Exception { class TestCase { class InnerClass {} - @InjectMocks - InnerClass f; - } + @InjectMocks InnerClass f; + } exception.expect(MockitoException.class); - exception.expectMessage("Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'InnerClass' is an inner non static class"); + exception.expectMessage( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'InnerClass' is an inner non static class"); initMocks(new TestCase()); } - static class StaticInnerClass {} + static class StaticInnerClass {} + @Test public void injectMocksMustSucceedWithStaticInnerClass() throws Exception { class TestCase { - @InjectMocks - StaticInnerClass f; + @InjectMocks StaticInnerClass f; } TestCase testClass = new TestCase(); @@ -202,8 +208,7 @@ class TestCase { @Test public void injectMocksMustSucceedWithInstance() throws Exception { class TestCase { - @InjectMocks - StaticInnerClass f = new StaticInnerClass(); + @InjectMocks StaticInnerClass f = new StaticInnerClass(); } TestCase testClass = new TestCase(); @@ -212,8 +217,4 @@ class TestCase { assertThat(testClass.f).isSameAs(original); } - - - - } diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java index b901ef14fe..88a74a697e 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java @@ -31,7 +31,9 @@ public class MockInjectionUsingSetterOrPropertyTest extends TestBase { @InjectMocks private BaseUnderTesting baseUnderTest = new BaseUnderTesting(); @InjectMocks private SubUnderTesting subUnderTest = new SubUnderTesting(); @InjectMocks private OtherBaseUnderTesting otherBaseUnderTest = new OtherBaseUnderTesting(); - @InjectMocks private HasTwoFieldsWithSameType hasTwoFieldsWithSameType = new HasTwoFieldsWithSameType(); + + @InjectMocks + private HasTwoFieldsWithSameType hasTwoFieldsWithSameType = new HasTwoFieldsWithSameType(); private BaseUnderTesting baseUnderTestingInstance = new BaseUnderTesting(); @InjectMocks private BaseUnderTesting initializedBase = baseUnderTestingInstance; @@ -110,10 +112,12 @@ public void should_inject_spies() { } @Test - public void should_insert_into_field_with_matching_name_when_multiple_fields_of_same_type_exists_in_injectee() { + public void + should_insert_into_field_with_matching_name_when_multiple_fields_of_same_type_exists_in_injectee() { MockitoAnnotations.initMocks(this); assertNull("not injected, no mock named 'candidate1'", hasTwoFieldsWithSameType.candidate1); - assertNotNull("injected, there's a mock named 'candidate2'", hasTwoFieldsWithSameType.candidate2); + assertNotNull( + "injected, there's a mock named 'candidate2'", hasTwoFieldsWithSameType.candidate2); } @Test @@ -128,46 +132,63 @@ public void should_keep_instance_on_inject_mock_field_if_present() throws Except @Test public void should_report_nicely() throws Exception { - Object failing = new Object() { - @InjectMocks ThrowingConstructor failingConstructor; - }; + Object failing = + new Object() { + @InjectMocks ThrowingConstructor failingConstructor; + }; try { MockitoAnnotations.initMocks(failing); fail(); } catch (MockitoException e) { - Assertions.assertThat(e.getMessage()).contains("failingConstructor").contains("constructor").contains("threw an exception"); + Assertions.assertThat(e.getMessage()) + .contains("failingConstructor") + .contains("constructor") + .contains("threw an exception"); Assertions.assertThat(e.getCause()).isInstanceOf(RuntimeException.class); } } static class ThrowingConstructor { - ThrowingConstructor() { throw new RuntimeException("aha"); } + ThrowingConstructor() { + throw new RuntimeException("aha"); + } } static class SuperUnderTesting { private List aList; - public List getAList() { return aList; } + public List getAList() { + return aList; + } } static class BaseUnderTesting extends SuperUnderTesting { private Map aMap; - public Map getAMap() { return aMap; } + public Map getAMap() { + return aMap; + } } static class OtherBaseUnderTesting extends SuperUnderTesting { private TreeSet searchTree; - public TreeSet getSearchTree() { return searchTree; } + public TreeSet getSearchTree() { + return searchTree; + } } static class SubUnderTesting extends BaseUnderTesting { private Set histogram1; private Set histogram2; - public Set getHistogram1() { return histogram1; } - public Set getHistogram2() { return histogram2; } + public Set getHistogram1() { + return histogram1; + } + + public Set getHistogram2() { + return histogram2; + } } static class HasTwoFieldsWithSameType { diff --git a/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java b/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java index 6a3e1a478b..bd3bde79ce 100644 --- a/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java +++ b/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java @@ -22,28 +22,25 @@ public class SpyAnnotationInitializedInBaseClassTest extends TestBase { class BaseClass { - @Spy - List list = new LinkedList(); + @Spy List list = new LinkedList(); } - class SubClass extends BaseClass { - - } + class SubClass extends BaseClass {} @Test public void shouldInitSpiesInBaseClass() throws Exception { - //given + // given SubClass subClass = new SubClass(); - //when + // when MockitoAnnotations.initMocks(subClass); - //then + // then assertTrue(MockUtil.isMock(subClass.list)); } @Before @Override public void init() { - //we need to get rid of parent implementation this time + // we need to get rid of parent implementation this time } @Before @@ -51,13 +48,11 @@ public void before() { MockitoAnnotations.initMocks(this); } - @Spy - List spyInBaseclass = new LinkedList(); + @Spy List spyInBaseclass = new LinkedList(); public static class SubTest extends SpyAnnotationInitializedInBaseClassTest { - @Spy - List spyInSubclass = new LinkedList(); + @Spy List spyInSubclass = new LinkedList(); @Test public void shouldInitSpiesInHierarchy() throws Exception { diff --git a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java index e19b2cae39..647b7c49bd 100644 --- a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java +++ b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java @@ -34,20 +34,15 @@ @SuppressWarnings("unused") public class SpyAnnotationTest extends TestBase { - @Spy - final List spiedList = new ArrayList(); + @Spy final List spiedList = new ArrayList(); - @Spy - InnerStaticClassWithNoArgConstructor staticTypeWithNoArgConstructor; + @Spy InnerStaticClassWithNoArgConstructor staticTypeWithNoArgConstructor; - @Spy - InnerStaticClassWithoutDefinedConstructor staticTypeWithoutDefinedConstructor; + @Spy InnerStaticClassWithoutDefinedConstructor staticTypeWithoutDefinedConstructor; - @Spy - MockTranslator translator; + @Spy MockTranslator translator; - @Rule - public final ExpectedException shouldThrow = ExpectedException.none(); + @Rule public final ExpectedException shouldThrow = ExpectedException.none(); @Test public void should_init_spy_by_instance() throws Exception { @@ -67,8 +62,7 @@ public void should_init_spy_and_automatically_create_instance() throws Exception @Test public void should_allow_spying_on_interfaces() throws Exception { class WithSpy { - @Spy - List list; + @Spy List list; } WithSpy withSpy = new WithSpy(); @@ -80,30 +74,29 @@ class WithSpy { @Test public void should_allow_spying_on_interfaces_when_instance_is_concrete() throws Exception { class WithSpy { - @Spy - List list = new LinkedList(); + @Spy List list = new LinkedList(); } WithSpy withSpy = new WithSpy(); - //when + // when MockitoAnnotations.initMocks(withSpy); - //then + // then verify(withSpy.list, never()).clear(); } @Test public void should_report_when_no_arg_less_constructor() throws Exception { class FailingSpy { - @Spy - NoValidConstructor noValidConstructor; + @Spy NoValidConstructor noValidConstructor; } try { MockitoAnnotations.initMocks(new FailingSpy()); fail(); } catch (MockitoException e) { - assertThat(e.getMessage()).contains("Please ensure that the type") + assertThat(e.getMessage()) + .contains("Please ensure that the type") .contains(NoValidConstructor.class.getSimpleName()) .contains("has a no-arg constructor"); } @@ -112,8 +105,7 @@ class FailingSpy { @Test public void should_report_when_constructor_is_explosive() throws Exception { class FailingSpy { - @Spy - ThrowingConstructor throwingConstructor; + @Spy ThrowingConstructor throwingConstructor; } try { @@ -127,8 +119,7 @@ class FailingSpy { @Test public void should_spy_abstract_class() throws Exception { class SpyAbstractClass { - @Spy - AbstractList list; + @Spy AbstractList list; List asSingletonList(String s) { when(list.size()).thenReturn(1); @@ -145,10 +136,8 @@ List asSingletonList(String s) { public void should_spy_inner_class() throws Exception { class WithMockAndSpy { - @Spy - private InnerStrength strength; - @Mock - private List list; + @Spy private InnerStrength strength; + @Mock private List list; abstract class InnerStrength { private final String name; @@ -181,12 +170,10 @@ public void should_reset_spy() throws Exception { @Test public void should_report_when_enclosing_instance_is_needed() throws Exception { class Outer { - class Inner { - } + class Inner {} } class WithSpy { - @Spy - private Outer.Inner inner; + @Spy private Outer.Inner inner; } try { MockitoAnnotations.initMocks(new WithSpy()); @@ -205,7 +192,8 @@ public void should_report_private_inner_not_supported() throws Exception { // Currently fails at instantiation time, because the mock subclass don't have the // 1-arg constructor expected for the outerclass. // org.mockito.internal.creation.instance.ConstructorInstantiator.withParams() - assertThat(e).hasMessageContaining("Unable to initialize @Spy annotated field 'spy_field'") + assertThat(e) + .hasMessageContaining("Unable to initialize @Spy annotated field 'spy_field'") .hasMessageContaining(WithInnerPrivate.InnerPrivate.class.getSimpleName()); } } @@ -216,9 +204,12 @@ public void should_report_private_abstract_inner_not_supported() throws Exceptio MockitoAnnotations.initMocks(new WithInnerPrivateAbstract()); fail(); } catch (MockitoException e) { - assertThat(e).hasMessageContaining("@Spy annotation can't initialize private abstract inner classes") + assertThat(e) + .hasMessageContaining( + "@Spy annotation can't initialize private abstract inner classes") .hasMessageContaining(WithInnerPrivateAbstract.class.getSimpleName()) - .hasMessageContaining(WithInnerPrivateAbstract.InnerPrivateAbstract.class.getSimpleName()) + .hasMessageContaining( + WithInnerPrivateAbstract.InnerPrivateAbstract.class.getSimpleName()) .hasMessageContaining("You should augment the visibility of this inner class"); } } @@ -229,87 +220,83 @@ public void should_report_private_static_abstract_inner_not_supported() throws E MockitoAnnotations.initMocks(new WithInnerPrivateStaticAbstract()); fail(); } catch (MockitoException e) { - assertThat(e).hasMessageContaining("@Spy annotation can't initialize private abstract inner classes") + assertThat(e) + .hasMessageContaining( + "@Spy annotation can't initialize private abstract inner classes") .hasMessageContaining(WithInnerPrivateStaticAbstract.class.getSimpleName()) - .hasMessageContaining(WithInnerPrivateStaticAbstract.InnerPrivateStaticAbstract.class.getSimpleName()) + .hasMessageContaining( + WithInnerPrivateStaticAbstract.InnerPrivateStaticAbstract.class + .getSimpleName()) .hasMessageContaining("You should augment the visibility of this inner class"); } } @Test public void should_be_able_to_stub_and_verify_via_varargs_for_list_params() throws Exception { - // You can stub with varargs. - when(translator.translate("hello", "mockito")).thenReturn(Arrays.asList("you", "too")); + // You can stub with varargs. + when(translator.translate("hello", "mockito")).thenReturn(Arrays.asList("you", "too")); - // Pretend the prod code will call translate(List) with these elements. - assertThat(translator.translate(Arrays.asList("hello", "mockito"))).containsExactly("you", "too"); - assertThat(translator.translate(Arrays.asList("not stubbed"))).isEmpty(); + // Pretend the prod code will call translate(List) with these elements. + assertThat(translator.translate(Arrays.asList("hello", "mockito"))) + .containsExactly("you", "too"); + assertThat(translator.translate(Arrays.asList("not stubbed"))).isEmpty(); - // You can verify with varargs. - verify(translator).translate("hello", "mockito"); + // You can verify with varargs. + verify(translator).translate("hello", "mockito"); } @Test - public void should_be_able_to_stub_and_verify_via_varargs_of_matchers_for_list_params() throws Exception { - // You can stub with varargs of matchers. - when(translator.translate(Mockito.anyString())).thenReturn(Arrays.asList("huh?")); - when(translator.translate(eq("hello"))).thenReturn(Arrays.asList("hi")); - - // Pretend the prod code will call translate(List) with these elements. - assertThat(translator.translate(Arrays.asList("hello"))).containsExactly("hi"); - assertThat(translator.translate(Arrays.asList("not explicitly stubbed"))).containsExactly("huh?"); - - // You can verify with varargs of matchers. - verify(translator).translate(eq("hello")); + public void should_be_able_to_stub_and_verify_via_varargs_of_matchers_for_list_params() + throws Exception { + // You can stub with varargs of matchers. + when(translator.translate(Mockito.anyString())).thenReturn(Arrays.asList("huh?")); + when(translator.translate(eq("hello"))).thenReturn(Arrays.asList("hi")); + + // Pretend the prod code will call translate(List) with these elements. + assertThat(translator.translate(Arrays.asList("hello"))).containsExactly("hi"); + assertThat(translator.translate(Arrays.asList("not explicitly stubbed"))) + .containsExactly("huh?"); + + // You can verify with varargs of matchers. + verify(translator).translate(eq("hello")); } static class WithInnerPrivateStaticAbstract { - @Spy - private InnerPrivateStaticAbstract spy_field; + @Spy private InnerPrivateStaticAbstract spy_field; - private static abstract class InnerPrivateStaticAbstract { - } + private abstract static class InnerPrivateStaticAbstract {} } + static class WithInnerPrivateAbstract { - @Spy - private InnerPrivateAbstract spy_field; + @Spy private InnerPrivateAbstract spy_field; public void some_method() { new InnerPrivateConcrete(); } - private abstract class InnerPrivateAbstract { - } - - private class InnerPrivateConcrete extends InnerPrivateAbstract { + private abstract class InnerPrivateAbstract {} - } + private class InnerPrivateConcrete extends InnerPrivateAbstract {} } static class WithInnerPrivate { - @Spy - private InnerPrivate spy_field; + @Spy private InnerPrivate spy_field; - private class InnerPrivate { - } + private class InnerPrivate {} private class InnerPrivateSub extends InnerPrivate {} } - static class InnerStaticClassWithoutDefinedConstructor { - } + static class InnerStaticClassWithoutDefinedConstructor {} static class InnerStaticClassWithNoArgConstructor { - InnerStaticClassWithNoArgConstructor() { - } + InnerStaticClassWithNoArgConstructor() {} - InnerStaticClassWithNoArgConstructor(String f) { - } + InnerStaticClassWithNoArgConstructor(String f) {} } static class NoValidConstructor { - NoValidConstructor(String f) { - } + NoValidConstructor(String f) {} } static class ThrowingConstructor { @@ -319,14 +306,15 @@ static class ThrowingConstructor { } interface Translator { - List translate(List messages); + List translate(List messages); } - static abstract class MockTranslator implements Translator { - @Override public final List translate(List messages) { - return translate(messages.toArray(new String[0])); - } + abstract static class MockTranslator implements Translator { + @Override + public final List translate(List messages) { + return translate(messages.toArray(new String[0])); + } - abstract List translate(String... messages); + abstract List translate(String... messages); } } diff --git a/src/test/java/org/mockitousage/annotation/SpyInjectionTest.java b/src/test/java/org/mockitousage/annotation/SpyInjectionTest.java index 664f992b1e..9961e6ee20 100644 --- a/src/test/java/org/mockitousage/annotation/SpyInjectionTest.java +++ b/src/test/java/org/mockitousage/annotation/SpyInjectionTest.java @@ -20,6 +20,7 @@ public class SpyInjectionTest extends TestBase { static class HasSpy { private List spy; + public void setSpy(List spy) { this.spy = spy; } diff --git a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java index 874172c271..b89c29cae6 100644 --- a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java +++ b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java @@ -16,17 +16,21 @@ public class WrongSetOfAnnotationsTest extends TestBase { - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void should_not_allow_Mock_and_Spy() throws Exception { - MockitoAnnotations.initMocks(new Object() { - @Mock @Spy List mock; - }); + MockitoAnnotations.initMocks( + new Object() { + @Mock @Spy List mock; + }); } @Test public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exception { try { - MockitoAnnotations.initMocks(new Object() { @InjectMocks @Spy List mock; }); + MockitoAnnotations.initMocks( + new Object() { + @InjectMocks @Spy List mock; + }); fail(); } catch (MockitoException me) { Assertions.assertThat(me.getMessage()).contains("'List' is an interface"); @@ -35,39 +39,45 @@ public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exceptio @Test public void should_allow_Spy_and_InjectMocks() throws Exception { - MockitoAnnotations.initMocks(new Object() { - @InjectMocks - @Spy - WithDependency mock; - }); + MockitoAnnotations.initMocks( + new Object() { + @InjectMocks @Spy WithDependency mock; + }); } - static class WithDependency { List list; } - @Test(expected=MockitoException.class) + static class WithDependency { + List list; + } + + @Test(expected = MockitoException.class) public void should_not_allow_Mock_and_InjectMocks() throws Exception { - MockitoAnnotations.initMocks(new Object() { - @InjectMocks @Mock List mock; - }); + MockitoAnnotations.initMocks( + new Object() { + @InjectMocks @Mock List mock; + }); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void should_not_allow_Captor_and_Mock() throws Exception { - MockitoAnnotations.initMocks(new Object() { - @Mock @Captor ArgumentCaptor captor; - }); + MockitoAnnotations.initMocks( + new Object() { + @Mock @Captor ArgumentCaptor captor; + }); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void should_not_allow_Captor_and_Spy() throws Exception { - MockitoAnnotations.initMocks(new Object() { - @Spy @Captor ArgumentCaptor captor; - }); + MockitoAnnotations.initMocks( + new Object() { + @Spy @Captor ArgumentCaptor captor; + }); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void should_not_allow_Captor_and_InjectMocks() throws Exception { - MockitoAnnotations.initMocks(new Object() { - @InjectMocks @Captor ArgumentCaptor captor; - }); + MockitoAnnotations.initMocks( + new Object() { + @InjectMocks @Captor ArgumentCaptor captor; + }); } } diff --git a/src/test/java/org/mockitousage/basicapi/MockAccessTest.java b/src/test/java/org/mockitousage/basicapi/MockAccessTest.java index 66280dbd10..13c0c744c7 100644 --- a/src/test/java/org/mockitousage/basicapi/MockAccessTest.java +++ b/src/test/java/org/mockitousage/basicapi/MockAccessTest.java @@ -4,7 +4,6 @@ */ package org.mockitousage.basicapi; - import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java b/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java index 1be6359e95..f7c3b00b6b 100644 --- a/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java +++ b/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java @@ -19,15 +19,17 @@ public class MockingMultipleInterfacesTest { class Foo {} + interface IFoo {} + interface IBar {} @Test public void should_allow_multiple_interfaces() { - //when + // when Foo mock = mock(Foo.class, withSettings().extraInterfaces(IFoo.class, IBar.class)); - //then + // then assertThat(mock).isInstanceOf(IFoo.class); assertThat(mock).isInstanceOf(IBar.class); } @@ -35,47 +37,50 @@ public void should_allow_multiple_interfaces() { @Test public void should_scream_when_null_passed_instead_of_an_interface() { try { - //when + // when mock(Foo.class, withSettings().extraInterfaces(IFoo.class, null)); fail(); } catch (MockitoException e) { - //then - assertThat(e.getMessage()).contains("extraInterfaces() does not accept null parameters"); + // then + assertThat(e.getMessage()) + .contains("extraInterfaces() does not accept null parameters"); } } @Test public void should_scream_when_no_args_passed() { try { - //when + // when mock(Foo.class, withSettings().extraInterfaces()); fail(); } catch (MockitoException e) { - //then - assertThat(e.getMessage()).contains("extraInterfaces() requires at least one interface"); + // then + assertThat(e.getMessage()) + .contains("extraInterfaces() requires at least one interface"); } } @Test public void should_scream_when_null_passed_instead_of_an_array() { try { - //when + // when mock(Foo.class, withSettings().extraInterfaces((Class[]) null)); fail(); } catch (MockitoException e) { - //then - assertThat(e.getMessage()).contains("extraInterfaces() requires at least one interface"); + // then + assertThat(e.getMessage()) + .contains("extraInterfaces() requires at least one interface"); } } @Test public void should_scream_when_non_interface_passed() { try { - //when + // when mock(Foo.class, withSettings().extraInterfaces(Foo.class)); fail(); } catch (MockitoException e) { - //then + // then assertThat(e.getMessage()).contains("Foo which is not an interface"); } } @@ -83,28 +88,37 @@ public void should_scream_when_non_interface_passed() { @Test public void should_scream_when_the_same_interfaces_passed() { try { - //when + // when mock(IMethods.class, withSettings().extraInterfaces(IMethods.class)); fail(); } catch (MockitoException e) { - //then + // then assertThat(e.getMessage()).contains("You mocked following type: IMethods"); } } @Test - public void should_mock_class_with_interfaces_of_different_class_loader_AND_different_classpaths() throws ClassNotFoundException { - // Note : if classes are in the same classpath, SearchingClassLoader can find the class/classes and load them in the first matching classloader - Class interface1 = inMemoryClassLoader() - .withClassDefinition("test.Interface1", makeMarkerInterface("test.Interface1")) - .build() - .loadClass("test.Interface1"); - Class interface2 = inMemoryClassLoader() - .withClassDefinition("test.Interface2", makeMarkerInterface("test.Interface2")) - .build() - .loadClass("test.Interface2"); + public void + should_mock_class_with_interfaces_of_different_class_loader_AND_different_classpaths() + throws ClassNotFoundException { + // Note : if classes are in the same classpath, SearchingClassLoader can find the + // class/classes and load them in the first matching classloader + Class interface1 = + inMemoryClassLoader() + .withClassDefinition( + "test.Interface1", makeMarkerInterface("test.Interface1")) + .build() + .loadClass("test.Interface1"); + Class interface2 = + inMemoryClassLoader() + .withClassDefinition( + "test.Interface2", makeMarkerInterface("test.Interface2")) + .build() + .loadClass("test.Interface2"); Object mocked = mock(interface1, withSettings().extraInterfaces(interface2)); - assertThat(interface2.isInstance(mocked)).describedAs("mock should be assignable from interface2 type").isTrue(); + assertThat(interface2.isInstance(mocked)) + .describedAs("mock should be assignable from interface2 type") + .isTrue(); } } diff --git a/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java b/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java index 8689592b2c..241c7754a9 100644 --- a/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java +++ b/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java @@ -39,62 +39,66 @@ public void should_create_mock_when_constructor_is_private() { @Test public void should_combine_mock_name_and_smart_nulls() { - //given - IMethods mock = mock(IMethods.class, withSettings() - .defaultAnswer(RETURNS_SMART_NULLS) - .name("great mockie")); + // given + IMethods mock = + mock( + IMethods.class, + withSettings().defaultAnswer(RETURNS_SMART_NULLS).name("great mockie")); - //when + // when IMethods smartNull = mock.iMethodsReturningMethod(); String name = mock.toString(); - //then + // then assertThat(name).contains("great mockie"); - //and + // and try { smartNull.simpleMethod(); fail(); - } catch(SmartNullPointerException e) {} + } catch (SmartNullPointerException e) { + } } @Test public void should_combine_mock_name_and_extra_interfaces() { - //given - IMethods mock = mock(IMethods.class, withSettings() - .extraInterfaces(List.class) - .name("great mockie")); + // given + IMethods mock = + mock( + IMethods.class, + withSettings().extraInterfaces(List.class).name("great mockie")); - //when + // when String name = mock.toString(); - //then + // then assertThat(name).contains("great mockie"); - //and + // and assertTrue(mock instanceof List); } @Test public void should_specify_mock_name_via_settings() { - //given + // given IMethods mock = mock(IMethods.class, withSettings().name("great mockie")); - //when + // when String name = mock.toString(); - //then + // then assertThat(name).contains("great mockie"); } @Test public void should_scream_when_spy_created_with_wrong_type() { - //given + // given List list = new LinkedList(); try { - //when + // when mock(List.class, withSettings().spiedInstance(list)); fail(); - //then - } catch (MockitoException e) {} + // then + } catch (MockitoException e) { + } } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) @@ -112,14 +116,15 @@ public void should_allow_inline_mock_creation() { @Retention(RetentionPolicy.RUNTIME) @interface SomeAnnotation {} - @SomeAnnotation static class Foo {} + @SomeAnnotation + static class Foo {} @Test public void should_strip_annotations() { Foo withAnnotations = mock(Foo.class); Foo withoutAnnotations = mock(Foo.class, withSettings().withoutAnnotations()); - //expect: + // expect: assertTrue(withAnnotations.getClass().isAnnotationPresent(SomeAnnotation.class)); assertFalse(withoutAnnotations.getClass().isAnnotationPresent(SomeAnnotation.class)); } diff --git a/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java b/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java index 1c3548521e..c2d1caa35b 100644 --- a/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java +++ b/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java @@ -32,19 +32,33 @@ public class MocksSerializationForAnnotationTest extends TestBase implements Ser private static final long serialVersionUID = 6160482220413048624L; @Mock Any any; - @Mock(serializable=true) Bar barMock; - @Mock(serializable=true) IMethods imethodsMock; - @Mock(serializable=true) IMethods imethodsMock2; - @Mock(serializable=true) Any anyMock; - @Mock(serializable=true) AlreadySerializable alreadySerializableMock; - @Mock(extraInterfaces={List.class},serializable=true) IMethods imethodsWithExtraInterfacesMock; + + @Mock(serializable = true) + Bar barMock; + + @Mock(serializable = true) + IMethods imethodsMock; + + @Mock(serializable = true) + IMethods imethodsMock2; + + @Mock(serializable = true) + Any anyMock; + + @Mock(serializable = true) + AlreadySerializable alreadySerializableMock; + + @Mock( + extraInterfaces = {List.class}, + serializable = true) + IMethods imethodsWithExtraInterfacesMock; @Test public void should_allow_throws_exception_to_be_serializable() throws Exception { // given when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException())); - //when-serialize then-deserialize + // when-serialize then-deserialize serializeAndBack(barMock); } @@ -96,7 +110,8 @@ public void should_all_mock_and_serializable_value_to_be_serialized() throws Exc } @Test - public void should_serialize_method_call_with_parameters_that_are_serializable() throws Exception { + public void should_serialize_method_call_with_parameters_that_are_serializable() + throws Exception { List value = Collections.emptyList(); when(imethodsMock.objectArgMethod(value)).thenReturn(value); @@ -147,8 +162,9 @@ public void should_verify_even_if_some_methods_called_after_serialization() thro // then verify(readObject, times(2)).simpleMethod(1); - //this test is working because it seems that java serialization mechanism replaces all instances - //of serialized object in the object graph (if there are any) + // this test is working because it seems that java serialization mechanism replaces all + // instances + // of serialized object in the object graph (if there are any) } class Bar implements Serializable { @@ -161,6 +177,7 @@ public Foo doSomething() { class Foo implements Serializable { Bar bar; + Foo() { bar = new Bar(); bar.foo = this; @@ -169,17 +186,17 @@ class Foo implements Serializable { @Test public void should_serialization_work() throws Exception { - //given + // given Foo foo = new Foo(); - //when + // when foo = serializeAndBack(foo); - //then + // then assertSame(foo, foo.bar.foo); } @Test public void should_stub_even_if_some_methods_called_after_serialization() throws Exception { - //given + // given // when when(imethodsMock.simpleMethod(1)).thenReturn("foo"); ByteArrayOutputStream serialized = serializeMock(imethodsMock); @@ -227,7 +244,7 @@ public void should_serialize_with_stubbing_callback() throws Exception { // given CustomAnswersMustImplementSerializableForSerializationToWork answer = - new CustomAnswersMustImplementSerializableForSerializationToWork(); + new CustomAnswersMustImplementSerializableForSerializationToWork(); answer.string = "return value"; when(imethodsMock.objectArgMethod(anyString())).thenAnswer(answer); @@ -240,8 +257,9 @@ public void should_serialize_with_stubbing_callback() throws Exception { } static class CustomAnswersMustImplementSerializableForSerializationToWork - implements Answer, Serializable { + implements Answer, Serializable { private String string; + public Object answer(InvocationOnMock invocation) throws Throwable { invocation.getArguments(); invocation.getMock(); @@ -253,10 +271,13 @@ public Object answer(InvocationOnMock invocation) throws Throwable { public void should_serialize_with_real_object_spy() throws Exception { // given SerializableSample list = new SerializableSample(); - SerializableSample spy = mock(SerializableSample.class, withSettings() - .spiedInstance(list) - .defaultAnswer(CALLS_REAL_METHODS) - .serializable()); + SerializableSample spy = + mock( + SerializableSample.class, + withSettings() + .spiedInstance(list) + .defaultAnswer(CALLS_REAL_METHODS) + .serializable()); when(spy.foo()).thenReturn("foo"); // when @@ -305,27 +326,33 @@ public void should_serialize_already_serializable_class() throws Exception { @Test public void should_be_serialize_and_have_extra_interfaces() throws Exception { - //then + // then Assertions.assertThat((Object) serializeAndBack((List) imethodsWithExtraInterfacesMock)) .isInstanceOf(List.class) .isInstanceOf(IMethods.class); } static class NotSerializableAndNoDefaultConstructor { - NotSerializableAndNoDefaultConstructor(Observable o) { super(); } + NotSerializableAndNoDefaultConstructor(Observable o) { + super(); + } } static class SerializableAndNoDefaultConstructor implements Serializable { - SerializableAndNoDefaultConstructor(Observable o) { super(); } + SerializableAndNoDefaultConstructor(Observable o) { + super(); + } } public static class TestClassThatHoldValidField { - @Mock(serializable=true) + @Mock(serializable = true) SerializableAndNoDefaultConstructor serializableAndNoDefaultConstructor; } @Test - public void should_be_able_to_serialize_type_that_implements_Serializable_but_but_dont_declare_a_no_arg_constructor() throws Exception { + public void + should_be_able_to_serialize_type_that_implements_Serializable_but_but_dont_declare_a_no_arg_constructor() + throws Exception { TestClassThatHoldValidField testClass = new TestClassThatHoldValidField(); MockitoAnnotations.initMocks(testClass); diff --git a/src/test/java/org/mockitousage/basicapi/MocksSerializationTest.java b/src/test/java/org/mockitousage/basicapi/MocksSerializationTest.java index a021c53c45..f1a40697b5 100644 --- a/src/test/java/org/mockitousage/basicapi/MocksSerializationTest.java +++ b/src/test/java/org/mockitousage/basicapi/MocksSerializationTest.java @@ -49,7 +49,7 @@ public void should_allow_method_delegation() throws Exception { Foo fooMock = mock(Foo.class); when(barMock.doSomething()).thenAnswer(new ThrowsException(new RuntimeException())); - //when-serialize then-deserialize + // when-serialize then-deserialize serializeAndBack(barMock); } @@ -107,7 +107,8 @@ public void should_all_mock_and_serializable_value_to_be_serialized() throws Exc } @Test - public void should_serialize_method_call_with_parameters_that_are_serializable() throws Exception { + public void should_serialize_method_call_with_parameters_that_are_serializable() + throws Exception { IMethods mock = mock(IMethods.class, withSettings().serializable()); List value = Collections.emptyList(); when(mock.objectArgMethod(value)).thenReturn(value); @@ -151,7 +152,7 @@ public void should_verify_called_n_times_for_serialized_mock() throws Exception @Test public void should_verify_even_if_some_methods_called_after_serialization() throws Exception { - //given + // given IMethods mock = mock(IMethods.class, withSettings().serializable()); // when @@ -163,8 +164,9 @@ public void should_verify_even_if_some_methods_called_after_serialization() thro // then verify(readObject, times(2)).simpleMethod(1); - //this test is working because it seems that java serialization mechanism replaces all instances - //of serialized object in the object graph (if there are any) + // this test is working because it seems that java serialization mechanism replaces all + // instances + // of serialized object in the object graph (if there are any) } class Bar implements Serializable { @@ -177,6 +179,7 @@ public Foo doSomething() { class Foo implements Serializable { Bar bar; + Foo() { bar = new Bar(); bar.foo = this; @@ -185,17 +188,17 @@ class Foo implements Serializable { @Test public void should_serialization_work() throws Exception { - //given + // given Foo foo = new Foo(); - //when + // when foo = serializeAndBack(foo); - //then + // then assertSame(foo, foo.bar.foo); } @Test public void should_stub_even_if_some_methods_called_after_serialization() throws Exception { - //given + // given IMethods mock = mock(IMethods.class, withSettings().serializable()); // when @@ -264,6 +267,7 @@ public void should_serialize_with_stubbing_callback() throws Exception { class CustomAnswersMustImplementSerializableForSerializationToWork implements Answer, Serializable { private String string; + public Object answer(InvocationOnMock invocation) throws Throwable { invocation.getArguments(); invocation.getMock(); @@ -275,10 +279,13 @@ public Object answer(InvocationOnMock invocation) throws Throwable { public void should_serialize_with_real_object_spy() throws Exception { // given SerializableClass sample = new SerializableClass(); - SerializableClass spy = mock(SerializableClass.class, withSettings() - .spiedInstance(sample) - .defaultAnswer(CALLS_REAL_METHODS) - .serializable()); + SerializableClass spy = + mock( + SerializableClass.class, + withSettings() + .spiedInstance(sample) + .defaultAnswer(CALLS_REAL_METHODS) + .serializable()); when(spy.foo()).thenReturn("foo"); // when @@ -332,11 +339,13 @@ public void should_serialize_already_serializable_class() throws Exception { @Test public void should_be_serialize_and_have_extra_interfaces() throws Exception { - //when - IMethods mock = mock(IMethods.class, withSettings().serializable().extraInterfaces(List.class)); - IMethods mockTwo = mock(IMethods.class, withSettings().extraInterfaces(List.class).serializable()); + // when + IMethods mock = + mock(IMethods.class, withSettings().serializable().extraInterfaces(List.class)); + IMethods mockTwo = + mock(IMethods.class, withSettings().extraInterfaces(List.class).serializable()); - //then + // then Assertions.assertThat((Object) serializeAndBack((List) mock)) .isInstanceOf(List.class) .isInstanceOf(IMethods.class); @@ -346,28 +355,34 @@ public void should_be_serialize_and_have_extra_interfaces() throws Exception { } static class SerializableAndNoDefaultConstructor implements Serializable { - SerializableAndNoDefaultConstructor(Observable o) { super(); } + SerializableAndNoDefaultConstructor(Observable o) { + super(); + } } @Test - public void should_be_able_to_serialize_type_that_implements_Serializable_but_but_dont_declare_a_no_arg_constructor() throws Exception { + public void + should_be_able_to_serialize_type_that_implements_Serializable_but_but_dont_declare_a_no_arg_constructor() + throws Exception { serializeAndBack(mock(SerializableAndNoDefaultConstructor.class)); } - - public static class AClassWithPrivateNoArgConstructor { private AClassWithPrivateNoArgConstructor() {} - List returningSomething() { return Collections.emptyList(); } + + List returningSomething() { + return Collections.emptyList(); + } } @Test - public void private_constructor_currently_not_supported_at_the_moment_at_deserialization_time() throws Exception { + public void private_constructor_currently_not_supported_at_the_moment_at_deserialization_time() + throws Exception { // given - AClassWithPrivateNoArgConstructor mockWithPrivateConstructor = Mockito.mock( - AClassWithPrivateNoArgConstructor.class, - Mockito.withSettings().serializable() - ); + AClassWithPrivateNoArgConstructor mockWithPrivateConstructor = + Mockito.mock( + AClassWithPrivateNoArgConstructor.class, + Mockito.withSettings().serializable()); try { // when @@ -379,14 +394,17 @@ public void private_constructor_currently_not_supported_at_the_moment_at_deseria } } - @Test public void BUG_ISSUE_399_try_some_mocks_with_current_answers() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V7)); - IMethods iMethods = mock(IMethods.class, withSettings().serializable().defaultAnswer(RETURNS_DEEP_STUBS)); + IMethods iMethods = + mock( + IMethods.class, + withSettings().serializable().defaultAnswer(RETURNS_DEEP_STUBS)); - when(iMethods.iMethodsReturningMethod().linkedListReturningMethod().contains(anyString())).thenReturn(false); + when(iMethods.iMethodsReturningMethod().linkedListReturningMethod().contains(anyString())) + .thenReturn(false); serializeAndBack(iMethods); } diff --git a/src/test/java/org/mockitousage/basicapi/ObjectsSerializationTest.java b/src/test/java/org/mockitousage/basicapi/ObjectsSerializationTest.java index 171f434b18..c3c668c96d 100644 --- a/src/test/java/org/mockitousage/basicapi/ObjectsSerializationTest.java +++ b/src/test/java/org/mockitousage/basicapi/ObjectsSerializationTest.java @@ -15,11 +15,14 @@ @SuppressWarnings("serial") public class ObjectsSerializationTest extends TestBase implements Serializable { - //Ok, this test has nothing to do with mocks but it shows fundamental feature of java serialization that - //plays important role in mocking: - //Serialization/deserialization actually replaces all instances of serialized object in the object graph (if there are any) - //thanks to that mechanizm, stubbing & verification can correctly match method invocations because - //one of the parts of invocation matching is checking if mock object is the same + // Ok, this test has nothing to do with mocks but it shows fundamental feature of java + // serialization that + // plays important role in mocking: + // Serialization/deserialization actually replaces all instances of serialized object in the + // object graph (if there are any) + // thanks to that mechanizm, stubbing & verification can correctly match method invocations + // because + // one of the parts of invocation matching is checking if mock object is the same class Bar implements Serializable { Foo foo; @@ -27,6 +30,7 @@ class Bar implements Serializable { class Foo implements Serializable { Bar bar; + Foo() { bar = new Bar(); bar.foo = this; @@ -35,11 +39,11 @@ class Foo implements Serializable { @Test public void shouldSerializationWork() throws Exception { - //given + // given Foo foo = new Foo(); - //when + // when foo = serializeAndBack(foo); - //then + // then assertSame(foo, foo.bar.foo); } } diff --git a/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java b/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java index 3857e084b1..72903f9e6e 100644 --- a/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java +++ b/src/test/java/org/mockitousage/basicapi/ReplacingObjectMethodsTest.java @@ -14,14 +14,18 @@ public class ReplacingObjectMethodsTest extends TestBase { private interface DummyInterface {} + private class DummyClass {} @Test public void shouldProvideMockyImplementationOfToString() { DummyClass dummyClass = Mockito.mock(DummyClass.class); - assertEquals("Mock for DummyClass, hashCode: " + dummyClass.hashCode(), dummyClass.toString()); + assertEquals( + "Mock for DummyClass, hashCode: " + dummyClass.hashCode(), dummyClass.toString()); DummyInterface dummyInterface = Mockito.mock(DummyInterface.class); - assertEquals("Mock for DummyInterface, hashCode: " + dummyInterface.hashCode(), dummyInterface.toString()); + assertEquals( + "Mock for DummyInterface, hashCode: " + dummyInterface.hashCode(), + dummyInterface.toString()); } @Test @@ -50,16 +54,20 @@ public void shouldReplaceObjectMethodsWhenOverridden() { public static class ObjectMethodsOverridden { public boolean equals(Object o) { - throw new RuntimeException("Should not be called. MethodInterceptorFilter provides implementation"); + throw new RuntimeException( + "Should not be called. MethodInterceptorFilter provides implementation"); } + public int hashCode() { - throw new RuntimeException("Should not be called. MethodInterceptorFilter provides implementation"); + throw new RuntimeException( + "Should not be called. MethodInterceptorFilter provides implementation"); } + public String toString() { - throw new RuntimeException("Should not be called. MethodInterceptorFilter provides implementation"); + throw new RuntimeException( + "Should not be called. MethodInterceptorFilter provides implementation"); } } - public static class ObjectMethodsOverriddenSubclass extends ObjectMethodsOverridden { - } + public static class ObjectMethodsOverriddenSubclass extends ObjectMethodsOverridden {} } diff --git a/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java b/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java index d98995971d..e6f2caf8d6 100644 --- a/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java +++ b/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java @@ -15,11 +15,9 @@ public class ResetInvocationsTest extends TestBase { - @Mock - IMethods methods; + @Mock IMethods methods; - @Mock - IMethods moarMethods; + @Mock IMethods moarMethods; @Test public void reset_invocations_should_reset_only_invocations() { @@ -51,6 +49,6 @@ public void resettingNonMockIsSafe() { @Test(expected = NotAMockException.class) public void resettingNullIsSafe() { - clearInvocations(new Object[]{null}); + clearInvocations(new Object[] {null}); } } diff --git a/src/test/java/org/mockitousage/basicapi/ResetTest.java b/src/test/java/org/mockitousage/basicapi/ResetTest.java index 9481b08475..8f4d7238de 100644 --- a/src/test/java/org/mockitousage/basicapi/ResetTest.java +++ b/src/test/java/org/mockitousage/basicapi/ResetTest.java @@ -18,11 +18,9 @@ public class ResetTest extends TestBase { - @Mock - private IMethods mock; + @Mock private IMethods mock; - @Mock - private IMethods mockTwo; + @Mock private IMethods mockTwo; @Test public void shouldResetOngoingStubbingSoThatMoreMeaningfulExceptionsAreRaised() { @@ -42,7 +40,7 @@ public void resettingNonMockIsSafe() { @Test(expected = NotAMockException.class) public void resettingNullIsSafe() { - reset(new Object[]{null}); + reset(new Object[] {null}); } @Test @@ -51,7 +49,8 @@ public void shouldRemoveAllStubbing() throws Exception { when(mock.objectReturningMethod(200)).thenReturn(200); reset(mock); assertNull(mock.objectReturningMethod(200)); - assertEquals("default behavior should return null", null, mock.objectReturningMethod("blah")); + assertEquals( + "default behavior should return null", null, mock.objectReturningMethod("blah")); } @Test @@ -112,7 +111,7 @@ public void shouldResetMultipleMocks() { @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) @Test public void shouldValidateStateWhenResetting() { - //invalid verify: + // invalid verify: verify(mock); try { @@ -124,11 +123,11 @@ public void shouldValidateStateWhenResetting() { @Test public void shouldMaintainPreviousDefaultAnswer() { - //given + // given mock = mock(IMethods.class, RETURNS_MOCKS); - //when + // when reset(mock); - //then + // then assertNotNull(mock.iMethodsReturningMethod()); } } diff --git a/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java b/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java index d71077f819..4e9fc59c53 100644 --- a/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java +++ b/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java @@ -21,10 +21,14 @@ public class UsingVarargsTest extends TestBase { private interface IVarArgs { void withStringVarargs(int value, String... s); + String withStringVarargsReturningString(int value, String... s); + void withObjectVarargs(int value, Object... o); + boolean withBooleanVarargs(int value, boolean... b); - int foo(Object ... objects); + + int foo(Object... objects); } @Mock IVarArgs mock; @@ -82,7 +86,8 @@ public void shouldVerifyStringVarargs() { try { verify(mock).withStringVarargs(2, "1", "2", "79", "4"); fail(); - } catch (ArgumentsAreDifferent e) {} + } catch (ArgumentsAreDifferent e) { + } } @Test @@ -96,7 +101,8 @@ public void shouldVerifyObjectVarargs() { try { verifyNoMoreInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -110,7 +116,8 @@ public void shouldVerifyBooleanVarargs() { try { verify(mock).withBooleanVarargs(3, true, true, true, true); fail(); - } catch (ArgumentsAreDifferent e) {} + } catch (ArgumentsAreDifferent e) { + } } @Test @@ -135,41 +142,42 @@ public void varArgs(String... args) {} interface MixedVarargs { String doSomething(String one, String... varargs); + String doSomething(String one, String two, String... varargs); } @SuppressWarnings("all") @Test - //See bug #31 + // See bug #31 public void shouldStubCorrectlyWhenMixedVarargsUsed() { MixedVarargs mixedVarargs = mock(MixedVarargs.class); - when(mixedVarargs.doSomething("hello", (String[])null)).thenReturn("hello"); - when(mixedVarargs.doSomething("goodbye", (String[])null)).thenReturn("goodbye"); + when(mixedVarargs.doSomething("hello", (String[]) null)).thenReturn("hello"); + when(mixedVarargs.doSomething("goodbye", (String[]) null)).thenReturn("goodbye"); - String result = mixedVarargs.doSomething("hello",(String[]) null); + String result = mixedVarargs.doSomething("hello", (String[]) null); assertEquals("hello", result); - verify(mixedVarargs).doSomething("hello", (String[])null); + verify(mixedVarargs).doSomething("hello", (String[]) null); } @SuppressWarnings("all") @Test public void shouldStubCorrectlyWhenDoubleStringAndMixedVarargsUsed() { MixedVarargs mixedVarargs = mock(MixedVarargs.class); - when(mixedVarargs.doSomething("one", "two", (String[])null)).thenReturn("hello"); - when(mixedVarargs.doSomething("1", "2", (String[])null)).thenReturn("goodbye"); + when(mixedVarargs.doSomething("one", "two", (String[]) null)).thenReturn("hello"); + when(mixedVarargs.doSomething("1", "2", (String[]) null)).thenReturn("goodbye"); - String result = mixedVarargs.doSomething("one", "two", (String[])null); + String result = mixedVarargs.doSomething("one", "two", (String[]) null); assertEquals("hello", result); } @Test - //See bug #157 + // See bug #157 public void shouldMatchEasilyEmptyVararg() throws Exception { - //when + // when when(mock.foo(anyVararg())).thenReturn(-1); - //then + // then assertEquals(-1, mock.foo()); } } diff --git a/src/test/java/org/mockitousage/bugs/AIOOBExceptionWithAtLeastTest.java b/src/test/java/org/mockitousage/bugs/AIOOBExceptionWithAtLeastTest.java index f1b862707e..f7127240e0 100644 --- a/src/test/java/org/mockitousage/bugs/AIOOBExceptionWithAtLeastTest.java +++ b/src/test/java/org/mockitousage/bugs/AIOOBExceptionWithAtLeastTest.java @@ -9,12 +9,14 @@ import org.junit.Test; import org.mockitoutil.TestBase; -//see bug 116 +// see bug 116 public class AIOOBExceptionWithAtLeastTest extends TestBase { interface IProgressMonitor { void beginTask(String s, int i); + void worked(int i); + void done(); } diff --git a/src/test/java/org/mockitousage/bugs/ActualInvocationHasNullArgumentNPEBugTest.java b/src/test/java/org/mockitousage/bugs/ActualInvocationHasNullArgumentNPEBugTest.java index 13d37662c4..c426e912b0 100644 --- a/src/test/java/org/mockitousage/bugs/ActualInvocationHasNullArgumentNPEBugTest.java +++ b/src/test/java/org/mockitousage/bugs/ActualInvocationHasNullArgumentNPEBugTest.java @@ -18,18 +18,18 @@ public interface Fun { @Test public void shouldAllowPassingNullArgument() { - //given + // given Fun mockFun = mock(Fun.class); when(mockFun.doFun((String) anyObject())).thenReturn("value"); - //when + // when mockFun.doFun(null); - //then + // then try { verify(mockFun).doFun("hello"); - } catch(AssertionError r) { - //it's ok, we just want to reproduce the bug + } catch (AssertionError r) { + // it's ok, we just want to reproduce the bug return; } fail(); diff --git a/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java b/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java index 04afc0b199..fc582ee4c2 100644 --- a/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java +++ b/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java @@ -13,14 +13,13 @@ public class AtLeastMarksAllInvocationsVerified extends TestBase { public static class SomeMethods { - public void allowedMethod() { - } - public void disallowedMethod() { - } + public void allowedMethod() {} + + public void disallowedMethod() {} } @Test(expected = org.mockito.exceptions.verification.NoInteractionsWanted.class) - public void shouldFailBecauseDisallowedMethodWasCalled(){ + public void shouldFailBecauseDisallowedMethodWasCalled() { SomeMethods someMethods = mock(SomeMethods.class); someMethods.allowedMethod(); diff --git a/src/test/java/org/mockitousage/bugs/BridgeMethodsHitAgainTest.java b/src/test/java/org/mockitousage/bugs/BridgeMethodsHitAgainTest.java index 7d4ad34303..c5f1b63102 100644 --- a/src/test/java/org/mockitousage/bugs/BridgeMethodsHitAgainTest.java +++ b/src/test/java/org/mockitousage/bugs/BridgeMethodsHitAgainTest.java @@ -15,45 +15,46 @@ import org.mockito.Mockito; import org.mockitoutil.TestBase; -//see issue 101 +// see issue 101 public class BridgeMethodsHitAgainTest extends TestBase { - public interface Factory {} - public interface ExtendedFactory extends Factory {} + public interface Factory {} - public interface SomeInterface { - Factory factory(); - } + public interface ExtendedFactory extends Factory {} - public interface SomeSubInterface extends SomeInterface { - ExtendedFactory factory(); - } + public interface SomeInterface { + Factory factory(); + } - public interface Base { - int test(T value); - } + public interface SomeSubInterface extends SomeInterface { + ExtendedFactory factory(); + } - public interface Extended extends Base { - @Override - int test(String value); - } + public interface Base { + int test(T value); + } - @Mock SomeSubInterface someSubInterface; - @Mock ExtendedFactory extendedFactory; + public interface Extended extends Base { + @Override + int test(String value); + } - @Test - public void basicCheck() { - Mockito.when((someSubInterface).factory()).thenReturn(extendedFactory); - SomeInterface si = someSubInterface; - assertTrue(si.factory() != null); - } + @Mock SomeSubInterface someSubInterface; + @Mock ExtendedFactory extendedFactory; - @Test - public void checkWithExtraCast() { - Mockito.when(((SomeInterface) someSubInterface).factory()).thenReturn(extendedFactory); - SomeInterface si = someSubInterface; - assertTrue(si.factory() != null); - } + @Test + public void basicCheck() { + Mockito.when((someSubInterface).factory()).thenReturn(extendedFactory); + SomeInterface si = someSubInterface; + assertTrue(si.factory() != null); + } + + @Test + public void checkWithExtraCast() { + Mockito.when(((SomeInterface) someSubInterface).factory()).thenReturn(extendedFactory); + SomeInterface si = someSubInterface; + assertTrue(si.factory() != null); + } @Test public void testBridgeInvocationIsRecordedForInterceptedMethod() { diff --git a/src/test/java/org/mockitousage/bugs/CaptorAnnotationAutoboxingTest.java b/src/test/java/org/mockitousage/bugs/CaptorAnnotationAutoboxingTest.java index ebbaa11ec7..78c70e912f 100644 --- a/src/test/java/org/mockitousage/bugs/CaptorAnnotationAutoboxingTest.java +++ b/src/test/java/org/mockitousage/bugs/CaptorAnnotationAutoboxingTest.java @@ -14,11 +14,12 @@ import org.mockito.Mock; import org.mockitoutil.TestBase; -//see issue 188 +// see issue 188 public class CaptorAnnotationAutoboxingTest extends TestBase { interface Fun { void doFun(double prmitive); + void moreFun(int howMuch); } @@ -27,10 +28,10 @@ interface Fun { @Test public void shouldAutoboxSafely() { - //given + // given fun.doFun(1.0); - //then + // then verify(fun).doFun(captor.capture()); assertEquals(Double.valueOf(1.0), captor.getValue()); } diff --git a/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java b/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java index 851d4175f0..6e9949f6c4 100644 --- a/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java +++ b/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java @@ -20,22 +20,28 @@ public interface TestMock { @Test(expected = NoInteractionsWanted.class) public void should_not_throw_ClassCastException_when_mock_verification_fails() { - TestMock test = mock(TestMock.class, new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return false; - } - }); + TestMock test = + mock( + TestMock.class, + new Answer() { + public Object answer(InvocationOnMock invocation) throws Throwable { + return false; + } + }); test.m1(); verifyZeroInteractions(test); } @Test(expected = WrongTypeOfReturnValue.class) public void should_report_bogus_default_answer() throws Exception { - TestMock test = mock(TestMock.class, new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return false; - } - }); + TestMock test = + mock( + TestMock.class, + new Answer() { + public Object answer(InvocationOnMock invocation) throws Throwable { + return false; + } + }); test.toString(); } diff --git a/src/test/java/org/mockitousage/bugs/CompareMatcherTest.java b/src/test/java/org/mockitousage/bugs/CompareMatcherTest.java index 01243c066c..240199509f 100644 --- a/src/test/java/org/mockitousage/bugs/CompareMatcherTest.java +++ b/src/test/java/org/mockitousage/bugs/CompareMatcherTest.java @@ -24,11 +24,9 @@ public class CompareMatcherTest { private static final Object NOT_A_COMPARABLE = new Object(); - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - public IMethods mock; + @Mock public IMethods mock; /** * Should not throw an {@link NullPointerException} @@ -41,7 +39,7 @@ public void compareNullArgument() { when(mock.forInteger(leq(5))).thenReturn(""); - assertThat(mock.forInteger(null)).isNull();// a default value must be returned + assertThat(mock.forInteger(null)).isNull(); // a default value must be returned } /** @@ -51,7 +49,7 @@ public void compareNullArgument() { public void compareToNonCompareable() { when(mock.forObject(leq(5))).thenReturn(""); - assertThat(mock.forObject(NOT_A_COMPARABLE)).isNull();// a default value must be returned + assertThat(mock.forObject(NOT_A_COMPARABLE)).isNull(); // a default value must be returned } /** @@ -61,7 +59,7 @@ public void compareToNonCompareable() { public void compareToNull() { when(mock.forInteger(leq((Integer) null))).thenReturn(""); - assertThat(mock.forInteger(null)).isNull();// a default value must be returned + assertThat(mock.forInteger(null)).isNull(); // a default value must be returned } /** @@ -71,7 +69,7 @@ public void compareToNull() { public void compareToStringVsInt() { when(mock.forObject(startsWith("Hello"))).thenReturn(""); - assertThat(mock.forObject(123)).isNull();// a default value must be returned + assertThat(mock.forObject(123)).isNull(); // a default value must be returned } @Test @@ -98,7 +96,6 @@ public boolean matches(Date arg) { public boolean matches(Integer arg, Void v) { throw new UnsupportedOperationException(); } - } when(mock.forObject(argThat(new TestMatcher()))).thenReturn("x"); @@ -132,5 +129,4 @@ public boolean matches(T argument) { assertThat(mock.forObject(123)).isNull(); } - } diff --git a/src/test/java/org/mockitousage/bugs/ConcurrentModificationExceptionOnMultiThreadedVerificationTest.java b/src/test/java/org/mockitousage/bugs/ConcurrentModificationExceptionOnMultiThreadedVerificationTest.java index ffc08ad8e7..46cbb9587a 100644 --- a/src/test/java/org/mockitousage/bugs/ConcurrentModificationExceptionOnMultiThreadedVerificationTest.java +++ b/src/test/java/org/mockitousage/bugs/ConcurrentModificationExceptionOnMultiThreadedVerificationTest.java @@ -39,7 +39,8 @@ public void setUp() { @Test public void shouldSuccessfullyVerifyConcurrentInvocationsWithTimeout() throws Exception { - int potentialOverhead = 1000; // Leave 1000ms extra before timing out as leeway for test overheads + int potentialOverhead = + 1000; // Leave 1000ms extra before timing out as leeway for test overheads int expectedMaxTestLength = TIMES * INTERVAL_MILLIS + potentialOverhead; reset(target); @@ -49,13 +50,11 @@ public void shouldSuccessfullyVerifyConcurrentInvocationsWithTimeout() throws Ex verifyNoMoreInteractions(target); } - private void startInvocations() throws InterruptedException, - ExecutionException { + private void startInvocations() throws InterruptedException, ExecutionException { - for(int i=0; i { @@ -75,11 +74,9 @@ public Object call() throws Exception { System.err.println("finished" + seq); return seq; } - } public interface ITarget { String targetMethod(String arg); } - } diff --git a/src/test/java/org/mockitousage/bugs/ConfusedSignatureTest.java b/src/test/java/org/mockitousage/bugs/ConfusedSignatureTest.java index 8d79b54a47..99c638c953 100644 --- a/src/test/java/org/mockitousage/bugs/ConfusedSignatureTest.java +++ b/src/test/java/org/mockitousage/bugs/ConfusedSignatureTest.java @@ -13,7 +13,8 @@ public class ConfusedSignatureTest { @Test - public void should_mock_method_which_has_generic_return_type_in_superclass_and_concrete_one_in_interface() { + public void + should_mock_method_which_has_generic_return_type_in_superclass_and_concrete_one_in_interface() { Sub mock = mock(Sub.class); // The following line resulted in // org.mockito.exceptions.misusing.MissingMethodInvocationException: @@ -31,12 +32,12 @@ public Super(T value) { this.value = value; } - public T getFoo() { return value; } + public T getFoo() { + return value; + } } - public class Sub - extends Super - implements iInterface { + public class Sub extends Super implements iInterface { public Sub(String s) { super(s); diff --git a/src/test/java/org/mockitousage/bugs/CovariantOverrideTest.java b/src/test/java/org/mockitousage/bugs/CovariantOverrideTest.java index 919ec77ec3..91d24867a1 100644 --- a/src/test/java/org/mockitousage/bugs/CovariantOverrideTest.java +++ b/src/test/java/org/mockitousage/bugs/CovariantOverrideTest.java @@ -10,7 +10,7 @@ import org.junit.Test; import org.mockitoutil.TestBase; -//see issue 101 +// see issue 101 public class CovariantOverrideTest extends TestBase { public interface ReturnsObject { diff --git a/src/test/java/org/mockitousage/bugs/DiamondInheritanceIsConfusingMockitoTest.java b/src/test/java/org/mockitousage/bugs/DiamondInheritanceIsConfusingMockitoTest.java index 4861dd54dd..e678594b82 100644 --- a/src/test/java/org/mockitousage/bugs/DiamondInheritanceIsConfusingMockitoTest.java +++ b/src/test/java/org/mockitousage/bugs/DiamondInheritanceIsConfusingMockitoTest.java @@ -31,12 +31,12 @@ public Super(T value) { this.value = value; } - public T getFoo() { return value; } + public T getFoo() { + return value; + } } - public class Sub - extends Super - implements iInterface { + public class Sub extends Super implements iInterface { public Sub(String s) { super(s); diff --git a/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java b/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java index a11cae7a67..e22505a133 100644 --- a/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java +++ b/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java @@ -42,14 +42,15 @@ public Exception fillInStackTrace() { } } - //issue 866 + // issue 866 @Test public void avoids_NPE() { when(mock.simpleMethod()).thenThrow(new NullStackTraceException()); try { mock.simpleMethod(); fail(); - } catch(NullStackTraceException e) {} + } catch (NullStackTraceException e) { + } } @Test @@ -58,6 +59,7 @@ public void uses_return_value_from_fillInStackTrace() { try { mock.simpleMethod(); fail(); - } catch(SomeException e) {} + } catch (SomeException e) { + } } } diff --git a/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java b/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java index 5cc91afe6a..6553b975c8 100644 --- a/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java +++ b/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java @@ -27,7 +27,6 @@ private static class FieldCharsetHolder { } private static class ConstructorCharsetHolder { - public ConstructorCharsetHolder(Charset charset) { - } + public ConstructorCharsetHolder(Charset charset) {} } } diff --git a/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java b/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java index 1caecec217..8f7a18e036 100644 --- a/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java +++ b/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java @@ -20,13 +20,13 @@ */ public class GenericsMockitoAnnotationsTest { - @Mock - private TestCollectionSourceProvider testCollectionSourceProvider; + @Mock private TestCollectionSourceProvider testCollectionSourceProvider; @Ignore @Test public void should_not_throw_class_cast_exception() { - given(testCollectionSourceProvider.getCollection(new ArrayList())).willReturn(new ArrayList()); + given(testCollectionSourceProvider.getCollection(new ArrayList())) + .willReturn(new ArrayList()); } static class TestCollectionSourceProvider { diff --git a/src/test/java/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java b/src/test/java/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java index d23919ec43..fed37f92b4 100644 --- a/src/test/java/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java +++ b/src/test/java/org/mockitousage/bugs/InheritedGenericsPolimorphicCallTest.java @@ -20,7 +20,7 @@ import org.mockitoutil.TestBase; @SuppressWarnings("unchecked") -//see issue 200 +// see issue 200 public class InheritedGenericsPolimorphicCallTest extends TestBase { protected interface MyIterable extends Iterable { @@ -51,24 +51,29 @@ public void shouldVerificationWorks() { @Test public void shouldWorkExactlyAsJavaProxyWould() { - //given + // given final List methods = new LinkedList(); - InvocationHandler handler = new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - methods.add(method); - return null; - }}; + InvocationHandler handler = + new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + methods.add(method); + return null; + } + }; - iterable = (MyIterable) Proxy.newProxyInstance( - this.getClass().getClassLoader(), - new Class[] { MyIterable.class }, - handler); + iterable = + (MyIterable) + Proxy.newProxyInstance( + this.getClass().getClassLoader(), + new Class[] {MyIterable.class}, + handler); - //when + // when iterable.iterator(); ((Iterable) iterable).iterator(); - //then + // then assertEquals(2, methods.size()); assertEquals(methods.get(0), methods.get(1)); } diff --git a/src/test/java/org/mockitousage/bugs/ListenersLostOnResetMockTest.java b/src/test/java/org/mockitousage/bugs/ListenersLostOnResetMockTest.java index a464d442ec..c9b2bcd187 100644 --- a/src/test/java/org/mockitousage/bugs/ListenersLostOnResetMockTest.java +++ b/src/test/java/org/mockitousage/bugs/ListenersLostOnResetMockTest.java @@ -4,7 +4,6 @@ */ package org.mockitousage.bugs; - import static org.mockito.Mockito.*; import java.util.List; diff --git a/src/test/java/org/mockitousage/bugs/MockitoRunnerBreaksWhenNoTestMethodsTest.java b/src/test/java/org/mockitousage/bugs/MockitoRunnerBreaksWhenNoTestMethodsTest.java index 2202a6cb4a..312984c764 100644 --- a/src/test/java/org/mockitousage/bugs/MockitoRunnerBreaksWhenNoTestMethodsTest.java +++ b/src/test/java/org/mockitousage/bugs/MockitoRunnerBreaksWhenNoTestMethodsTest.java @@ -20,14 +20,13 @@ import org.mockito.junit.MockitoJUnitRunner; import org.mockitoutil.TestBase; - // @Ignore("for demo only. this test cannot be enabled as it fails :)") public class MockitoRunnerBreaksWhenNoTestMethodsTest extends TestBase { @Test public void ensure_the_test_runner_breaks() throws Exception { JUnitCore runner = new JUnitCore(); -// runner.addListener(new TextListener(System.out)); + // runner.addListener(new TextListener(System.out)); runner.addListener(new TextListener(DevNull.out)); Result result = runner.run(TestClassWithoutTestMethod.class); @@ -39,17 +38,22 @@ public void ensure_the_test_runner_breaks() throws Exception { @RunWith(MockitoJUnitRunner.class) static class TestClassWithoutTestMethod { // package visibility is important - public void notATestMethod() { } + public void notATestMethod() {} } public static final class DevNull { - public final static PrintStream out = new PrintStream(new OutputStream() { - public void close() {} - public void flush() {} - public void write(byte[] b) {} - public void write(byte[] b, int off, int len) {} - public void write(int b) {} - - } ); + public static final PrintStream out = + new PrintStream( + new OutputStream() { + public void close() {} + + public void flush() {} + + public void write(byte[] b) {} + + public void write(byte[] b, int off, int len) {} + + public void write(int b) {} + }); } } diff --git a/src/test/java/org/mockitousage/bugs/MockitoStubbedCallInAnswerTest.java b/src/test/java/org/mockitousage/bugs/MockitoStubbedCallInAnswerTest.java index f133f4ee4f..1cf92688f0 100644 --- a/src/test/java/org/mockitousage/bugs/MockitoStubbedCallInAnswerTest.java +++ b/src/test/java/org/mockitousage/bugs/MockitoStubbedCallInAnswerTest.java @@ -23,81 +23,92 @@ public class MockitoStubbedCallInAnswerTest extends TestBase { @Test public void stubbing_the_right_mock() throws Exception { - //stubbing on different mock should not be altered + // stubbing on different mock should not be altered when(bar.doInt()).thenReturn(0); - when(foo.doInt()).thenAnswer(new Answer() { - @Override - public Integer answer(InvocationOnMock invocation) throws Throwable { - return bar.doInt(); - } - }); + when(foo.doInt()) + .thenAnswer( + new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return bar.doInt(); + } + }); assertEquals(0, foo.doInt()); assertEquals(0, bar.doInt()); - //when we override the stubbing + // when we override the stubbing when(foo.doInt()).thenReturn(1); - //we expect it to be reflected: + // we expect it to be reflected: assertEquals(1, foo.doInt()); - //but the stubbing on a different mock should not be altered: + // but the stubbing on a different mock should not be altered: assertEquals(0, bar.doInt()); } @Test public void return_type_validation() throws Exception { - when(foo.doString()).thenAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - //invoking a method on a different mock, with different return type - return String.valueOf(bar.doInt()); - } - }); + when(foo.doString()) + .thenAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + // invoking a method on a different mock, with different return type + return String.valueOf(bar.doInt()); + } + }); assertEquals("0", foo.doString()); - //we can override stubbing without misleading return type validation errors: + // we can override stubbing without misleading return type validation errors: when(foo.doString()).thenReturn(""); assertEquals("", foo.doString()); } @Test public void prevents_stack_overflow() throws Exception { - when(foo.doInt()).thenAnswer(new Answer() { - public Integer answer(InvocationOnMock invocation) throws Throwable { - return bar.doInt(); - } - }); + when(foo.doInt()) + .thenAnswer( + new Answer() { + public Integer answer(InvocationOnMock invocation) throws Throwable { + return bar.doInt(); + } + }); assertEquals(0, foo.doInt()); - when(foo.doInt()).thenAnswer(new Answer() { - public Integer answer(InvocationOnMock invocation) throws Throwable { - return bar.doInt() + 1; - } - }); + when(foo.doInt()) + .thenAnswer( + new Answer() { + public Integer answer(InvocationOnMock invocation) throws Throwable { + return bar.doInt() + 1; + } + }); - //calling below used to cause SO error + // calling below used to cause SO error assertEquals(1, foo.doInt()); } @Test public void overriding_stubbing() throws Exception { when(bar.doInt()).thenReturn(10); - when(foo.doInt()).thenAnswer(new Answer() { - public Integer answer(InvocationOnMock invocation) throws Throwable { - return bar.doInt() + 1; - } - }); + when(foo.doInt()) + .thenAnswer( + new Answer() { + public Integer answer(InvocationOnMock invocation) throws Throwable { + return bar.doInt() + 1; + } + }); assertEquals(11, foo.doInt()); - //when we override the stubbing with a different one + // when we override the stubbing with a different one when(foo.doInt()).thenReturn(100); - //we expect it to be reflected: + // we expect it to be reflected: assertEquals(100, foo.doInt()); } interface Foo { String doString(); + int doInt(); } diff --git a/src/test/java/org/mockitousage/bugs/MultipleInOrdersTest.java b/src/test/java/org/mockitousage/bugs/MultipleInOrdersTest.java index f213ce129e..65472ff903 100644 --- a/src/test/java/org/mockitousage/bugs/MultipleInOrdersTest.java +++ b/src/test/java/org/mockitousage/bugs/MultipleInOrdersTest.java @@ -17,8 +17,8 @@ public class MultipleInOrdersTest { @Test - public void inOrderTest(){ - List list= mock(List.class); + public void inOrderTest() { + List list = mock(List.class); list.add("a"); list.add("x"); diff --git a/src/test/java/org/mockitousage/bugs/MultithreadedStubbingHalfManualTest.java b/src/test/java/org/mockitousage/bugs/MultithreadedStubbingHalfManualTest.java index 36db7a707b..30a8eae8e7 100644 --- a/src/test/java/org/mockitousage/bugs/MultithreadedStubbingHalfManualTest.java +++ b/src/test/java/org/mockitousage/bugs/MultithreadedStubbingHalfManualTest.java @@ -67,9 +67,9 @@ public void run() { } @Test - //this problem shows at 4 out of 5 executions - //it is not strictly a bug because Mockito does not support simultanous stubbing (see FAQ) - //however I decided to synchronize some calls in order to make the exceptions nicer + // this problem shows at 4 out of 5 executions + // it is not strictly a bug because Mockito does not support simultanous stubbing (see FAQ) + // however I decided to synchronize some calls in order to make the exceptions nicer public void tryToRevealTheProblem() { ToMock toMock = mock(ToMock.class); for (int i = 0; i < 100; i++) { @@ -77,8 +77,8 @@ public void tryToRevealTheProblem() { // Repeated mocking when(toMock.getValue(i)).thenReturn(j); - //TODO make it also showing errors for doReturn() -// doReturn(j).when(toMock).getValue(i); + // TODO make it also showing errors for doReturn() + // doReturn(j).when(toMock).getValue(i); while (true) { try { @@ -91,7 +91,7 @@ public void tryToRevealTheProblem() { } try { - Thread.sleep(10 / ((i % 10) + 1)); //NOPMD + Thread.sleep(10 / ((i % 10) + 1)); // NOPMD } catch (InterruptedException e) { } } diff --git a/src/test/java/org/mockitousage/bugs/NPEOnAnyClassMatcherAutounboxTest.java b/src/test/java/org/mockitousage/bugs/NPEOnAnyClassMatcherAutounboxTest.java index 7b7b4ac347..daa61c7a9c 100644 --- a/src/test/java/org/mockitousage/bugs/NPEOnAnyClassMatcherAutounboxTest.java +++ b/src/test/java/org/mockitousage/bugs/NPEOnAnyClassMatcherAutounboxTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import org.mockitoutil.TestBase; -//see issue 221 +// see issue 221 public class NPEOnAnyClassMatcherAutounboxTest extends TestBase { interface Foo { diff --git a/src/test/java/org/mockitousage/bugs/NPEWhenMockingThrowablesTest.java b/src/test/java/org/mockitousage/bugs/NPEWhenMockingThrowablesTest.java index 7da0967426..a266efd471 100644 --- a/src/test/java/org/mockitousage/bugs/NPEWhenMockingThrowablesTest.java +++ b/src/test/java/org/mockitousage/bugs/NPEWhenMockingThrowablesTest.java @@ -21,13 +21,14 @@ class DummyException extends RuntimeException { private static final long serialVersionUID = 1L; } - //issue 70 + // issue 70 @Test public void shouldNotThrowNPE() { when(mock.simpleMethod()).thenThrow(mock2); try { mock.simpleMethod(); fail(); - } catch(DummyException e) {} + } catch (DummyException e) { + } } } diff --git a/src/test/java/org/mockitousage/bugs/ShouldMocksCompareToBeConsistentWithEqualsTest.java b/src/test/java/org/mockitousage/bugs/ShouldMocksCompareToBeConsistentWithEqualsTest.java index dafaf393cd..a695be9ce8 100644 --- a/src/test/java/org/mockitousage/bugs/ShouldMocksCompareToBeConsistentWithEqualsTest.java +++ b/src/test/java/org/mockitousage/bugs/ShouldMocksCompareToBeConsistentWithEqualsTest.java @@ -14,59 +14,59 @@ import org.junit.Test; import org.mockitoutil.TestBase; -//see issue 184 +// see issue 184 public class ShouldMocksCompareToBeConsistentWithEqualsTest extends TestBase { @Test public void should_compare_to_be_consistent_with_equals() { - //given - Date today = mock(Date.class); + // given + Date today = mock(Date.class); Date tomorrow = mock(Date.class); - //when + // when Set set = new TreeSet(); set.add(today); set.add(tomorrow); - //then + // then assertEquals(2, set.size()); } @Test public void should_compare_to_be_consistent_with_equals_when_comparing_the_same_reference() { - //given - Date today = mock(Date.class); + // given + Date today = mock(Date.class); - //when + // when Set set = new TreeSet(); set.add(today); set.add(today); - //then + // then assertEquals(1, set.size()); } @Test public void should_allow_stubbing_and_verifying_compare_to() { - //given - Date mock = mock(Date.class); + // given + Date mock = mock(Date.class); when(mock.compareTo(any(Date.class))).thenReturn(10); - //when + // when mock.compareTo(new Date()); - //then + // then assertEquals(10, mock.compareTo(new Date())); verify(mock, atLeastOnce()).compareTo(any(Date.class)); } @Test public void should_reset_not_remove_default_stubbing() { - //given - Date mock = mock(Date.class); + // given + Date mock = mock(Date.class); reset(mock); - //then + // then assertEquals(1, mock.compareTo(new Date())); } } diff --git a/src/test/java/org/mockitousage/bugs/ShouldNotDeadlockAnswerExecutionTest.java b/src/test/java/org/mockitousage/bugs/ShouldNotDeadlockAnswerExecutionTest.java index 7141333697..e1c8dbdab6 100644 --- a/src/test/java/org/mockitousage/bugs/ShouldNotDeadlockAnswerExecutionTest.java +++ b/src/test/java/org/mockitousage/bugs/ShouldNotDeadlockAnswerExecutionTest.java @@ -16,7 +16,7 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -//see bug 190 +// see bug 190 public class ShouldNotDeadlockAnswerExecutionTest { @Test @@ -91,7 +91,6 @@ public String answer(InvocationOnMock invocation) throws Throwable { return null; } - } static class ServiceRunner implements Runnable { @@ -105,13 +104,10 @@ public ServiceRunner(Service service) { public void run() { service.verySlowMethod(); } - } interface Service { String verySlowMethod(); - } - } diff --git a/src/test/java/org/mockitousage/bugs/ShouldOnlyModeAllowCapturingArgumentsTest.java b/src/test/java/org/mockitousage/bugs/ShouldOnlyModeAllowCapturingArgumentsTest.java index 6793cbaccd..7da4f7ed38 100644 --- a/src/test/java/org/mockitousage/bugs/ShouldOnlyModeAllowCapturingArgumentsTest.java +++ b/src/test/java/org/mockitousage/bugs/ShouldOnlyModeAllowCapturingArgumentsTest.java @@ -14,21 +14,21 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//bug 197 +// bug 197 public class ShouldOnlyModeAllowCapturingArgumentsTest extends TestBase { @Mock IMethods mock; @Test public void shouldAllowCapturingArguments() { - //given + // given mock.simpleMethod("o"); ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); - //when + // when verify(mock, only()).simpleMethod(arg.capture()); - //then + // then assertEquals("o", arg.getValue()); } } diff --git a/src/test/java/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java b/src/test/java/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java index ac7a494162..353b405469 100644 --- a/src/test/java/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java +++ b/src/test/java/org/mockitousage/bugs/SpyShouldHaveNiceNameTest.java @@ -15,20 +15,20 @@ import org.mockito.Spy; import org.mockitoutil.TestBase; -//see issue 216 +// see issue 216 public class SpyShouldHaveNiceNameTest extends TestBase { @Spy List veryCoolSpy = new LinkedList(); @Test public void shouldPrintNiceName() { - //when + // when veryCoolSpy.add(1); try { verify(veryCoolSpy).add(2); fail(); - } catch(AssertionError e) { + } catch (AssertionError e) { Assertions.assertThat(e.getMessage()).contains("veryCoolSpy"); } } diff --git a/src/test/java/org/mockitousage/bugs/StubbingMocksThatAreConfiguredToReturnMocksTest.java b/src/test/java/org/mockitousage/bugs/StubbingMocksThatAreConfiguredToReturnMocksTest.java index ef3fe6c340..19043e4e8f 100644 --- a/src/test/java/org/mockitousage/bugs/StubbingMocksThatAreConfiguredToReturnMocksTest.java +++ b/src/test/java/org/mockitousage/bugs/StubbingMocksThatAreConfiguredToReturnMocksTest.java @@ -10,7 +10,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//issue 151 +// issue 151 public class StubbingMocksThatAreConfiguredToReturnMocksTest extends TestBase { @Test diff --git a/src/test/java/org/mockitousage/bugs/VerifyingWithAnExtraCallToADifferentMockTest.java b/src/test/java/org/mockitousage/bugs/VerifyingWithAnExtraCallToADifferentMockTest.java index dfd2b7cd34..eb64989f68 100644 --- a/src/test/java/org/mockitousage/bugs/VerifyingWithAnExtraCallToADifferentMockTest.java +++ b/src/test/java/org/mockitousage/bugs/VerifyingWithAnExtraCallToADifferentMockTest.java @@ -13,7 +13,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//see bug 138 +// see bug 138 public class VerifyingWithAnExtraCallToADifferentMockTest extends TestBase { @Mock IMethods mock; @@ -21,17 +21,18 @@ public class VerifyingWithAnExtraCallToADifferentMockTest extends TestBase { @Test public void shouldAllowVerifyingWhenOtherMockCallIsInTheSameLine() { - //given + // given when(mock.otherMethod()).thenReturn("foo"); - //when + // when mockTwo.simpleMethod("foo"); - //then + // then verify(mockTwo).simpleMethod(mock.otherMethod()); try { verify(mockTwo, never()).simpleMethod(mock.otherMethod()); fail(); - } catch (NeverWantedButInvoked e) {} + } catch (NeverWantedButInvoked e) { + } } } diff --git a/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java b/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java index 9cf59599c0..54de41089a 100644 --- a/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java +++ b/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java @@ -16,8 +16,7 @@ public class ConstructorInvokingMethodShouldNotRaiseExceptionTest { public static class WithDumbMethod { - @Spy - HasConstructorInvokingMethod hasConstructorInvokingMethod; + @Spy HasConstructorInvokingMethod hasConstructorInvokingMethod; @Test public void should_be_able_to_create_spy() throws Exception { @@ -25,15 +24,16 @@ public void should_be_able_to_create_spy() throws Exception { } private static class HasConstructorInvokingMethod { - public HasConstructorInvokingMethod() { someMethod(); } + public HasConstructorInvokingMethod() { + someMethod(); + } - void someMethod() { } + void someMethod() {} } } public static class UsingMethodObjectReferenceResult { - @Spy - HasConstructorInvokingMethod hasConstructorInvokingMethod; + @Spy HasConstructorInvokingMethod hasConstructorInvokingMethod; @Test public void should_be_able_to_create_spy() throws Exception { @@ -42,17 +42,19 @@ public void should_be_able_to_create_spy() throws Exception { private static class HasConstructorInvokingMethod { private final boolean doesIt; + public HasConstructorInvokingMethod() { doesIt = someMethod().contains("yup"); } - String someMethod() { return "tada!"; } + String someMethod() { + return "tada!"; + } } } public static class UsingMethodPrimitiveResult { - @Spy - HasConstructorInvokingMethod hasConstructorInvokingMethod; + @Spy HasConstructorInvokingMethod hasConstructorInvokingMethod; @Test public void should_be_able_to_create_spy() throws Exception { @@ -61,11 +63,14 @@ public void should_be_able_to_create_spy() throws Exception { private static class HasConstructorInvokingMethod { private final boolean doesIt; + public HasConstructorInvokingMethod() { doesIt = someMethod(); } - boolean someMethod() { return new Random().nextBoolean(); } + boolean someMethod() { + return new Random().nextBoolean(); + } } } } diff --git a/src/test/java/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java b/src/test/java/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java index 5a5e43d4d4..93c77e4733 100644 --- a/src/test/java/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java +++ b/src/test/java/org/mockitousage/bugs/creation/PublicMethodInParentWithNonPublicTypeInSignatureTest.java @@ -4,7 +4,6 @@ */ package org.mockitousage.bugs.creation; - import org.junit.Test; import org.mockito.Mockito; import org.mockitousage.bugs.creation.api.PublicClass; diff --git a/src/test/java/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java b/src/test/java/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java index 5ba878b047..fab68e3385 100644 --- a/src/test/java/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java +++ b/src/test/java/org/mockitousage/bugs/creation/ShouldAllowInlineMockCreationTest.java @@ -15,7 +15,7 @@ import org.mockito.Mock; import org.mockitoutil.TestBase; -//see issue 191 +// see issue 191 public class ShouldAllowInlineMockCreationTest extends TestBase { @Mock List list; diff --git a/src/test/java/org/mockitousage/bugs/creation/api/PublicClass.java b/src/test/java/org/mockitousage/bugs/creation/api/PublicClass.java index 834ef86c0a..048208c627 100644 --- a/src/test/java/org/mockitousage/bugs/creation/api/PublicClass.java +++ b/src/test/java/org/mockitousage/bugs/creation/api/PublicClass.java @@ -6,5 +6,4 @@ import org.mockitousage.bugs.creation.otherpackage.PublicParentClass; -public class PublicClass extends PublicParentClass { -} +public class PublicClass extends PublicParentClass {} diff --git a/src/test/java/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java b/src/test/java/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java index df7f79a3dc..3de5f2cf51 100644 --- a/src/test/java/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java +++ b/src/test/java/org/mockitousage/bugs/creation/otherpackage/PublicParentClass.java @@ -5,6 +5,7 @@ package org.mockitousage.bugs.creation.otherpackage; public class PublicParentClass { - public void method_with_non_public_argument(PackageLocalArg arg) { } - static class PackageLocalArg { } + public void method_with_non_public_argument(PackageLocalArg arg) {} + + static class PackageLocalArg {} } diff --git a/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenericNestedAsRawTypeTest.java b/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenericNestedAsRawTypeTest.java index bd633a54f6..ac9029cdc4 100644 --- a/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenericNestedAsRawTypeTest.java +++ b/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubFailingWhenGenericNestedAsRawTypeTest.java @@ -10,21 +10,21 @@ public class DeepStubFailingWhenGenericNestedAsRawTypeTest { - interface MyClass1 { - MC2 getNested(); - } + interface MyClass1 { + MC2 getNested(); + } - interface MyClass2 { - MC3 getNested(); - } + interface MyClass2 { + MC3 getNested(); + } - interface MyClass3 { - String returnSomething(); - } + interface MyClass3 { + String returnSomething(); + } - @Test - public void discoverDeepMockingOfGenerics() { - MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS); - when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); - } + @Test + public void discoverDeepMockingOfGenerics() { + MyClass1 myMock1 = mock(MyClass1.class, RETURNS_DEEP_STUBS); + when(myMock1.getNested().getNested().returnSomething()).thenReturn("Hello World."); + } } diff --git a/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java b/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java index a2dc0db17b..7f61dc68a5 100644 --- a/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java +++ b/src/test/java/org/mockitousage/bugs/deepstubs/DeepStubsWronglyReportsSerializationProblemsTest.java @@ -16,13 +16,15 @@ public class DeepStubsWronglyReportsSerializationProblemsTest { @Test - public void should_not_raise_a_mockito_exception_about_serialization_when_accessing_deep_stub() { - NotSerializableShouldBeMocked the_deep_stub = mock(ToBeDeepStubbed.class, RETURNS_DEEP_STUBS).getSomething(); + public void + should_not_raise_a_mockito_exception_about_serialization_when_accessing_deep_stub() { + NotSerializableShouldBeMocked the_deep_stub = + mock(ToBeDeepStubbed.class, RETURNS_DEEP_STUBS).getSomething(); assertThat(the_deep_stub).isNotNull(); } public static class ToBeDeepStubbed { - public ToBeDeepStubbed() { } + public ToBeDeepStubbed() {} public NotSerializableShouldBeMocked getSomething() { return null; @@ -30,7 +32,6 @@ public NotSerializableShouldBeMocked getSomething() { } public static class NotSerializableShouldBeMocked { - NotSerializableShouldBeMocked(String mandatory_param) { } + NotSerializableShouldBeMocked(String mandatory_param) {} } - } diff --git a/src/test/java/org/mockitousage/bugs/injection/ChildWithSameParentFieldInjectionTest.java b/src/test/java/org/mockitousage/bugs/injection/ChildWithSameParentFieldInjectionTest.java index c58ebb4975..8570db1790 100644 --- a/src/test/java/org/mockitousage/bugs/injection/ChildWithSameParentFieldInjectionTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/ChildWithSameParentFieldInjectionTest.java @@ -15,11 +15,9 @@ // issue 289 @RunWith(MockitoJUnitRunner.class) public class ChildWithSameParentFieldInjectionTest { - @InjectMocks - private System system; + @InjectMocks private System system; - @Mock - private SomeService someService; + @Mock private SomeService someService; @Test public void parent_field_is_not_null() { @@ -48,7 +46,6 @@ public void doSomething() { } public static class SomeService { - public void doSomething() { - } + public void doSomething() {} } } diff --git a/src/test/java/org/mockitousage/bugs/injection/InjectMocksShouldTryPropertySettersFirstBeforeFieldAccessTest.java b/src/test/java/org/mockitousage/bugs/injection/InjectMocksShouldTryPropertySettersFirstBeforeFieldAccessTest.java index bf3c797278..0869f581bb 100644 --- a/src/test/java/org/mockitousage/bugs/injection/InjectMocksShouldTryPropertySettersFirstBeforeFieldAccessTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/InjectMocksShouldTryPropertySettersFirstBeforeFieldAccessTest.java @@ -44,5 +44,4 @@ public void setPropertySetterAccess(List propertySetterAccess) { propertySetterUsed = true; } } - } diff --git a/src/test/java/org/mockitousage/bugs/injection/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java b/src/test/java/org/mockitousage/bugs/injection/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java index 1ad4eb44cb..5a8b41571b 100644 --- a/src/test/java/org/mockitousage/bugs/injection/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest.java @@ -22,7 +22,10 @@ public class InjectionByTypeShouldFirstLookForExactTypeThenAncestorTest { @Mock private Bean mockedBean; @InjectMocks private Service illegalInjectionExample = new Service(); - @InjectMocks private ServiceWithReversedOrder reversedOrderService = new ServiceWithReversedOrder(); + + @InjectMocks + private ServiceWithReversedOrder reversedOrderService = new ServiceWithReversedOrder(); + @InjectMocks private WithNullObjectField withNullObjectField = new WithNullObjectField(); @Test @@ -63,7 +66,7 @@ public static class ServiceWithReversedOrder { public final Object mockShouldNotGoInHere = REFERENCE; } - class WithNullObjectField{ + class WithNullObjectField { Bean injectMePlease; Object keepMeNull = null; } diff --git a/src/test/java/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java b/src/test/java/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java index 434abe1d03..3023e32f2b 100644 --- a/src/test/java/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java @@ -4,7 +4,6 @@ */ package org.mockitousage.bugs.injection; - import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertSame; @@ -24,8 +23,12 @@ public class Issue353InjectionMightNotHappenInCertainConfigurationTest { @InjectMocks FooService fooService; @Test - public void when_identical_types_and_the_correct_mock_name_is_greater_than_the_non_matching_name_then_injection_occurs_only_on_the_named_one() { - assertThat("stringString_that_matches_field".compareTo("mockStringInteger_was_not_injected")).isGreaterThanOrEqualTo(1); + public void + when_identical_types_and_the_correct_mock_name_is_greater_than_the_non_matching_name_then_injection_occurs_only_on_the_named_one() { + assertThat( + "stringString_that_matches_field" + .compareTo("mockStringInteger_was_not_injected")) + .isGreaterThanOrEqualTo(1); assertSame(stringString_that_matches_field, fooService.stringString_that_matches_field); assertSame(mockStringInteger_was_not_injected, fooService.stringInteger_field); @@ -35,5 +38,4 @@ public static class FooService { Map stringInteger_field = new HashMap(); Map stringString_that_matches_field = new HashMap(); } - } diff --git a/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java b/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java index ec56b7e9a7..cf22301ffc 100644 --- a/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java @@ -28,7 +28,7 @@ public void injectMocksShouldInjectMocksFromTestSuperClasses() { } @Ignore - public static abstract class BaseTest { + public abstract static class BaseTest { @Mock protected DaoA daoFromParent; } @@ -59,13 +59,11 @@ public void businessMethod() { } } - public static class DaoA { - public void doQuery() { } + public void doQuery() {} } public static class DaoB { - public void doQuery() { } + public void doQuery() {} } - } diff --git a/src/test/java/org/mockitousage/bugs/injection/ShouldNotTryToInjectInFinalOrStaticFieldsTest.java b/src/test/java/org/mockitousage/bugs/injection/ShouldNotTryToInjectInFinalOrStaticFieldsTest.java index 1da31290da..c98103d996 100644 --- a/src/test/java/org/mockitousage/bugs/injection/ShouldNotTryToInjectInFinalOrStaticFieldsTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/ShouldNotTryToInjectInFinalOrStaticFieldsTest.java @@ -30,12 +30,10 @@ public static class ExampleService { @InjectMocks private ExampleService exampleService = new ExampleService(); @Test - public void dont_fail_with_CONSTANTS() throws Exception { - } + public void dont_fail_with_CONSTANTS() throws Exception {} @Test public void dont_inject_in_final() { assertNotSame(unrelatedSet, exampleService.aSet); } - } diff --git a/src/test/java/org/mockitousage/bugs/varargs/VarargsAndAnyObjectPicksUpExtraInvocationsTest.java b/src/test/java/org/mockitousage/bugs/varargs/VarargsAndAnyObjectPicksUpExtraInvocationsTest.java index 387cc65989..c9112fad8f 100644 --- a/src/test/java/org/mockitousage/bugs/varargs/VarargsAndAnyObjectPicksUpExtraInvocationsTest.java +++ b/src/test/java/org/mockitousage/bugs/varargs/VarargsAndAnyObjectPicksUpExtraInvocationsTest.java @@ -17,36 +17,35 @@ public interface TableBuilder { void newRow(String trAttributes, String... cells); } - @Mock - TableBuilder table; + @Mock TableBuilder table; @Test public void shouldVerifyCorrectlyWithAnyVarargs() { - //when + // when table.newRow("qux", "foo", "bar", "baz"); table.newRow("abc", "def"); - //then + // then verify(table, times(2)).newRow(anyString(), (String[]) anyVararg()); } @Test public void shouldVerifyCorrectlyNumberOfInvocationsUsingAnyVarargAndEqualArgument() { - //when + // when table.newRow("x", "foo", "bar", "baz"); table.newRow("x", "def"); - //then + // then verify(table, times(2)).newRow(eq("x"), (String[]) anyVararg()); } @Test public void shouldVerifyCorrectlyNumberOfInvocationsWithVarargs() { - //when + // when table.newRow("qux", "foo", "bar", "baz"); table.newRow("abc", "def"); - //then + // then verify(table).newRow(anyString(), eq("foo"), anyString(), anyString()); verify(table).newRow(anyString(), anyString()); } diff --git a/src/test/java/org/mockitousage/bugs/varargs/VarargsErrorWhenCallingRealMethodTest.java b/src/test/java/org/mockitousage/bugs/varargs/VarargsErrorWhenCallingRealMethodTest.java index bc11f92273..22382211a8 100644 --- a/src/test/java/org/mockitousage/bugs/varargs/VarargsErrorWhenCallingRealMethodTest.java +++ b/src/test/java/org/mockitousage/bugs/varargs/VarargsErrorWhenCallingRealMethodTest.java @@ -13,7 +13,7 @@ public class VarargsErrorWhenCallingRealMethodTest extends TestBase { class Foo { - int blah(String a, String b, Object ... c) { + int blah(String a, String b, Object... c) { return 1; } } diff --git a/src/test/java/org/mockitousage/bugs/varargs/VarargsNotPlayingWithAnyObjectTest.java b/src/test/java/org/mockitousage/bugs/varargs/VarargsNotPlayingWithAnyObjectTest.java index 123e2e3fa1..a77782b1d0 100644 --- a/src/test/java/org/mockitousage/bugs/varargs/VarargsNotPlayingWithAnyObjectTest.java +++ b/src/test/java/org/mockitousage/bugs/varargs/VarargsNotPlayingWithAnyObjectTest.java @@ -17,7 +17,7 @@ import org.mockito.Mock; import org.mockitoutil.TestBase; -//see issue 62 +// see issue 62 public class VarargsNotPlayingWithAnyObjectTest extends TestBase { interface VarargMethod { diff --git a/src/test/java/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java b/src/test/java/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java index 4c029f9332..7d9c95061f 100644 --- a/src/test/java/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java +++ b/src/test/java/org/mockitousage/configuration/ClassCacheVersusClassReloadingTest.java @@ -4,7 +4,6 @@ */ package org.mockitousage.configuration; - import static org.mockito.Mockito.mock; import java.util.concurrent.Callable; @@ -16,38 +15,51 @@ public class ClassCacheVersusClassReloadingTest { // TODO refactor to use ClassLoaders - private SimplePerRealmReloadingClassLoader testMethodClassLoaderRealm = new SimplePerRealmReloadingClassLoader(reloadMockito()); + private SimplePerRealmReloadingClassLoader testMethodClassLoaderRealm = + new SimplePerRealmReloadingClassLoader(reloadMockito()); @Test - public void should_not_throw_ClassCastException_when_objenesis_cache_disabled() throws Exception { + public void should_not_throw_ClassCastException_when_objenesis_cache_disabled() + throws Exception { prepareMockitoAndDisableObjenesisCache(); - doInNewChildRealm(testMethodClassLoaderRealm, "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking"); - doInNewChildRealm(testMethodClassLoaderRealm, "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking"); + doInNewChildRealm( + testMethodClassLoaderRealm, + "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking"); + doInNewChildRealm( + testMethodClassLoaderRealm, + "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking"); } public static class DoTheMocking implements Callable { public Object call() throws Exception { - Class clazz = this.getClass().getClassLoader().loadClass("org.mockitousage.configuration.ClassToBeMocked"); + Class clazz = + this.getClass() + .getClassLoader() + .loadClass("org.mockitousage.configuration.ClassToBeMocked"); return mock(clazz); } } - private static void doInNewChildRealm(ClassLoader parentRealm, String callableCalledInClassLoaderRealm) throws Exception { - new SimplePerRealmReloadingClassLoader(parentRealm, reloadScope()).doInRealm(callableCalledInClassLoaderRealm); + private static void doInNewChildRealm( + ClassLoader parentRealm, String callableCalledInClassLoaderRealm) throws Exception { + new SimplePerRealmReloadingClassLoader(parentRealm, reloadScope()) + .doInRealm(callableCalledInClassLoaderRealm); } private static SimplePerRealmReloadingClassLoader.ReloadClassPredicate reloadScope() { return new SimplePerRealmReloadingClassLoader.ReloadClassPredicate() { public boolean acceptReloadOf(String qualifiedName) { - return "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking".equals(qualifiedName) - || "org.mockitousage.configuration.ClassToBeMocked".equals(qualifiedName); + return "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$DoTheMocking" + .equals(qualifiedName) + || "org.mockitousage.configuration.ClassToBeMocked".equals(qualifiedName); } }; } private void prepareMockitoAndDisableObjenesisCache() throws Exception { - testMethodClassLoaderRealm.doInRealm("org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$PrepareMockito"); + testMethodClassLoaderRealm.doInRealm( + "org.mockitousage.configuration.ClassCacheVersusClassReloadingTest$PrepareMockito"); } public static class PrepareMockito implements Callable { @@ -61,9 +73,9 @@ public Boolean call() throws Exception { private static SimplePerRealmReloadingClassLoader.ReloadClassPredicate reloadMockito() { return new SimplePerRealmReloadingClassLoader.ReloadClassPredicate() { public boolean acceptReloadOf(String qualifiedName) { - return (!qualifiedName.contains("net.bytebuddy") && qualifiedName.contains("org.mockito")); + return (!qualifiedName.contains("net.bytebuddy") + && qualifiedName.contains("org.mockito")); } }; } - } diff --git a/src/test/java/org/mockitousage/configuration/ClassToBeMocked.java b/src/test/java/org/mockitousage/configuration/ClassToBeMocked.java index adc863d6ee..fbb852d894 100644 --- a/src/test/java/org/mockitousage/configuration/ClassToBeMocked.java +++ b/src/test/java/org/mockitousage/configuration/ClassToBeMocked.java @@ -7,4 +7,4 @@ /** * Some class to mock that is created via Class.forClass */ -public class ClassToBeMocked { } +public class ClassToBeMocked {} diff --git a/src/test/java/org/mockitousage/configuration/CustomizedAnnotationForSmartMockTest.java b/src/test/java/org/mockitousage/configuration/CustomizedAnnotationForSmartMockTest.java index bc161321f3..b487063c26 100644 --- a/src/test/java/org/mockitousage/configuration/CustomizedAnnotationForSmartMockTest.java +++ b/src/test/java/org/mockitousage/configuration/CustomizedAnnotationForSmartMockTest.java @@ -23,7 +23,6 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; - /** * @see MockitoConfiguration#getAnnotationEngine() for the custom smartmock injection engine */ @@ -33,22 +32,29 @@ public class CustomizedAnnotationForSmartMockTest extends TestBase { @Test public void shouldUseCustomAnnotation() { - assertEquals("SmartMock should return empty String by default", "", smartMock.simpleMethod(1)); + assertEquals( + "SmartMock should return empty String by default", "", smartMock.simpleMethod(1)); verify(smartMock).simpleMethod(1); } - @Target({FIELD }) + @Target({FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface SmartMock {} public static class CustomInjectingAnnotationEngine extends InjectingAnnotationEngine { @Override - protected void onInjection(Object testClassInstance, Class clazz, Set mockDependentFields, Set mocks) { + protected void onInjection( + Object testClassInstance, + Class clazz, + Set mockDependentFields, + Set mocks) { for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(SmartMock.class)) { field.setAccessible(true); try { - field.set(Modifier.isStatic(field.getModifiers()) ? null : testClassInstance, Mockito.mock(field.getType(), Mockito.RETURNS_SMART_NULLS)); + field.set( + Modifier.isStatic(field.getModifiers()) ? null : testClassInstance, + Mockito.mock(field.getType(), Mockito.RETURNS_SMART_NULLS)); } catch (Exception exception) { throw new AssertionError(exception.getMessage()); } diff --git a/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java b/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java index 5816be1e3d..a70b5b25cc 100644 --- a/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java +++ b/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java @@ -24,35 +24,46 @@ public class CreatingMocksWithConstructorTest extends TestBase { - static abstract class AbstractMessage { + abstract static class AbstractMessage { private final String message; + AbstractMessage() { this.message = "hey!"; } + AbstractMessage(String message) { this.message = message; } + AbstractMessage(int i) { this.message = String.valueOf(i); } + String getMessage() { return message; } } static class Message extends AbstractMessage {} + class InnerClass extends AbstractMessage {} @Test public void can_create_mock_with_constructor() { - Message mock = mock(Message.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); - //the message is a part of state of the mocked type that gets initialized in constructor + Message mock = + mock( + Message.class, + withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); + // the message is a part of state of the mocked type that gets initialized in constructor assertEquals("hey!", mock.getMessage()); } @Test public void can_mock_abstract_classes() { - AbstractMessage mock = mock(AbstractMessage.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); + AbstractMessage mock = + mock( + AbstractMessage.class, + withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); assertEquals("hey!", mock.getMessage()); } @@ -64,46 +75,72 @@ public void can_spy_abstract_classes() { @Test public void can_spy_abstract_classes_with_constructor_args() { - AbstractMessage mock = mock(AbstractMessage.class, withSettings().useConstructor("hello!").defaultAnswer(CALLS_REAL_METHODS)); + AbstractMessage mock = + mock( + AbstractMessage.class, + withSettings().useConstructor("hello!").defaultAnswer(CALLS_REAL_METHODS)); assertEquals("hello!", mock.getMessage()); } @Test public void can_spy_abstract_classes_with_constructor_primitive_args() { - AbstractMessage mock = mock(AbstractMessage.class, withSettings().useConstructor(7).defaultAnswer(CALLS_REAL_METHODS)); + AbstractMessage mock = + mock( + AbstractMessage.class, + withSettings().useConstructor(7).defaultAnswer(CALLS_REAL_METHODS)); assertEquals("7", mock.getMessage()); } @Test public void can_spy_abstract_classes_with_constructor_array_of_nulls() { - AbstractMessage mock = mock(AbstractMessage.class, withSettings().useConstructor(new Object[]{null}).defaultAnswer(CALLS_REAL_METHODS)); + AbstractMessage mock = + mock( + AbstractMessage.class, + withSettings() + .useConstructor(new Object[] {null}) + .defaultAnswer(CALLS_REAL_METHODS)); assertNull(mock.getMessage()); } @Test public void can_spy_abstract_classes_with_casted_null() { - AbstractMessage mock = mock(AbstractMessage.class, withSettings().useConstructor((String) null).defaultAnswer(CALLS_REAL_METHODS)); + AbstractMessage mock = + mock( + AbstractMessage.class, + withSettings() + .useConstructor((String) null) + .defaultAnswer(CALLS_REAL_METHODS)); assertNull(mock.getMessage()); } @Test public void can_spy_abstract_classes_with_null_varargs() { try { - mock(AbstractMessage.class, withSettings().useConstructor(null).defaultAnswer(CALLS_REAL_METHODS)); + mock( + AbstractMessage.class, + withSettings().useConstructor(null).defaultAnswer(CALLS_REAL_METHODS)); fail(); } catch (IllegalArgumentException e) { - assertThat(e).hasMessageContaining("constructorArgs should not be null. " + - "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)"); + assertThat(e) + .hasMessageContaining( + "constructorArgs should not be null. " + + "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)"); } } @Test public void can_mock_inner_classes() { - InnerClass mock = mock(InnerClass.class, withSettings().useConstructor().outerInstance(this).defaultAnswer(CALLS_REAL_METHODS)); + InnerClass mock = + mock( + InnerClass.class, + withSettings() + .useConstructor() + .outerInstance(this) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("hey!", mock.getMessage()); } - public static class ThrowingConstructorClass{ + public static class ThrowingConstructorClass { public ThrowingConstructorClass() { throw new RuntimeException(); } @@ -112,11 +149,15 @@ public ThrowingConstructorClass() { @Test public void explains_constructor_exceptions() { try { - mock(ThrowingConstructorClass.class, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); + mock( + ThrowingConstructorClass.class, + withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); fail(); } catch (MockitoException e) { assertThat(e).hasRootCauseInstanceOf(RuntimeException.class); - assertThat(e.getCause()).hasMessageContaining("Please ensure the target class has a 0-arg constructor and executes cleanly."); + assertThat(e.getCause()) + .hasMessageContaining( + "Please ensure the target class has a 0-arg constructor and executes cleanly."); } } @@ -127,29 +168,35 @@ static class HasConstructor { @Test public void exception_message_when_constructor_not_found() { try { - //when + // when spy(HasConstructor.class); - //then + // then fail(); } catch (MockitoException e) { assertThat(e).hasMessage("Unable to create mock instance of type 'HasConstructor'"); - assertThat(e.getCause()).hasMessageContaining("Please ensure that the target class has a 0-arg constructor."); + assertThat(e.getCause()) + .hasMessageContaining( + "Please ensure that the target class has a 0-arg constructor."); } } static class Base {} + static class ExtendsBase extends Base {} + static class ExtendsExtendsBase extends ExtendsBase {} static class UsesBase { public UsesBase(Base b) { constructorUsed = "Base"; } + public UsesBase(ExtendsBase b) { constructorUsed = "ExtendsBase"; } private String constructorUsed = null; + String getConstructorUsed() { return constructorUsed; } @@ -157,19 +204,34 @@ String getConstructorUsed() { @Test public void can_mock_unambigous_constructor_with_inheritance_base_class_exact_match() { - UsesBase u = mock(UsesBase.class, withSettings().useConstructor(new Base()).defaultAnswer(CALLS_REAL_METHODS)); + UsesBase u = + mock( + UsesBase.class, + withSettings() + .useConstructor(new Base()) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("Base", u.getConstructorUsed()); } @Test public void can_mock_unambigous_constructor_with_inheritance_extending_class_exact_match() { - UsesBase u = mock(UsesBase.class, withSettings().useConstructor(new ExtendsBase()).defaultAnswer(CALLS_REAL_METHODS)); + UsesBase u = + mock( + UsesBase.class, + withSettings() + .useConstructor(new ExtendsBase()) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("ExtendsBase", u.getConstructorUsed()); } @Test public void can_mock_unambigous_constructor_with_inheritance_non_exact_match() { - UsesBase u = mock(UsesBase.class, withSettings().useConstructor(new ExtendsExtendsBase()).defaultAnswer(CALLS_REAL_METHODS)); + UsesBase u = + mock( + UsesBase.class, + withSettings() + .useConstructor(new ExtendsExtendsBase()) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("ExtendsBase", u.getConstructorUsed()); } @@ -177,14 +239,17 @@ static class UsesTwoBases { public UsesTwoBases(Base b1, Base b2) { constructorUsed = "Base,Base"; } + public UsesTwoBases(ExtendsBase b1, Base b2) { constructorUsed = "ExtendsBase,Base"; } + public UsesTwoBases(Base b1, ExtendsBase b2) { constructorUsed = "Base,ExtendsBase"; } private String constructorUsed = null; + String getConstructorUsed() { return constructorUsed; } @@ -193,67 +258,93 @@ String getConstructorUsed() { @Test public void can_mock_unambigous_constructor_with_inheritance_multiple_base_class_exact_match() { UsesTwoBases u = - mock(UsesTwoBases.class, withSettings().useConstructor(new Base(), new Base()).defaultAnswer(CALLS_REAL_METHODS)); + mock( + UsesTwoBases.class, + withSettings() + .useConstructor(new Base(), new Base()) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("Base,Base", u.getConstructorUsed()); } @Test - public void can_mock_unambigous_constructor_with_inheritance_first_extending_class_exact_match() { + public void + can_mock_unambigous_constructor_with_inheritance_first_extending_class_exact_match() { UsesTwoBases u = - mock(UsesTwoBases.class, withSettings().useConstructor(new ExtendsBase(), new Base()).defaultAnswer(CALLS_REAL_METHODS)); + mock( + UsesTwoBases.class, + withSettings() + .useConstructor(new ExtendsBase(), new Base()) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("ExtendsBase,Base", u.getConstructorUsed()); } @Test - public void can_mock_unambigous_constructor_with_inheritance_second_extending_class_exact_match() { + public void + can_mock_unambigous_constructor_with_inheritance_second_extending_class_exact_match() { UsesTwoBases u = - mock(UsesTwoBases.class, withSettings().useConstructor(new Base(), new ExtendsBase()).defaultAnswer(CALLS_REAL_METHODS)); + mock( + UsesTwoBases.class, + withSettings() + .useConstructor(new Base(), new ExtendsBase()) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("Base,ExtendsBase", u.getConstructorUsed()); } @Test public void fail_when_multiple_matching_constructors_with_inheritence() { try { - //when - mock(UsesTwoBases.class, withSettings().useConstructor(new ExtendsBase(), new ExtendsBase())); - //then + // when + mock( + UsesTwoBases.class, + withSettings().useConstructor(new ExtendsBase(), new ExtendsBase())); + // then fail(); } catch (MockitoException e) { - //TODO the exception message includes Mockito internals like the name of the generated class name. - //I suspect that we could make this exception message nicer. + // TODO the exception message includes Mockito internals like the name of the generated + // class name. + // I suspect that we could make this exception message nicer. assertThat(e).hasMessage("Unable to create mock instance of type 'UsesTwoBases'"); assertThat(e.getCause()) - .hasMessageContaining("Multiple constructors could be matched to arguments of types " - + "[org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase, " - + "org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase]") - .hasMessageContaining("If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.\n" + - "Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.\n" + - "See https://github.com/mockito/mockito/issues/685"); + .hasMessageContaining( + "Multiple constructors could be matched to arguments of types " + + "[org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase, " + + "org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase]") + .hasMessageContaining( + "If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.\n" + + "Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.\n" + + "See https://github.com/mockito/mockito/issues/685"); } } @Test public void mocking_inner_classes_with_wrong_outer_instance() { try { - //when - mock(InnerClass.class, withSettings().useConstructor().outerInstance(123).defaultAnswer(CALLS_REAL_METHODS)); - //then + // when + mock( + InnerClass.class, + withSettings() + .useConstructor() + .outerInstance(123) + .defaultAnswer(CALLS_REAL_METHODS)); + // then fail(); } catch (MockitoException e) { assertThat(e).hasMessage("Unable to create mock instance of type 'InnerClass'"); - //TODO it would be nice if all useful information was in the top level exception, instead of in the exception's cause - //also applies to other scenarios in this test - assertThat(e.getCause()).hasMessageContaining( - "Please ensure that the target class has a 0-arg constructor" - + " and provided outer instance is correct."); + // TODO it would be nice if all useful information was in the top level exception, + // instead of in the exception's cause + // also applies to other scenarios in this test + assertThat(e.getCause()) + .hasMessageContaining( + "Please ensure that the target class has a 0-arg constructor" + + " and provided outer instance is correct."); } } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) @Test public void mocking_interfaces_with_constructor() { - //at the moment this is allowed however we can be more strict if needed - //there is not much sense in creating a spy of an interface + // at the moment this is allowed however we can be more strict if needed + // there is not much sense in creating a spy of an interface mock(IMethods.class, withSettings().useConstructor()); spy(IMethods.class); } @@ -261,17 +352,26 @@ public void mocking_interfaces_with_constructor() { @Test public void prevents_across_jvm_serialization_with_constructor() { try { - //when - mock(AbstractMessage.class, withSettings().useConstructor().serializable(SerializableMode.ACROSS_CLASSLOADERS)); - //then + // when + mock( + AbstractMessage.class, + withSettings() + .useConstructor() + .serializable(SerializableMode.ACROSS_CLASSLOADERS)); + // then fail(); } catch (MockitoException e) { - assertEquals("Mocks instantiated with constructor cannot be combined with " + SerializableMode.ACROSS_CLASSLOADERS + " serialization mode.", e.getMessage()); + assertEquals( + "Mocks instantiated with constructor cannot be combined with " + + SerializableMode.ACROSS_CLASSLOADERS + + " serialization mode.", + e.getMessage()); } } - static abstract class AbstractThing { + abstract static class AbstractThing { abstract String name(); + String fullName() { return "abstract " + name(); } @@ -330,11 +430,13 @@ private static class AmbiguousWithPrimitive { public AmbiguousWithPrimitive(String s, int i) { data = s; } + public AmbiguousWithPrimitive(Object o, int i) { data = "just an object"; } private String data; + public String getData() { return data; } @@ -342,7 +444,12 @@ public String getData() { @Test public void can_spy_ambiguius_constructor_with_primitive() { - AmbiguousWithPrimitive mock = mock(AmbiguousWithPrimitive.class, withSettings().useConstructor("String", 7).defaultAnswer(CALLS_REAL_METHODS)); + AmbiguousWithPrimitive mock = + mock( + AmbiguousWithPrimitive.class, + withSettings() + .useConstructor("String", 7) + .defaultAnswer(CALLS_REAL_METHODS)); assertEquals("String", mock.getData()); } } diff --git a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java index 0154f4a898..89ed109e5e 100644 --- a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java +++ b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java @@ -25,8 +25,7 @@ public class BDDMockitoTest extends TestBase { - @Mock - IMethods mock; + @Mock IMethods mock; @Test public void should_stub() throws Exception { @@ -62,7 +61,8 @@ public void should_stub_with_throwable_class() throws Exception { @SuppressWarnings("unchecked") public void should_stub_with_throwable_classes() throws Exception { // unavoidable 'unchecked generic array creation' warning (from JDK7 onward) - given(mock.simpleMethod("foo")).willThrow(SomethingWasWrong.class, AnotherThingWasWrong.class); + given(mock.simpleMethod("foo")) + .willThrow(SomethingWasWrong.class, AnotherThingWasWrong.class); try { Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); @@ -73,31 +73,33 @@ public void should_stub_with_throwable_classes() throws Exception { @Test public void should_stub_with_answer() throws Exception { - given(mock.simpleMethod(anyString())).willAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgument(0); - } - }); + given(mock.simpleMethod(anyString())) + .willAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + return invocation.getArgument(0); + } + }); Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); } @Test public void should_stub_with_will_answer_alias() throws Exception { - given(mock.simpleMethod(anyString())).will(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgument(0); - } - }); + given(mock.simpleMethod(anyString())) + .will( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + return invocation.getArgument(0); + } + }); Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); } @Test public void should_stub_consecutively() throws Exception { - given(mock.simpleMethod(anyString())) - .willReturn("foo") - .willReturn("bar"); + given(mock.simpleMethod(anyString())).willReturn("foo").willReturn("bar"); Assertions.assertThat(mock.simpleMethod("whatever")).isEqualTo("foo"); Assertions.assertThat(mock.simpleMethod("whatever")).isEqualTo("bar"); @@ -105,8 +107,7 @@ public void should_stub_consecutively() throws Exception { @Test public void should_return_consecutively() throws Exception { - given(mock.objectReturningMethodNoArgs()) - .willReturn("foo", "bar", 12L, new byte[0]); + given(mock.objectReturningMethodNoArgs()).willReturn("foo", "bar", 12L, new byte[0]); Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("foo"); Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("bar"); @@ -117,8 +118,7 @@ public void should_return_consecutively() throws Exception { @Test public void should_stub_consecutively_with_call_real_method() throws Exception { MethodsImpl mock = mock(MethodsImpl.class); - willReturn("foo").willCallRealMethod() - .given(mock).simpleMethod(); + willReturn("foo").willCallRealMethod().given(mock).simpleMethod(); Assertions.assertThat(mock.simpleMethod()).isEqualTo("foo"); Assertions.assertThat(mock.simpleMethod()).isEqualTo(null); @@ -160,9 +160,7 @@ public void should_stub_void_with_exception_classes() throws Exception { @Test public void should_stub_void_consecutively() throws Exception { - willDoNothing() - .willThrow(new SomethingWasWrong()) - .given(mock).voidMethod(); + willDoNothing().willThrow(new SomethingWasWrong()).given(mock).voidMethod(); mock.voidMethod(); try { @@ -174,9 +172,7 @@ public void should_stub_void_consecutively() throws Exception { @Test public void should_stub_void_consecutively_with_exception_class() throws Exception { - willDoNothing() - .willThrow(SomethingWasWrong.class) - .given(mock).voidMethod(); + willDoNothing().willThrow(SomethingWasWrong.class).given(mock).voidMethod(); mock.voidMethod(); try { @@ -196,33 +192,36 @@ public void should_stub_using_do_return_style() throws Exception { @Test public void should_stub_using_do_answer_style() throws Exception { - willAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgument(0); - } - }) - .given(mock).simpleMethod(anyString()); + willAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + return invocation.getArgument(0); + } + }) + .given(mock) + .simpleMethod(anyString()); Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); } @Test public void should_stub_by_delegating_to_real_method() throws Exception { - //given + // given Dog dog = mock(Dog.class); - //when + // when willCallRealMethod().given(dog).bark(); - //then + // then Assertions.assertThat(dog.bark()).isEqualTo("woof"); } @Test - public void should_stub_by_delegating_to_real_method_using_typical_stubbing_syntax() throws Exception { - //given + public void should_stub_by_delegating_to_real_method_using_typical_stubbing_syntax() + throws Exception { + // given Dog dog = mock(Dog.class); - //when + // when given(dog.bark()).willCallRealMethod(); - //then + // then Assertions.assertThat(dog.bark()).isEqualTo("woof"); } @@ -372,25 +371,18 @@ public void should_pass_fluent_bdd_scenario_with_ordered_verification_for_two_mo static class Person { - void ride(Bike bike) { - } - - void drive(Car car) { - } - } - - static class Bike { + void ride(Bike bike) {} + void drive(Car car) {} } - static class Car { + static class Bike {} - } + static class Car {} static class Police { - void chase(Car car) { - } + void chase(Car car) {} } class Dog { @@ -400,11 +392,7 @@ public String bark() { } } - private class SomethingWasWrong extends RuntimeException { + private class SomethingWasWrong extends RuntimeException {} - } - - private class AnotherThingWasWrong extends RuntimeException { - - } + private class AnotherThingWasWrong extends RuntimeException {} } diff --git a/src/test/java/org/mockitousage/debugging/Foo.java b/src/test/java/org/mockitousage/debugging/Foo.java index be52a983af..6a3c747fc2 100644 --- a/src/test/java/org/mockitousage/debugging/Foo.java +++ b/src/test/java/org/mockitousage/debugging/Foo.java @@ -6,5 +6,6 @@ interface Foo { String giveMeSomeString(String param); + void doSomething(String param); } diff --git a/src/test/java/org/mockitousage/debugging/InvocationListenerCallbackTest.java b/src/test/java/org/mockitousage/debugging/InvocationListenerCallbackTest.java index d74a6f022a..be69b70920 100644 --- a/src/test/java/org/mockitousage/debugging/InvocationListenerCallbackTest.java +++ b/src/test/java/org/mockitousage/debugging/InvocationListenerCallbackTest.java @@ -24,7 +24,6 @@ import org.mockito.listeners.InvocationListener; import org.mockito.listeners.MethodInvocationReport; - /** * Ensures that custom listeners can be registered and will be called every time * a method on a mock is invoked. @@ -113,7 +112,8 @@ public void should_call_all_listener_when_mock_throws_exception() throws Excepti } } - private static Condition notifiedFor(final Object returned, final String location) { + private static Condition notifiedFor( + final Object returned, final String location) { return new Condition() { public boolean matches(RememberingListener toBeAsserted) { assertThat(toBeAsserted.returnValue).isEqualTo(returned); @@ -142,9 +142,9 @@ public void reportInvocation(MethodInvocationReport mcr) { this.invocation = mcr.getInvocation(); this.returnValue = mcr.getReturnedValue(); this.locationOfStubbing = mcr.getLocationOfStubbing(); - listenerContainer.add(this); //so that we can assert on order + listenerContainer.add(this); // so that we can assert on order } } - private static class OvenNotWorking extends RuntimeException { } + private static class OvenNotWorking extends RuntimeException {} } diff --git a/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java b/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java index 9b70410e33..41761ef7fe 100644 --- a/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java +++ b/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java @@ -17,61 +17,75 @@ public class InvocationsPrinterTest extends TestBase { @Mock IMethods mock; - @Test public void no_invocations() { - assertThat(new InvocationsPrinter().printInvocations(mock)).isEqualTo("No interactions and stubbings found for mock: mock"); + @Test + public void no_invocations() { + assertThat(new InvocationsPrinter().printInvocations(mock)) + .isEqualTo("No interactions and stubbings found for mock: mock"); } - @Test public void prints_invocations() { + @Test + public void prints_invocations() { mock.simpleMethod(100); triggerInteraction(); assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock))) - .isEqualTo(filterLineNo("[Mockito] Interactions of: mock\n" + - " 1. mock.simpleMethod(100);\n" + - " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n" + - " 2. mock.otherMethod();\n" + - " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n")); + .isEqualTo( + filterLineNo( + "[Mockito] Interactions of: mock\n" + + " 1. mock.simpleMethod(100);\n" + + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n" + + " 2. mock.otherMethod();\n" + + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n")); } - @Test public void prints_stubbings() { + @Test + public void prints_stubbings() { triggerStubbing(); assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock))) - .isEqualTo(filterLineNo("[Mockito] Unused stubbings of: mock\n" + - " 1. mock.simpleMethod(\"a\");\n" + - " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n")); + .isEqualTo( + filterLineNo( + "[Mockito] Unused stubbings of: mock\n" + + " 1. mock.simpleMethod(\"a\");\n" + + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n")); } - @Test public void prints_invocations_and_stubbings() { + @Test + public void prints_invocations_and_stubbings() { triggerStubbing(); mock.simpleMethod("a"); triggerInteraction(); assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock))) - .isEqualTo(filterLineNo("[Mockito] Interactions of: mock\n" + - " 1. mock.simpleMethod(\"a\");\n" + - " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n" + - " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n" + - " 2. mock.otherMethod();\n" + - " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n")); + .isEqualTo( + filterLineNo( + "[Mockito] Interactions of: mock\n" + + " 1. mock.simpleMethod(\"a\");\n" + + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n" + + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n" + + " 2. mock.otherMethod();\n" + + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n")); } - @Test public void prints_invocations_and_unused_stubbings() { + @Test + public void prints_invocations_and_unused_stubbings() { triggerStubbing(); mock.simpleMethod("b"); triggerInteraction(); assertThat(filterLineNo(new InvocationsPrinter().printInvocations(mock))) - .isEqualTo(filterLineNo("[Mockito] Interactions of: mock\n" + - " 1. mock.simpleMethod(\"b\");\n" + - " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n" + - " 2. mock.otherMethod();\n" + - " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n" + - "[Mockito] Unused stubbings of: mock\n" + - " 1. mock.simpleMethod(\"a\");\n" + - " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n")); + .isEqualTo( + filterLineNo( + "[Mockito] Interactions of: mock\n" + + " 1. mock.simpleMethod(\"b\");\n" + + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n" + + " 2. mock.otherMethod();\n" + + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n" + + "[Mockito] Unused stubbings of: mock\n" + + " 1. mock.simpleMethod(\"a\");\n" + + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n")); } private void triggerInteraction() { diff --git a/src/test/java/org/mockitousage/debugging/NewMockito.java b/src/test/java/org/mockitousage/debugging/NewMockito.java index e8cf2729f3..07cb625c95 100644 --- a/src/test/java/org/mockitousage/debugging/NewMockito.java +++ b/src/test/java/org/mockitousage/debugging/NewMockito.java @@ -8,7 +8,7 @@ import org.mockito.MockitoDebugger; import org.mockito.internal.debugging.MockitoDebuggerImpl; -//TODO get rid when debug() finally is out +// TODO get rid when debug() finally is out public class NewMockito extends Mockito { public static MockitoDebugger debug() { diff --git a/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java b/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java index d7ba7d643c..5a5783388a 100644 --- a/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java +++ b/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java @@ -39,16 +39,24 @@ public void should_call_listener_when_mock_return_normally_with_stubbed_answer() mock.giveMeSomeString("soda"); // then - verify(listener).onStubbingLookup(argThat(new ArgumentMatcher() { - @Override - public boolean matches(StubbingLookupEvent argument) { - assertEquals("soda", argument.getInvocation().getArgument(0)); - assertEquals("mock", argument.getMockSettings().getMockName().toString()); - assertEquals(2, argument.getAllStubbings().size()); - assertNotNull(argument.getStubbingFound()); - return true; - } - })); + verify(listener) + .onStubbingLookup( + argThat( + new ArgumentMatcher() { + @Override + public boolean matches(StubbingLookupEvent argument) { + assertEquals( + "soda", argument.getInvocation().getArgument(0)); + assertEquals( + "mock", + argument.getMockSettings() + .getMockName() + .toString()); + assertEquals(2, argument.getAllStubbings().size()); + assertNotNull(argument.getStubbingFound()); + return true; + } + })); } @Test @@ -60,16 +68,24 @@ public void should_call_listener_when_mock_return_normally_with_default_answer() mock.giveMeSomeString("soda"); // then - verify(listener).onStubbingLookup(argThat(new ArgumentMatcher() { - @Override - public boolean matches(StubbingLookupEvent argument) { - assertEquals("soda", argument.getInvocation().getArgument(0)); - assertEquals("mock", argument.getMockSettings().getMockName().toString()); - assertEquals(1, argument.getAllStubbings().size()); - assertNull(argument.getStubbingFound()); - return true; - } - })); + verify(listener) + .onStubbingLookup( + argThat( + new ArgumentMatcher() { + @Override + public boolean matches(StubbingLookupEvent argument) { + assertEquals( + "soda", argument.getInvocation().getArgument(0)); + assertEquals( + "mock", + argument.getMockSettings() + .getMockName() + .toString()); + assertEquals(1, argument.getAllStubbings().size()); + assertNull(argument.getStubbingFound()); + return true; + } + })); } @Test @@ -133,7 +149,10 @@ public void should_delete_listener() { // when mock.doSomething("1"); - mockingDetails(mock).getMockCreationSettings().getStubbingLookupListeners().remove(listener2); + mockingDetails(mock) + .getMockCreationSettings() + .getStubbingLookupListeners() + .remove(listener2); mock.doSomething("2"); // then @@ -156,28 +175,30 @@ public void should_clear_listeners() { @Test public void add_listeners_concurrently_sanity_check() throws Exception { - //given + // given final IMethods mock = mock(IMethods.class); final MockCreationSettings settings = mockingDetails(mock).getMockCreationSettings(); List runnables = new LinkedList(); for (int i = 0; i < 50; i++) { - runnables.add(new Runnable() { - public void run() { - StubbingLookupListener listener1 = mock(StubbingLookupListener.class); - StubbingLookupListener listener2 = mock(StubbingLookupListener.class); - settings.getStubbingLookupListeners().add(listener1); - settings.getStubbingLookupListeners().add(listener2); - settings.getStubbingLookupListeners().remove(listener1); - } - }); + runnables.add( + new Runnable() { + public void run() { + StubbingLookupListener listener1 = mock(StubbingLookupListener.class); + StubbingLookupListener listener2 = mock(StubbingLookupListener.class); + settings.getStubbingLookupListeners().add(listener1); + settings.getStubbingLookupListeners().add(listener2); + settings.getStubbingLookupListeners().remove(listener1); + } + }); } - //when + // when ConcurrentTesting.concurrently(runnables.toArray(new Runnable[runnables.size()])); - //then - //This assertion may be flaky. If it is let's fix it or remove the test. For now, I'm keeping the test. + // then + // This assertion may be flaky. If it is let's fix it or remove the test. For now, I'm + // keeping the test. assertEquals(50, settings.getStubbingLookupListeners().size()); } diff --git a/src/test/java/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java b/src/test/java/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java index 1c0d7a28d4..6696c12a5b 100644 --- a/src/test/java/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java +++ b/src/test/java/org/mockitousage/debugging/VerboseLoggingOfInvocationsOnMockTest.java @@ -123,8 +123,8 @@ public void shouldPrintThrowingInvocationOnMockToStdOut() { @Test public void shouldPrintRealInvocationOnSpyToStdOut() { // given - FooImpl fooSpy = mock(FooImpl.class, - withSettings().spiedInstance(new FooImpl()).verboseLogging()); + FooImpl fooSpy = + mock(FooImpl.class, withSettings().spiedInstance(new FooImpl()).verboseLogging()); doCallRealMethod().when(fooSpy).doSomething("Klipsch"); // when @@ -142,8 +142,7 @@ public void shouldPrintRealInvocationOnSpyToStdOut() { public void usage() { // given Foo foo = mock(Foo.class, withSettings().verboseLogging()); - given(foo.giveMeSomeString("Apple")).willReturn( - "earbuds"); + given(foo.giveMeSomeString("Apple")).willReturn("earbuds"); // when foo.giveMeSomeString("Shure"); @@ -160,8 +159,7 @@ private String mockName(Object mock) { } private static class UnrelatedClass { - void unrelatedMethod(String anotherStringValue) { - } + void unrelatedMethod(String anotherStringValue) {} } /** @@ -177,7 +175,6 @@ public String giveMeSomeString(String param) { return null; } - public void doSomething(String param) { - } + public void doSomething(String param) {} } } diff --git a/src/test/java/org/mockitousage/debugging/VerificationListenerCallBackTest.java b/src/test/java/org/mockitousage/debugging/VerificationListenerCallBackTest.java index b995f7a8a0..7ce75f1ece 100644 --- a/src/test/java/org/mockitousage/debugging/VerificationListenerCallBackTest.java +++ b/src/test/java/org/mockitousage/debugging/VerificationListenerCallBackTest.java @@ -33,7 +33,7 @@ public void clearListeners() { @Test public void should_call_single_listener_on_verify() throws NoSuchMethodException { - //given + // given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); @@ -41,17 +41,17 @@ public void should_call_single_listener_on_verify() throws NoSuchMethodException Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class); Foo foo = mock(Foo.class); - //when + // when VerificationMode never = never(); verify(foo, never).doSomething(""); - //then + // then assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); } @Test public void should_call_all_listeners_on_verify() throws NoSuchMethodException { - //given + // given RememberingListener listener1 = new RememberingListener(); RememberingListener2 listener2 = new RememberingListener2(); Mockito.framework().addListener(listener1).addListener(listener2); @@ -59,18 +59,18 @@ public void should_call_all_listeners_on_verify() throws NoSuchMethodException { Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class); Foo foo = mock(Foo.class); - //when + // when VerificationMode never = never(); verify(foo, never).doSomething(""); - //then + // then assertThat(listener1).is(notifiedFor(foo, never, invocationWanted)); assertThat(listener2).is(notifiedFor(foo, never, invocationWanted)); } @Test public void should_not_call_listener_when_verify_was_called_incorrectly() { - //when + // when VerificationListener listener = mock(VerificationListener.class); framework().addListener(listener); Foo foo = null; @@ -79,59 +79,59 @@ public void should_not_call_listener_when_verify_was_called_incorrectly() { verify(foo).doSomething(""); fail("Exception expected."); } catch (Exception e) { - //then + // then verify(listener, never()).onVerification(any(VerificationEvent.class)); } } @Test public void should_notify_when_verification_throws_type_error() { - //given + // given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); Foo foo = mock(Foo.class); - //when + // when try { verify(foo).doSomething(""); fail("Exception expected."); } catch (Throwable e) { - //then + // then assertThat(listener.cause).isInstanceOf(MockitoAssertionError.class); } } @Test public void should_notify_when_verification_throws_runtime_exception() { - //given + // given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); Foo foo = mock(Foo.class); - //when + // when try { verify(foo, new RuntimeExceptionVerificationMode()).doSomething(""); fail("Exception expected."); } catch (Throwable e) { - //then + // then assertThat(listener.cause).isInstanceOf(RuntimeException.class); } } @Test public void should_call_verification_listeners() { - //given + // given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); JUnitCore runner = new JUnitCore(); - //when + // when runner.run(VerificationListenerSample.class); - //then + // then assertThat(listener.mock).isNotNull(); assertThat(listener.mode).isEqualToComparingFieldByField(times(1)); } @@ -160,16 +160,16 @@ public void onVerification(VerificationEvent verificationEvent) { } } - private static class RememberingListener2 extends RememberingListener { + private static class RememberingListener2 extends RememberingListener {} - } - - private static Condition notifiedFor(final Object mock, final VerificationMode mode, final Method wantedMethod) { + private static Condition notifiedFor( + final Object mock, final VerificationMode mode, final Method wantedMethod) { return new Condition() { public boolean matches(RememberingListener listener) { assertThat(listener.mock).isEqualTo(mock); assertThat(listener.mode).isEqualTo(mode); - assertThat(listener.data.getTarget().getInvocation().getMethod()).isEqualTo(wantedMethod); + assertThat(listener.data.getTarget().getInvocation().getMethod()) + .isEqualTo(wantedMethod); return true; } diff --git a/src/test/java/org/mockitousage/examples/use/ArticleCalculator.java b/src/test/java/org/mockitousage/examples/use/ArticleCalculator.java index 826733a5d0..b3b54125c3 100644 --- a/src/test/java/org/mockitousage/examples/use/ArticleCalculator.java +++ b/src/test/java/org/mockitousage/examples/use/ArticleCalculator.java @@ -6,7 +6,10 @@ public interface ArticleCalculator { int countArticles(String newspaper); + int countArticlesInPolish(String newspaper); + int countNumberOfRelatedArticles(Article article); - int countAllArticles(String ... publications); + + int countAllArticles(String... publications); } diff --git a/src/test/java/org/mockitousage/examples/use/ArticleDatabase.java b/src/test/java/org/mockitousage/examples/use/ArticleDatabase.java index f69ede718a..f45990218a 100644 --- a/src/test/java/org/mockitousage/examples/use/ArticleDatabase.java +++ b/src/test/java/org/mockitousage/examples/use/ArticleDatabase.java @@ -8,19 +8,15 @@ public class ArticleDatabase { - public void updateNumberOfArticles(String newspaper, int articles) { - } + public void updateNumberOfArticles(String newspaper, int articles) {} - public void updateNumberOfPolishArticles(String newspaper, int polishArticles) { - } + public void updateNumberOfPolishArticles(String newspaper, int polishArticles) {} - public void updateNumberOfEnglishArticles(String newspaper, int i) { - } + public void updateNumberOfEnglishArticles(String newspaper, int i) {} public List
getArticlesFor(String string) { return null; } - public void save(Article article) { - } + public void save(Article article) {} } diff --git a/src/test/java/org/mockitousage/examples/use/ExampleTest.java b/src/test/java/org/mockitousage/examples/use/ExampleTest.java index 077a12341c..ec2f407103 100644 --- a/src/test/java/org/mockitousage/examples/use/ExampleTest.java +++ b/src/test/java/org/mockitousage/examples/use/ExampleTest.java @@ -64,7 +64,8 @@ public void managerUpdatesNumberOfRelatedArticles() { when(mockCalculator.countNumberOfRelatedArticles(articleTwo)).thenReturn(12); when(mockCalculator.countNumberOfRelatedArticles(articleThree)).thenReturn(0); - when(mockDatabase.getArticlesFor("Guardian")).thenReturn(Arrays.asList(articleOne, articleTwo, articleThree)); + when(mockDatabase.getArticlesFor("Guardian")) + .thenReturn(Arrays.asList(articleOne, articleTwo, articleThree)); articleManager.updateRelatedArticlesCounters("Guardian"); @@ -81,7 +82,8 @@ public void shouldPersistRecalculatedArticle() { when(mockCalculator.countNumberOfRelatedArticles(articleOne)).thenReturn(1); when(mockCalculator.countNumberOfRelatedArticles(articleTwo)).thenReturn(12); - when(mockDatabase.getArticlesFor("Guardian")).thenReturn(Arrays.asList(articleOne, articleTwo)); + when(mockDatabase.getArticlesFor("Guardian")) + .thenReturn(Arrays.asList(articleOne, articleTwo)); articleManager.updateRelatedArticlesCounters("Guardian"); diff --git a/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java b/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java index 48112b856f..d20bfce02a 100644 --- a/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java +++ b/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java @@ -20,42 +20,44 @@ public class LocationImplTest extends TestBase { @Test public void shouldLocationNotContainGetStackTraceMethod() { - assertThat(new LocationImpl().toString()).contains("shouldLocationNotContainGetStackTraceMethod"); + assertThat(new LocationImpl().toString()) + .contains("shouldLocationNotContainGetStackTraceMethod"); } @Test public void shouldBeSafeInCaseForSomeReasonFilteredStackTraceIsEmpty() { - //given - StackTraceFilter filterReturningEmptyArray = new StackTraceFilter() { - @Override - public StackTraceElement[] filter(StackTraceElement[] target, boolean keepTop) { - return new StackTraceElement[0]; - } - - @Override - public StackTraceElement filterFirst(Throwable target, boolean isInline) { - return null; - } - }; - - //when + // given + StackTraceFilter filterReturningEmptyArray = + new StackTraceFilter() { + @Override + public StackTraceElement[] filter(StackTraceElement[] target, boolean keepTop) { + return new StackTraceElement[0]; + } + + @Override + public StackTraceElement filterFirst(Throwable target, boolean isInline) { + return null; + } + }; + + // when String loc = new LocationImpl(filterReturningEmptyArray).toString(); - //then + // then assertEquals("-> at <>", loc); } @Test public void provides_location_class() { - //when + // when final List files = new ArrayList(); - new Runnable() { //anonymous inner class adds stress to the check + new Runnable() { // anonymous inner class adds stress to the check public void run() { files.add(new LocationImpl().getSourceFile()); } }.run(); - //then + // then assertEquals("LocationImplTest.java", files.get(0)); } } diff --git a/src/test/java/org/mockitousage/internal/junit/UnusedStubbingsFinderTest.java b/src/test/java/org/mockitousage/internal/junit/UnusedStubbingsFinderTest.java index 99a6f80359..38db2511a6 100644 --- a/src/test/java/org/mockitousage/internal/junit/UnusedStubbingsFinderTest.java +++ b/src/test/java/org/mockitousage/internal/junit/UnusedStubbingsFinderTest.java @@ -34,38 +34,38 @@ public class UnusedStubbingsFinderTest extends TestBase { @Test public void no_interactions() throws Exception { - //expect + // expect assertEquals(0, finder.getUnusedStubbings((List) asList(mock1, mock2)).size()); assertEquals(0, finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)).size()); } @Test public void no_stubbings() throws Exception { - //when + // when mock1.simpleMethod(); - //then + // then assertEquals(0, finder.getUnusedStubbings((List) asList(mock1, mock2)).size()); assertEquals(0, finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)).size()); } @Test public void no_unused_stubbings() throws Exception { - //when + // when when(mock1.simpleMethod()).thenReturn("1"); mock1.simpleMethod(); - //then + // then assertEquals(0, finder.getUnusedStubbings((List) asList(mock1, mock2)).size()); assertEquals(0, finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)).size()); } @Test public void unused_stubbings() throws Exception { - //when + // when when(mock1.simpleMethod()).thenReturn("1"); - //then + // then assertEquals(1, finder.getUnusedStubbings((List) asList(mock1, mock2)).size()); assertEquals(1, finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)).size()); } @@ -78,12 +78,13 @@ public void some_unused_stubbings() throws Exception { mock2.simpleMethod(2); - //when + // when UnusedStubbings stubbings = finder.getUnusedStubbings((List) asList(mock1, mock2)); - //then + // then assertEquals(2, stubbings.size()); - assertEquals("[mock1.simpleMethod(1); stubbed with: [Returns: 1], mock2.simpleMethod(3); stubbed with: [Returns: 3]]", + assertEquals( + "[mock1.simpleMethod(1); stubbed with: [Returns: 1], mock2.simpleMethod(3); stubbed with: [Returns: 3]]", stubbings.toString()); } @@ -95,13 +96,12 @@ public void unused_and_lenient_stubbings() throws Exception { mock1.simpleMethod(1); - //when + // when UnusedStubbings stubbings = finder.getUnusedStubbings((List) asList(mock1, mock2)); - //then + // then assertEquals(1, stubbings.size()); - assertEquals("[mock1.simpleMethod(2); stubbed with: [Returns: 2]]", - stubbings.toString()); + assertEquals("[mock1.simpleMethod(2); stubbed with: [Returns: 2]]", stubbings.toString()); } @Test @@ -109,43 +109,43 @@ public void some_unused_stubbings_by_location() throws Exception { when(mock1.simpleMethod(1)).thenReturn("1"); when(mock2.simpleMethod(2)).thenReturn("2"); when(mock2.simpleMethod(3)).thenReturn("3"); - lenient().when(mock2.differentMethod()).thenReturn("4"); //will not be included in results + lenient().when(mock2.differentMethod()).thenReturn("4"); // will not be included in results mock2.simpleMethod(2); - //when + // when Collection stubbings = finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)); - //then + // then assertEquals(2, stubbings.size()); assertEquals("[mock1.simpleMethod(1);, mock2.simpleMethod(3);]", stubbings.toString()); } @Test public void stubbing_used_by_location() throws Exception { - //when - //Emulating stubbing in the same location by putting stubbing in the same line: + // when + // Emulating stubbing in the same location by putting stubbing in the same line: when(mock1.simpleMethod(1)).thenReturn("1"); when(mock2.simpleMethod(1)).thenReturn("1"); - //End of emulation + // End of emulation mock1.simpleMethod(1); - //then technically unused stubbings exist + // then technically unused stubbings exist assertEquals(1, finder.getUnusedStubbings((List) asList(mock1, mock2)).size()); - //however if we consider stubbings in the same location as the same stubbing, all is used: + // however if we consider stubbings in the same location as the same stubbing, all is used: assertEquals(0, finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)).size()); } @Test public void deduplicates_stubbings_by_location() throws Exception { - //when - //Emulating stubbing in the same location by putting stubbing in the same line: + // when + // Emulating stubbing in the same location by putting stubbing in the same line: when(mock1.simpleMethod(1)).thenReturn("1"); when(mock2.simpleMethod(1)).thenReturn("1"); - //End of emulation + // End of emulation - //when + // when Collection stubbings = finder.getUnusedStubbingsByLocation((List) asList(mock1, mock2)); - //then + // then assertEquals(1, stubbings.size()); } } diff --git a/src/test/java/org/mockitousage/jls/JLS_15_12_2_5Test.java b/src/test/java/org/mockitousage/jls/JLS_15_12_2_5Test.java index 470f8101c4..1c3dcb5494 100644 --- a/src/test/java/org/mockitousage/jls/JLS_15_12_2_5Test.java +++ b/src/test/java/org/mockitousage/jls/JLS_15_12_2_5Test.java @@ -19,7 +19,6 @@ import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; - /** * Illustrate differences in the JLS depending on the Java version. */ @@ -46,8 +45,10 @@ public class JLS_15_12_2_5Test { public static class JLS_15_12_2_5_Java6_Java7_Test { @Before public void setUp() throws Exception { - Assume.assumeTrue(ClassFileVersion.of(JLS_15_12_2_5_Java6_Java7_Test.class).equals(JAVA_V6) - || ClassFileVersion.of(JLS_15_12_2_5_Java6_Java7_Test.class).equals(JAVA_V7)); + Assume.assumeTrue( + ClassFileVersion.of(JLS_15_12_2_5_Java6_Java7_Test.class).equals(JAVA_V6) + || ClassFileVersion.of(JLS_15_12_2_5_Java6_Java7_Test.class) + .equals(JAVA_V7)); } @Test @@ -56,10 +57,12 @@ public void with_single_arg() throws Exception { when(mock.oneArg(isNull())).thenReturn("ok"); - assertThat(mock.oneArg(null)).describedAs("Most generic method chosen for matcher " + - "(isNull generic upper bound is Object), but null applies " + - "to select most specific method") - .isEqualTo(null); + assertThat(mock.oneArg(null)) + .describedAs( + "Most generic method chosen for matcher " + + "(isNull generic upper bound is Object), but null applies " + + "to select most specific method") + .isEqualTo(null); } @Test @@ -68,7 +71,9 @@ public void with_single_arg_and_matcher_cast() throws Exception { when(mock.oneArg((String) isNull())).thenReturn("ok"); - assertThat(mock.oneArg(null)).describedAs("Most specific method enforced for matcher via cast").isEqualTo("ok"); + assertThat(mock.oneArg(null)) + .describedAs("Most specific method enforced for matcher via cast") + .isEqualTo("ok"); } @Test @@ -78,7 +83,9 @@ public void with_single_arg_and_null_Object_reference() throws Exception { when(mock.oneArg(isNull())).thenReturn("ok"); Object arg = null; - assertThat(mock.oneArg(arg)).describedAs("Most generic method chosen for matcher").isEqualTo("ok"); + assertThat(mock.oneArg(arg)) + .describedAs("Most generic method chosen for matcher") + .isEqualTo("ok"); } @Test @@ -87,10 +94,12 @@ public void with_variable_arg() throws Exception { when(mock.varargs(isNull())).thenReturn("ok"); - assertThat(mock.varargs(null)).describedAs("Most generic method chosen for matcher " + - "(isNull generic upper bound is Object), but null applies " + - "to select most specific method") - .isEqualTo(null); + assertThat(mock.varargs(null)) + .describedAs( + "Most generic method chosen for matcher " + + "(isNull generic upper bound is Object), but null applies " + + "to select most specific method") + .isEqualTo(null); } @Test @@ -99,7 +108,9 @@ public void with_variable_arg_and_matcher_String_cast() throws Exception { when(mock.varargs((String) isNull())).thenReturn("ok"); - assertThat(mock.varargs(null)).describedAs("Most specific method enforced for matcher via String cast").isEqualTo("ok"); + assertThat(mock.varargs(null)) + .describedAs("Most specific method enforced for matcher via String cast") + .isEqualTo("ok"); } @Test @@ -108,7 +119,9 @@ public void with_variable_arg_and_matcher_String_array_cast() throws Exception { when(mock.varargs((String[]) isNull())).thenReturn("ok"); - assertThat(mock.varargs(null)).describedAs("Most specific method enforced for matcher via String[] cast").isEqualTo("ok"); + assertThat(mock.varargs(null)) + .describedAs("Most specific method enforced for matcher via String[] cast") + .isEqualTo("ok"); } @Test @@ -118,7 +131,9 @@ public void with_variable_arg_and_null_Object_array() throws Exception { when(mock.varargs(isNull())).thenReturn("ok"); Object[] args = null; - assertThat(mock.varargs(args)).describedAs("isNull matcher generic upper bound is Object").isEqualTo("ok"); + assertThat(mock.varargs(args)) + .describedAs("isNull matcher generic upper bound is Object") + .isEqualTo("ok"); } @Test @@ -128,7 +143,9 @@ public void with_variable_arg_and_null_Object_arg() throws Exception { when(mock.varargs(isNull())).thenReturn("ok"); Object arg = null; - assertThat(mock.varargs(arg)).describedAs("isNull matcher generic upper bound is Object").isEqualTo("ok"); + assertThat(mock.varargs(arg)) + .describedAs("isNull matcher generic upper bound is Object") + .isEqualTo("ok"); } } @@ -181,7 +198,8 @@ public void with_variable_arg_and_null_Object_arg() throws Exception { public static class JLS_15_12_2_5_Java8_Test { @Before public void setUp() throws Exception { - Assume.assumeTrue(ClassFileVersion.of(JLS_15_12_2_5_Java8_Test.class).isAtLeast(JAVA_V8)); + Assume.assumeTrue( + ClassFileVersion.of(JLS_15_12_2_5_Java8_Test.class).isAtLeast(JAVA_V8)); } @Test @@ -190,7 +208,9 @@ public void with_single_arg() throws Exception { when(mock.oneArg(isNull())).thenReturn("ok"); - assertThat(mock.oneArg(null)).describedAs("Most specific method chosen for matcher and for null").isEqualTo("ok"); + assertThat(mock.oneArg(null)) + .describedAs("Most specific method chosen for matcher and for null") + .isEqualTo("ok"); } @Test @@ -209,7 +229,9 @@ public void with_variable_arg() throws Exception { when(mock.varargs(isNull())).thenReturn("ok"); - assertThat(mock.varargs(null)).describedAs("Most specific method chosen for matcher and for null").isEqualTo("ok"); + assertThat(mock.varargs(null)) + .describedAs("Most specific method chosen for matcher and for null") + .isEqualTo("ok"); } @Test @@ -219,7 +241,9 @@ public void with_variable_arg_and_null_Object_array() throws Exception { when(mock.varargs(isNull())).thenReturn("ok"); Object[] args = null; - assertThat(mock.varargs(args)).describedAs("Most specific method chosen for matcher").isEqualTo(null); + assertThat(mock.varargs(args)) + .describedAs("Most specific method chosen for matcher") + .isEqualTo(null); } @Test @@ -229,16 +253,19 @@ public void with_variable_arg_and_null_Object_arg() throws Exception { when(mock.varargs(isNull())).thenReturn("ok"); Object arg = null; - assertThat(mock.varargs(arg)).describedAs("Most specific method chosen for matcher").isEqualTo(null); + assertThat(mock.varargs(arg)) + .describedAs("Most specific method chosen for matcher") + .isEqualTo(null); } - } interface SingleOverload { String oneArg(Object arg); + String oneArg(String arg); + String varargs(Object... args); + String varargs(String... args); } - } diff --git a/src/test/java/org/mockitousage/junitrule/InvalidTargetMockitoJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/InvalidTargetMockitoJUnitRuleTest.java index 943361e907..b20615170f 100644 --- a/src/test/java/org/mockitousage/junitrule/InvalidTargetMockitoJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/InvalidTargetMockitoJUnitRuleTest.java @@ -15,14 +15,11 @@ public class InvalidTargetMockitoJUnitRuleTest { - @Rule - public MockitoRule mockitoJUnitRule = MockitoJUnit.rule(); + @Rule public MockitoRule mockitoJUnitRule = MockitoJUnit.rule(); - @Mock - private Injected injected; + @Mock private Injected injected; - @InjectMocks - private InjectInto injectInto; + @InjectMocks private InjectInto injectInto; @Test public void shouldInjectWithInvalidReference() throws Exception { @@ -30,7 +27,7 @@ public void shouldInjectWithInvalidReference() throws Exception { assertNotNull("Test object created", injectInto); } - public static class Injected { } + public static class Injected {} public static class InjectInto { private Injected injected; diff --git a/src/test/java/org/mockitousage/junitrule/JUnitTestRuleIntegratesWithRuleChainTest.java b/src/test/java/org/mockitousage/junitrule/JUnitTestRuleIntegratesWithRuleChainTest.java index 9038e75417..498d2bc890 100644 --- a/src/test/java/org/mockitousage/junitrule/JUnitTestRuleIntegratesWithRuleChainTest.java +++ b/src/test/java/org/mockitousage/junitrule/JUnitTestRuleIntegratesWithRuleChainTest.java @@ -26,40 +26,40 @@ public class JUnitTestRuleIntegratesWithRuleChainTest { JUnitCore runner = new JUnitCore(); - @Test public void rule_can_be_changed_to_strict() { - //when + @Test + public void rule_can_be_changed_to_strict() { + // when Result result = runner.run(StrictByDefault.class); - //then - JUnitResultAssert.assertThat(result) - .succeeds(1) - .fails(1, RuntimeException.class); + // then + JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class); } - @Test public void rule_can_be_changed_to_lenient() { - //when + @Test + public void rule_can_be_changed_to_lenient() { + // when Result result = runner.run(LenientByDefault.class); - //then - JUnitResultAssert.assertThat(result) - .isSuccessful(); + // then + JUnitResultAssert.assertThat(result).isSuccessful(); } public static class LenientByDefault { @Rule - public final RuleChain chain = RuleChain.outerRule( - MockitoJUnit.testRule(this) - ).around((base, description) -> new Statement() { - @Override - public void evaluate() throws Throwable { - assertThat(MockUtil.isMock(mock)).isTrue(); - called.set(true); - base.evaluate(); - } - }); - - @Mock - public IMethods mock; + public final RuleChain chain = + RuleChain.outerRule(MockitoJUnit.testRule(this)) + .around( + (base, description) -> + new Statement() { + @Override + public void evaluate() throws Throwable { + assertThat(MockUtil.isMock(mock)).isTrue(); + called.set(true); + base.evaluate(); + } + }); + + @Mock public IMethods mock; private AtomicBoolean called = new AtomicBoolean(false); @@ -72,19 +72,20 @@ public void creates_mocks_in_correct_rulechain_ordering() { public static class StrictByDefault { @Rule - public final RuleChain chain = RuleChain.outerRule( - MockitoJUnit.testRule(this).strictness(Strictness.STRICT_STUBS) - ).around((base, description) -> new Statement() { - @Override - public void evaluate() throws Throwable { - assertThat(MockUtil.isMock(mock)).isTrue(); - called.set(true); - base.evaluate(); - } - }); - - @Mock - public IMethods mock; + public final RuleChain chain = + RuleChain.outerRule(MockitoJUnit.testRule(this).strictness(Strictness.STRICT_STUBS)) + .around( + (base, description) -> + new Statement() { + @Override + public void evaluate() throws Throwable { + assertThat(MockUtil.isMock(mock)).isTrue(); + called.set(true); + base.evaluate(); + } + }); + + @Mock public IMethods mock; private AtomicBoolean called = new AtomicBoolean(false); @@ -94,7 +95,8 @@ public void creates_mocks_in_correct_rulechain_ordering() { assertThat(called.get()).isTrue(); } - @Test public void unused_stub() throws Throwable { + @Test + public void unused_stub() throws Throwable { when(mock.simpleMethod()).thenReturn("1"); assertThat(called.get()).isTrue(); } diff --git a/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java index 8b65a7c0f2..c72e0ce3a0 100644 --- a/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java @@ -17,25 +17,30 @@ public class LenientJUnitRuleTest { - private MockitoLogger explosiveLogger = new MockitoLogger() { - public void log(Object what) { - throw new RuntimeException("Silent rule should not write anything to the logger"); - } - }; + private MockitoLogger explosiveLogger = + new MockitoLogger() { + public void log(Object what) { + throw new RuntimeException( + "Silent rule should not write anything to the logger"); + } + }; @Mock private IMethods mock; @Rule public MockitoRule mockitoRule = new JUnitRule(explosiveLogger, Strictness.LENIENT); - @Test public void no_warning_for_unused_stubbing() throws Exception { + @Test + public void no_warning_for_unused_stubbing() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); } - @Test public void no_warning_for_stubbing_arg_mismatch() throws Exception { + @Test + public void no_warning_for_stubbing_arg_mismatch() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); } - @Test(expected = IllegalStateException.class) public void no_warning_for_stubbing_arg_mismatch_on_failure() throws Exception { + @Test(expected = IllegalStateException.class) + public void no_warning_for_stubbing_arg_mismatch_on_failure() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); throw new IllegalStateException("hey!"); diff --git a/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java index e25f011466..1c6930e2cb 100644 --- a/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java @@ -16,18 +16,14 @@ public class MockitoJUnitRuleTest { - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); // Fixes #1578: Protect against multiple execution. - @Rule - public MockitoRule mockitoRule2 = mockitoRule; + @Rule public MockitoRule mockitoRule2 = mockitoRule; - @Mock - private Injected injected; + @Mock private Injected injected; - @InjectMocks - private InjectInto injectInto; + @InjectMocks private InjectInto injectInto; @Test public void testInjectMocks() throws Exception { @@ -36,7 +32,7 @@ public void testInjectMocks() throws Exception { assertEquals("A injected into B", injected, injectInto.getInjected()); } - public static class Injected { } + public static class Injected {} public static class InjectInto { private Injected injected; diff --git a/src/test/java/org/mockitousage/junitrule/MockitoJUnitTestRuleTest.java b/src/test/java/org/mockitousage/junitrule/MockitoJUnitTestRuleTest.java index c533039a33..122b3c1972 100644 --- a/src/test/java/org/mockitousage/junitrule/MockitoJUnitTestRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/MockitoJUnitTestRuleTest.java @@ -16,18 +16,14 @@ public class MockitoJUnitTestRuleTest { - @Rule - public MockitoTestRule mockitoRule = MockitoJUnit.testRule(this); + @Rule public MockitoTestRule mockitoRule = MockitoJUnit.testRule(this); // Fixes #1578: Protect against multiple execution. - @Rule - public MockitoTestRule mockitoRule2 = mockitoRule; + @Rule public MockitoTestRule mockitoRule2 = mockitoRule; - @Mock - private Injected injected; + @Mock private Injected injected; - @InjectMocks - private InjectInto injectInto; + @InjectMocks private InjectInto injectInto; @Test public void testInjectMocks() throws Exception { @@ -36,7 +32,7 @@ public void testInjectMocks() throws Exception { assertEquals("A injected into B", injected, injectInto.getInjected()); } - public static class Injected { } + public static class Injected {} public static class InjectInto { private Injected injected; diff --git a/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitRuleTest.java index 66c9197529..b0efc2cb2e 100644 --- a/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitRuleTest.java @@ -21,36 +21,36 @@ public class MutableStrictJUnitRuleTest { JUnitCore runner = new JUnitCore(); - @Test public void rule_can_be_changed_to_strict() throws Throwable { - //when + @Test + public void rule_can_be_changed_to_strict() throws Throwable { + // when Result result = runner.run(LenientByDefault.class); - //then - JUnitResultAssert.assertThat(result) - .succeeds(1) - .fails(1, RuntimeException.class); + // then + JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class); } - @Test public void rule_can_be_changed_to_lenient() throws Throwable { - //when + @Test + public void rule_can_be_changed_to_lenient() throws Throwable { + // when Result result = runner.run(StrictByDefault.class); - //then - JUnitResultAssert.assertThat(result) - .succeeds(1) - .fails(1, RuntimeException.class); + // then + JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class); } public static class LenientByDefault { @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.LENIENT); @Mock IMethods mock; - @Test public void unused_stub() throws Throwable { + @Test + public void unused_stub() throws Throwable { when(mock.simpleMethod()).thenReturn("1"); } - @Test public void unused_stub_with_strictness() throws Throwable { - //making Mockito strict only for this test method + @Test + public void unused_stub_with_strictness() throws Throwable { + // making Mockito strict only for this test method mockito.strictness(Strictness.STRICT_STUBS); when(mock.simpleMethod()).thenReturn("1"); @@ -61,12 +61,14 @@ public static class StrictByDefault { @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @Mock IMethods mock; - @Test public void unused_stub() throws Throwable { + @Test + public void unused_stub() throws Throwable { when(mock.simpleMethod()).thenReturn("1"); } - @Test public void unused_stub_with_lenient() throws Throwable { - //making Mockito lenient only for this test method + @Test + public void unused_stub_with_lenient() throws Throwable { + // making Mockito lenient only for this test method mockito.strictness(Strictness.LENIENT); when(mock.simpleMethod()).thenReturn("1"); diff --git a/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitTestRuleTest.java b/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitTestRuleTest.java index df8cc48237..1e2faac199 100644 --- a/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitTestRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/MutableStrictJUnitTestRuleTest.java @@ -21,36 +21,38 @@ public class MutableStrictJUnitTestRuleTest { JUnitCore runner = new JUnitCore(); - @Test public void rule_can_be_changed_to_strict() throws Throwable { - //when + @Test + public void rule_can_be_changed_to_strict() throws Throwable { + // when Result result = runner.run(LenientByDefault.class); - //then - JUnitResultAssert.assertThat(result) - .succeeds(1) - .fails(1, RuntimeException.class); + // then + JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class); } - @Test public void rule_can_be_changed_to_lenient() throws Throwable { - //when + @Test + public void rule_can_be_changed_to_lenient() throws Throwable { + // when Result result = runner.run(StrictByDefault.class); - //then - JUnitResultAssert.assertThat(result) - .succeeds(1) - .fails(1, RuntimeException.class); + // then + JUnitResultAssert.assertThat(result).succeeds(1).fails(1, RuntimeException.class); } public static class LenientByDefault { - @Rule public MockitoTestRule mockito = MockitoJUnit.testRule(this).strictness(Strictness.LENIENT); + @Rule + public MockitoTestRule mockito = MockitoJUnit.testRule(this).strictness(Strictness.LENIENT); + @Mock IMethods mock; - @Test public void unused_stub() throws Throwable { + @Test + public void unused_stub() throws Throwable { when(mock.simpleMethod()).thenReturn("1"); } - @Test public void unused_stub_with_strictness() throws Throwable { - //making Mockito strict only for this test method + @Test + public void unused_stub_with_strictness() throws Throwable { + // making Mockito strict only for this test method mockito.strictness(Strictness.STRICT_STUBS); when(mock.simpleMethod()).thenReturn("1"); @@ -58,15 +60,20 @@ public static class LenientByDefault { } public static class StrictByDefault { - @Rule public MockitoTestRule mockito = MockitoJUnit.testRule(this).strictness(Strictness.STRICT_STUBS); + @Rule + public MockitoTestRule mockito = + MockitoJUnit.testRule(this).strictness(Strictness.STRICT_STUBS); + @Mock IMethods mock; - @Test public void unused_stub() throws Throwable { + @Test + public void unused_stub() throws Throwable { when(mock.simpleMethod()).thenReturn("1"); } - @Test public void unused_stub_with_lenient() throws Throwable { - //making Mockito lenient only for this test method + @Test + public void unused_stub_with_lenient() throws Throwable { + // making Mockito lenient only for this test method mockito.strictness(Strictness.LENIENT); when(mock.simpleMethod()).thenReturn("1"); diff --git a/src/test/java/org/mockitousage/junitrule/RuleTestWithFactoryMethodTest.java b/src/test/java/org/mockitousage/junitrule/RuleTestWithFactoryMethodTest.java index 8f5830bf84..e7d613080a 100644 --- a/src/test/java/org/mockitousage/junitrule/RuleTestWithFactoryMethodTest.java +++ b/src/test/java/org/mockitousage/junitrule/RuleTestWithFactoryMethodTest.java @@ -16,25 +16,20 @@ public class RuleTestWithFactoryMethodTest { - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock - private Injected injected; + @Mock private Injected injected; - @InjectMocks - private InjectInto injectInto; + @InjectMocks private InjectInto injectInto; @Test public void testInjectMocks() throws Exception { assertNotNull("Mock created", injected); assertNotNull("Object created", injectInto); assertEquals("A injected into B", injected, injectInto.getInjected()); - } - public static class Injected { - } + public static class Injected {} public static class InjectInto { diff --git a/src/test/java/org/mockitousage/junitrule/RuleTestWithParameterConstructorTest.java b/src/test/java/org/mockitousage/junitrule/RuleTestWithParameterConstructorTest.java index ed2aa036f9..be56e876b6 100644 --- a/src/test/java/org/mockitousage/junitrule/RuleTestWithParameterConstructorTest.java +++ b/src/test/java/org/mockitousage/junitrule/RuleTestWithParameterConstructorTest.java @@ -16,25 +16,20 @@ public class RuleTestWithParameterConstructorTest { - @Rule - public MockitoRule mockitoJUnitRule = MockitoJUnit.rule(); + @Rule public MockitoRule mockitoJUnitRule = MockitoJUnit.rule(); - @Mock - private Injected injected; + @Mock private Injected injected; - @InjectMocks - private InjectInto injectInto; + @InjectMocks private InjectInto injectInto; @Test public void testInjectMocks() throws Exception { assertNotNull("Mock created", injected); assertNotNull("Object created", injectInto); assertEquals("A injected into B", injected, injectInto.getInjected()); - } - public static class Injected { - } + public static class Injected {} public static class InjectInto { diff --git a/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java index 98b17915b6..6c6d1acd6c 100644 --- a/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java @@ -27,143 +27,162 @@ public class StrictJUnitRuleTest { - @Rule public SafeJUnitRule rule = new SafeJUnitRule(MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)); + @Rule + public SafeJUnitRule rule = + new SafeJUnitRule(MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)); @Mock IMethods mock; @Mock IMethods mock2; - @Test public void ok_when_no_stubbings() throws Throwable { + @Test + public void ok_when_no_stubbings() throws Throwable { mock.simpleMethod(); verify(mock).simpleMethod(); } - @Test public void ok_when_all_stubbings_used() throws Throwable { + @Test + public void ok_when_all_stubbings_used() throws Throwable { given(mock.simpleMethod(10)).willReturn("foo"); mock.simpleMethod(10); } - @Test public void ok_when_used_and_mismatched_argument() throws Throwable { + @Test + public void ok_when_used_and_mismatched_argument() throws Throwable { given(mock.simpleMethod(10)).willReturn("foo"); mock.simpleMethod(10); mock.simpleMethod(15); } - @Test public void fails_when_unused_stubbings() throws Throwable { - //expect + @Test + public void fails_when_unused_stubbings() throws Throwable { + // expect rule.expectFailure(UnnecessaryStubbingException.class); - //when + // when given(mock.simpleMethod(10)).willReturn("foo"); mock2.simpleMethod(10); } - @Test public void test_failure_trumps_unused_stubbings() throws Throwable { - //expect + @Test + public void test_failure_trumps_unused_stubbings() throws Throwable { + // expect rule.expectFailure(AssertionError.class, "x"); - //when + // when given(mock.simpleMethod(10)).willReturn("foo"); mock.otherMethod(); throw new AssertionError("x"); } - @Test public void why_do_return_syntax_is_useful() throws Throwable { - //Trade-off of Mockito strictness documented in test + @Test + public void why_do_return_syntax_is_useful() throws Throwable { + // Trade-off of Mockito strictness documented in test - //expect + // expect rule.expectFailure(PotentialStubbingProblem.class); - //when + // when when(mock.simpleMethod(10)).thenReturn("10"); ProductionCode.simpleMethod(mock, 20); } - @Test public void fails_fast_when_stubbing_invoked_with_different_argument() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - Assertions.assertThat(t).isInstanceOf(PotentialStubbingProblem.class); - assertEquals(filterLineNo("\n" + - "Strict stubbing argument mismatch. Please check:\n" + - " - this invocation of 'simpleMethod' method:\n" + - " mock.simpleMethod(15);\n" + - " -> at org.mockitousage.strictness.ProductionCode.simpleMethod(ProductionCode.java:0)\n" + - " - has following stubbing(s) with different arguments:\n" + - " 1. mock.simpleMethod(20);\n" + - " -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" + - " 2. mock.simpleMethod(30);\n" + - " -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" + - "Typically, stubbing argument mismatch indicates user mistake when writing tests.\n" + - "Mockito fails early so that you can debug potential problem easily.\n" + - "However, there are legit scenarios when this exception generates false negative signal:\n" + - " - stubbing the same method multiple times using 'given().will()' or 'when().then()' API\n" + - " Please use 'will().given()' or 'doReturn().when()' API for stubbing.\n" + - " - stubbed method is intentionally invoked with different arguments by code under test\n" + - " Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).\n" + - "For more information see javadoc for PotentialStubbingProblem class."), - filterLineNo(t.getMessage())); - } - }); - - //when stubbings in the test code: - willReturn("10").given(mock).simpleMethod(10) ; //used - willReturn("20").given(mock).simpleMethod(20) ; //unused - willReturn("30").given(mock).simpleMethod(30) ; //unused - - //then - mock.otherMethod(); //ok, different method - mock.simpleMethod(10); //ok, stubbed with this argument - - //invocation in the code under test uses different argument and should fail immediately - //this helps with debugging and is essential for Mockito strictness + @Test + public void fails_fast_when_stubbing_invoked_with_different_argument() throws Throwable { + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + Assertions.assertThat(t).isInstanceOf(PotentialStubbingProblem.class); + assertEquals( + filterLineNo( + "\n" + + "Strict stubbing argument mismatch. Please check:\n" + + " - this invocation of 'simpleMethod' method:\n" + + " mock.simpleMethod(15);\n" + + " -> at org.mockitousage.strictness.ProductionCode.simpleMethod(ProductionCode.java:0)\n" + + " - has following stubbing(s) with different arguments:\n" + + " 1. mock.simpleMethod(20);\n" + + " -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" + + " 2. mock.simpleMethod(30);\n" + + " -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.java:0)\n" + + "Typically, stubbing argument mismatch indicates user mistake when writing tests.\n" + + "Mockito fails early so that you can debug potential problem easily.\n" + + "However, there are legit scenarios when this exception generates false negative signal:\n" + + " - stubbing the same method multiple times using 'given().will()' or 'when().then()' API\n" + + " Please use 'will().given()' or 'doReturn().when()' API for stubbing.\n" + + " - stubbed method is intentionally invoked with different arguments by code under test\n" + + " Please use default or 'silent' JUnit Rule (equivalent of Strictness.LENIENT).\n" + + "For more information see javadoc for PotentialStubbingProblem class."), + filterLineNo(t.getMessage())); + } + }); + + // when stubbings in the test code: + willReturn("10").given(mock).simpleMethod(10); // used + willReturn("20").given(mock).simpleMethod(20); // unused + willReturn("30").given(mock).simpleMethod(30); // unused + + // then + mock.otherMethod(); // ok, different method + mock.simpleMethod(10); // ok, stubbed with this argument + + // invocation in the code under test uses different argument and should fail immediately + // this helps with debugging and is essential for Mockito strictness ProductionCode.simpleMethod(mock, 15); } - @Test public void verify_no_more_interactions_ignores_stubs() throws Throwable { - //when stubbing in test: + @Test + public void verify_no_more_interactions_ignores_stubs() throws Throwable { + // when stubbing in test: given(mock.simpleMethod(10)).willReturn("foo"); - //and code under test does: - mock.simpleMethod(10); //implicitly verifies the stubbing + // and code under test does: + mock.simpleMethod(10); // implicitly verifies the stubbing mock.otherMethod(); - //and in test we: + // and in test we: verify(mock).otherMethod(); verifyNoMoreInteractions(mock); } - @Test public void unused_stubs_with_multiple_mocks() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals(filterLineNo("\n" + - "Unnecessary stubbings detected.\n" + - "Clean & maintainable test code requires zero unnecessary code.\n" + - "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" + - " 1. -> at org.mockitousage.junitrule.StrictJUnitRuleTest.unused_stubs_with_multiple_mocks(StrictJUnitRuleTest.java:0)\n" + - " 2. -> at org.mockitousage.junitrule.StrictJUnitRuleTest.unused_stubs_with_multiple_mocks(StrictJUnitRuleTest.java:0)\n" + - "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class."), filterLineNo(t.getMessage())); - } - }); - - //when test has + @Test + public void unused_stubs_with_multiple_mocks() throws Throwable { + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals( + filterLineNo( + "\n" + + "Unnecessary stubbings detected.\n" + + "Clean & maintainable test code requires zero unnecessary code.\n" + + "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" + + " 1. -> at org.mockitousage.junitrule.StrictJUnitRuleTest.unused_stubs_with_multiple_mocks(StrictJUnitRuleTest.java:0)\n" + + " 2. -> at org.mockitousage.junitrule.StrictJUnitRuleTest.unused_stubs_with_multiple_mocks(StrictJUnitRuleTest.java:0)\n" + + "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class."), + filterLineNo(t.getMessage())); + } + }); + + // when test has given(mock.simpleMethod(10)).willReturn("foo"); given(mock2.simpleMethod(20)).willReturn("foo"); - given(mock.otherMethod()).willReturn("foo"); //used and should not be reported + given(mock.otherMethod()).willReturn("foo"); // used and should not be reported - //and code has + // and code has mock.otherMethod(); mock2.booleanObjectReturningMethod(); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void rule_validates_mockito_usage() throws Throwable { - //expect + @Test + public void rule_validates_mockito_usage() throws Throwable { + // expect rule.expectFailure(UnfinishedVerificationException.class); - //when test contains unfinished verification + // when test contains unfinished verification verify(mock); } } diff --git a/src/test/java/org/mockitousage/junitrule/StubbingWarningsJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/StubbingWarningsJUnitRuleTest.java index da9f4ac44c..7f77eeb59f 100644 --- a/src/test/java/org/mockitousage/junitrule/StubbingWarningsJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/StubbingWarningsJUnitRuleTest.java @@ -26,49 +26,53 @@ public class StubbingWarningsJUnitRuleTest { @Test public void no_unused_stubs_reported_on_failure() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals("x", t.getMessage()); - assertTrue(logger.getLoggedInfo().isEmpty()); - } - }); - - //when + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals("x", t.getMessage()); + assertTrue(logger.getLoggedInfo().isEmpty()); + } + }); + + // when declareStubbing(mock); throw new AssertionError("x"); } @Test public void stubbing_arg_mismatch_on_failure() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals("x", t.getMessage()); - assertEquals( - "[MockitoHint] StubbingWarningsJUnitRuleTest.stubbing_arg_mismatch_on_failure (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", - filterLineNo(logger.getLoggedInfo())); - } - }); - - //when + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals("x", t.getMessage()); + assertEquals( + "[MockitoHint] StubbingWarningsJUnitRuleTest.stubbing_arg_mismatch_on_failure (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); + } + }); + + // when declareStubbingWithArg(mock, "a"); useStubbingWithArg(mock, "b"); throw new AssertionError("x"); } - @Test public void no_stubbing_arg_mismatch_when_no_mismatch_on_fail() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals("x", t.getMessage()); - assertTrue(logger.getLoggedInfo().isEmpty()); - } - }); - - //when + @Test + public void no_stubbing_arg_mismatch_when_no_mismatch_on_fail() throws Throwable { + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals("x", t.getMessage()); + assertTrue(logger.getLoggedInfo().isEmpty()); + } + }); + + // when declareStubbingWithArg(mock, "a"); useStubbingWithArg(mock, "a"); throw new AssertionError("x"); @@ -76,37 +80,39 @@ public void doAssert(Throwable t) { @Test public void no_stubbing_warning_on_pass() throws Throwable { - //expect - rule.expectSuccess(new Runnable() { - public void run() { - assertTrue(logger.isEmpty()); - } - }); - - //when + // expect + rule.expectSuccess( + new Runnable() { + public void run() { + assertTrue(logger.isEmpty()); + } + }); + + // when declareStubbingWithArg(mock, "a"); useStubbingWithArg(mock, "a"); } @Test public void multiple_stubbing_arg_mismatch_on_failure() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals("x", t.getMessage()); - assertEquals( - "[MockitoHint] StubbingWarningsJUnitRuleTest.multiple_stubbing_arg_mismatch_on_failure (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] 2. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", - filterLineNo(logger.getLoggedInfo())); - } - }); - - //when + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals("x", t.getMessage()); + assertEquals( + "[MockitoHint] StubbingWarningsJUnitRuleTest.multiple_stubbing_arg_mismatch_on_failure (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] 2. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); + } + }); + + // when declareStubbingWithArg(mock, "a"); declareStubbingWithArg(mock, "b"); @@ -118,19 +124,20 @@ public void doAssert(Throwable t) { @Test public void reports_only_mismatching_stubs() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals("x", t.getMessage()); - assertEquals( - "[MockitoHint] StubbingWarningsJUnitRuleTest.reports_only_mismatching_stubs (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", - filterLineNo(logger.getLoggedInfo())); - } - }); - - //when + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals("x", t.getMessage()); + assertEquals( + "[MockitoHint] StubbingWarningsJUnitRuleTest.reports_only_mismatching_stubs (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.useStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); + } + }); + + // when declareStubbingWithArg(mock, "a"); // <-- used declareStubbingWithArg(mock, "b"); // <-- unused @@ -142,15 +149,16 @@ public void doAssert(Throwable t) { @Test public void no_mismatch_when_stub_was_used() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - assertEquals("x", t.getMessage()); - assertTrue(logger.getLoggedInfo().isEmpty()); - } - }); - - //when + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + assertEquals("x", t.getMessage()); + assertTrue(logger.getLoggedInfo().isEmpty()); + } + }); + + // when declareStubbingWithArg(mock, "a"); useStubbingWithArg(mock, "a"); @@ -161,35 +169,36 @@ public void doAssert(Throwable t) { @Test public void no_stubbing_arg_mismatch_on_pass() throws Throwable { - //expect - rule.expectSuccess(new Runnable() { - public void run() { - assertEquals( - "[MockitoHint] StubbingWarningsJUnitRuleTest.no_stubbing_arg_mismatch_on_pass (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", - filterLineNo(logger.getLoggedInfo())); - } - }); - - //when + // expect + rule.expectSuccess( + new Runnable() { + public void run() { + assertEquals( + "[MockitoHint] StubbingWarningsJUnitRuleTest.no_stubbing_arg_mismatch_on_pass (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbingWithArg(StubbingWarningsJUnitRuleTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); + } + }); + + // when declareStubbingWithArg(mock, "a"); useStubbingWithArg(mock, "b"); } @Test public void warns_about_unused_stubs_when_passed() throws Throwable { - //expect - rule.expectSuccess(new Runnable() { - public void run() { - assertEquals( - "[MockitoHint] StubbingWarningsJUnitRuleTest.warns_about_unused_stubs_when_passed (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbing(StubbingWarningsJUnitRuleTest.java:0)\n", - filterLineNo(logger.getLoggedInfo())); - - } - }); - - //when + // expect + rule.expectSuccess( + new Runnable() { + public void run() { + assertEquals( + "[MockitoHint] StubbingWarningsJUnitRuleTest.warns_about_unused_stubs_when_passed (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused -> at org.mockitousage.junitrule.StubbingWarningsJUnitRuleTest.declareStubbing(StubbingWarningsJUnitRuleTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); + } + }); + + // when declareStubbing(mock); } diff --git a/src/test/java/org/mockitousage/junitrule/StubbingWarningsMultiThreadingTest.java b/src/test/java/org/mockitousage/junitrule/StubbingWarningsMultiThreadingTest.java index 5f8bdc5e02..683a9e8857 100644 --- a/src/test/java/org/mockitousage/junitrule/StubbingWarningsMultiThreadingTest.java +++ b/src/test/java/org/mockitousage/junitrule/StubbingWarningsMultiThreadingTest.java @@ -25,45 +25,50 @@ public class StubbingWarningsMultiThreadingTest { @Rule public SafeJUnitRule rule = new SafeJUnitRule(new JUnitRule(logger, Strictness.WARN)); @Mock IMethods mock; - @Test public void using_stubbing_from_different_thread() throws Throwable { - //expect no warnings - rule.expectSuccess(new Runnable() { - public void run() { - assertTrue(logger.getLoggedInfo().isEmpty()); - } - }); + @Test + public void using_stubbing_from_different_thread() throws Throwable { + // expect no warnings + rule.expectSuccess( + new Runnable() { + public void run() { + assertTrue(logger.getLoggedInfo().isEmpty()); + } + }); - //when stubbing is declared + // when stubbing is declared when(mock.simpleMethod()).thenReturn("1"); - //and used from a different thread - ConcurrentTesting.inThread(new Runnable() { + // and used from a different thread + ConcurrentTesting.inThread( + new Runnable() { public void run() { mock.simpleMethod(); } }); } - @Test public void unused_stub_from_different_thread() throws Throwable { - //expect warnings - rule.expectSuccess(new Runnable() { - public void run() { - assertEquals( - "[MockitoHint] StubbingWarningsMultiThreadingTest.unused_stub_from_different_thread (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused -> at org.mockitousage.junitrule.StubbingWarningsMultiThreadingTest.unused_stub_from_different_thread(StubbingWarningsMultiThreadingTest.java:0)\n", - filterLineNo(logger.getLoggedInfo())); - } - }); + @Test + public void unused_stub_from_different_thread() throws Throwable { + // expect warnings + rule.expectSuccess( + new Runnable() { + public void run() { + assertEquals( + "[MockitoHint] StubbingWarningsMultiThreadingTest.unused_stub_from_different_thread (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused -> at org.mockitousage.junitrule.StubbingWarningsMultiThreadingTest.unused_stub_from_different_thread(StubbingWarningsMultiThreadingTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); + } + }); - //when stubbings are declared + // when stubbings are declared when(mock.simpleMethod(1)).thenReturn("1"); when(mock.simpleMethod(2)).thenReturn("2"); - //and one of the stubbings is used from a different thread - ConcurrentTesting.inThread(new Runnable() { - public void run() { - mock.simpleMethod(1); - } - }); + // and one of the stubbings is used from a different thread + ConcurrentTesting.inThread( + new Runnable() { + public void run() { + mock.simpleMethod(1); + } + }); } - } diff --git a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java index ab4def4d7c..1500bcf39e 100644 --- a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java +++ b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java @@ -72,21 +72,27 @@ public void should_collect_matching_error_from_non_matching_arguments() { methods.intArgumentMethod(6); methods.longArg(8L); - methods.forShort((short)6); + methods.forShort((short) 6); verify(methods).intArgumentMethod(8); - verify(methods).longArg(longThat(new ArgumentMatcher() { - @Override - public boolean matches(Long argument) { - throw new AssertionError("custom error message"); - } - })); - verify(methods).forShort(shortThat(new ArgumentMatcher() { - @Override - public boolean matches(Short argument) { - return false; - } - })); + verify(methods) + .longArg( + longThat( + new ArgumentMatcher() { + @Override + public boolean matches(Long argument) { + throw new AssertionError("custom error message"); + } + })); + verify(methods) + .forShort( + shortThat( + new ArgumentMatcher() { + @Override + public boolean matches(Short argument) { + return false; + } + })); try { collector.collectAndReport(); @@ -139,17 +145,19 @@ public void should_invoke_collector_rule_after_test() { Result result = runner.run(VerificationCollectorRuleInner.class); assertThat(result.getFailureCount()).as("failureCount").isEqualTo(2); - assertThat(result.getFailures().get(0).getMessage()).as("failure1").contains("1. Wanted but not invoked:"); - assertThat(result.getFailures().get(1).getMessage()).as("failure2") - .contains("1. Argument(s) are different! Wanted:") - .contains("2. Wanted but not invoked:"); + assertThat(result.getFailures().get(0).getMessage()) + .as("failure1") + .contains("1. Wanted but not invoked:"); + assertThat(result.getFailures().get(1).getMessage()) + .as("failure2") + .contains("1. Argument(s) are different! Wanted:") + .contains("2. Wanted but not invoked:"); } // This class is picked up when running a test suite using an IDE. It fails on purpose. public static class VerificationCollectorRuleInner { - @Rule - public VerificationCollector collector = MockitoJUnit.collector(); + @Rule public VerificationCollector collector = MockitoJUnit.collector(); @Test public void should_fail() { diff --git a/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java index be42213248..7236f1b9b0 100644 --- a/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java @@ -15,14 +15,15 @@ public class DeepStubbingWithJUnitRunnerTest { private final SomeClass someClass = new SomeClass(); - @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Root root; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Root root; @Test public void deep_stubs_dont_trigger_unnecessary_stubbing_exception() { - //when + // when someClass.someMethod(root); - //then unnecessary stubbing exception is not thrown + // then unnecessary stubbing exception is not thrown } public static class SomeClass { @@ -39,7 +40,5 @@ interface Foo { Bar getBar(); } - interface Bar { - - } + interface Bar {} } diff --git a/src/test/java/org/mockitousage/junitrunner/JUnit45RunnerTest.java b/src/test/java/org/mockitousage/junitrunner/JUnit45RunnerTest.java index ed5a531480..bd9b485a5a 100644 --- a/src/test/java/org/mockitousage/junitrunner/JUnit45RunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/JUnit45RunnerTest.java @@ -35,7 +35,7 @@ public void shouldInjectMocksUsingRunner() { } @Test - public void shouldFilterTestMethodsCorrectly() throws Exception{ + public void shouldFilterTestMethodsCorrectly() throws Exception { MockitoJUnitRunner runner = new MockitoJUnitRunner(this.getClass()); runner.filter(methodNameContains("shouldInitMocksUsingRunner")); diff --git a/src/test/java/org/mockitousage/junitrunner/ModellingVerboseMockitoTest.java b/src/test/java/org/mockitousage/junitrunner/ModellingVerboseMockitoTest.java index 980300e594..193a30baef 100644 --- a/src/test/java/org/mockitousage/junitrunner/ModellingVerboseMockitoTest.java +++ b/src/test/java/org/mockitousage/junitrunner/ModellingVerboseMockitoTest.java @@ -18,7 +18,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//@RunWith(ConsoleSpammingMockitoJUnitRunner.class) +// @RunWith(ConsoleSpammingMockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class) @Ignore public class ModellingVerboseMockitoTest extends TestBase { @@ -36,22 +36,23 @@ public void shouldLogUnusedStubbingWarningWhenTestFails() throws Exception { when(mock.otherMethod()).thenReturn("foo"); when(mock.booleanObjectReturningMethod()).thenReturn(false); - //TODO: stubbed with those args here -> stubbed with certain args here + // TODO: stubbed with those args here -> stubbed with certain args here String ret = mock.simpleMethod(2); assertEquals("foo", ret); - //TODO: should show message from actual failure not at the bottom but at least below 'the actual failure is ...' + // TODO: should show message from actual failure not at the bottom but at least below 'the + // actual failure is ...' } @Test public void shouldNotLogAnythingWhenNoWarnings() throws Exception { - //stub + // stub when(mock.simpleMethod()).thenReturn("foo"); - //use stub: + // use stub: mock.simpleMethod(); - //verify: + // verify: verify(mock).simpleMethod(); - //should be no warnings: + // should be no warnings: fail(); } } diff --git a/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java index 040d0d9aa1..afb375debb 100644 --- a/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java @@ -28,55 +28,54 @@ public class SilentRunnerTest extends TestBase { JUnitCore runner = new JUnitCore(); - @Test public void passing_test() { - //when - Result result = runner.run( - SomeFeature.class - ); - //then + @Test + public void passing_test() { + // when + Result result = runner.run(SomeFeature.class); + // then JUnitResultAssert.assertThat(result).isSuccessful(); } - @Test public void failing_test() { - //when - Result result = runner.run( - SomeFailingFeature.class - ); - //then + @Test + public void failing_test() { + // when + Result result = runner.run(SomeFailingFeature.class); + // then JUnitResultAssert.assertThat(result).fails(1, TooFewActualInvocations.class); } - @Test public void failing_test_in_constructor() { - //when - Result result = runner.run( - FailsInConstructor.class - ); - //then + @Test + public void failing_test_in_constructor() { + // when + Result result = runner.run(FailsInConstructor.class); + // then JUnitResultAssert.assertThat(result).fails(1, IllegalArgumentException.class); } - @Test public void validates_framework_usage() { - //when - Result result = runner.run( - UsesFrameworkIncorrectly.class - ); - //then - JUnitResultAssert.assertThat(result).fails(1, "unfinished_stubbing_test_method", UnfinishedStubbingException.class); + @Test + public void validates_framework_usage() { + // when + Result result = runner.run(UsesFrameworkIncorrectly.class); + // then + JUnitResultAssert.assertThat(result) + .fails(1, "unfinished_stubbing_test_method", UnfinishedStubbingException.class); } @Test public void ignores_unused_stubs() { JUnitCore runner = new JUnitCore(); - //when + // when Result result = runner.run(HasUnnecessaryStubs.class); - //then + // then JUnitResultAssert.assertThat(result).isSuccessful(); } @RunWith(MockitoJUnitRunner.Silent.class) public static class SomeFeature { @Mock List list; - @Test public void some_behavior() { + + @Test + public void some_behavior() { when(list.get(0)).thenReturn("0"); assertEquals("0", list.get(0)); } @@ -85,7 +84,9 @@ public static class SomeFeature { @RunWith(MockitoJUnitRunner.Silent.class) public static class SomeFailingFeature { @Mock List list; - @Test public void some_failing_behavior() { + + @Test + public void some_failing_behavior() { list.clear(); verify(list, times(2)).clear(); } @@ -98,8 +99,11 @@ public static class FailsInConstructor { throw new IllegalArgumentException("Boo!"); } } + @Mock List list; - @Test public void some_behavior() {} + + @Test + public void some_behavior() {} } @RunWith(MockitoJUnitRunner.Silent.class) @@ -107,8 +111,9 @@ public static class UsesFrameworkIncorrectly { @Mock List list; @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void unfinished_stubbing_test_method() { - when(list.get(0)); //unfinished stubbing + @Test + public void unfinished_stubbing_test_method() { + when(list.get(0)); // unfinished stubbing } } diff --git a/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java index 5b7591fb67..47ed6886e6 100644 --- a/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/StrictRunnerTest.java @@ -23,77 +23,87 @@ import org.mockitoutil.JUnitResultAssert; import org.mockitoutil.TestBase; - public class StrictRunnerTest extends TestBase { JUnitCore runner = new JUnitCore(); - @Test public void succeeds_when_all_stubs_were_used() { - //when - Result result = runner.run( - StubbingInConstructorUsed.class, - StubbingInBeforeUsed.class, - StubbingInTestUsed.class - ); - //then + @Test + public void succeeds_when_all_stubs_were_used() { + // when + Result result = + runner.run( + StubbingInConstructorUsed.class, + StubbingInBeforeUsed.class, + StubbingInTestUsed.class); + // then JUnitResultAssert.assertThat(result).isSuccessful(); } - @Test public void fails_when_stubs_were_not_used() { - Class[] tests = {StubbingInConstructorUnused.class, - StubbingInBeforeUnused.class, - StubbingInTestUnused.class}; + @Test + public void fails_when_stubs_were_not_used() { + Class[] tests = { + StubbingInConstructorUnused.class, + StubbingInBeforeUnused.class, + StubbingInTestUnused.class + }; - //when + // when Result result = runner.run(tests); - //then + // then JUnitResultAssert.assertThat(result).fails(3, UnnecessaryStubbingException.class); } - @Test public void does_not_report_unused_stubs_when_different_failure_is_present() { - //when + @Test + public void does_not_report_unused_stubs_when_different_failure_is_present() { + // when Result result = runner.run(WithUnrelatedAssertionFailure.class); - //then + // then JUnitResultAssert.assertThat(result).fails(1, MyAssertionError.class); } - @Test public void runner_can_coexist_with_rule() { - //I don't believe that this scenario is useful - //I only wish that Mockito does not break awkwardly when both: runner & rule is used + @Test + public void runner_can_coexist_with_rule() { + // I don't believe that this scenario is useful + // I only wish that Mockito does not break awkwardly when both: runner & rule is used - //when + // when Result result = runner.run(RunnerAndRule.class); - //then + // then JUnitResultAssert.assertThat(result).fails(1, UnnecessaryStubbingException.class); } - @Test public void runner_in_multi_threaded_tests() { - //when + @Test + public void runner_in_multi_threaded_tests() { + // when Result result = runner.run(StubUsedFromDifferentThread.class); - //then + // then JUnitResultAssert.assertThat(result).isSuccessful(); } @RunWith(MockitoJUnitRunner.class) public static class StubbingInConstructorUsed extends StubbingInConstructorUnused { - @Test public void test() { + @Test + public void test() { assertEquals("1", mock.simpleMethod(1)); } } - @RunWith(MockitoJUnitRunner.Strict.class) //using Strict to make sure it does the right thing + @RunWith(MockitoJUnitRunner.Strict.class) // using Strict to make sure it does the right thing public static class StubbingInConstructorUnused { IMethods mock = when(mock(IMethods.class).simpleMethod(1)).thenReturn("1").getMock(); - @Test public void dummy() {} + + @Test + public void dummy() {} } @RunWith(MockitoJUnitRunner.class) public static class StubbingInBeforeUsed extends StubbingInBeforeUnused { - @Test public void test() { + @Test + public void test() { assertEquals("1", mock.simpleMethod(1)); } } @@ -101,15 +111,20 @@ public static class StubbingInBeforeUsed extends StubbingInBeforeUnused { @RunWith(MockitoJUnitRunner.class) public static class StubbingInBeforeUnused { @Mock IMethods mock; - @Before public void before() { + + @Before + public void before() { when(mock.simpleMethod(1)).thenReturn("1"); } - @Test public void dummy() {} + + @Test + public void dummy() {} } @RunWith(MockitoJUnitRunner.class) public static class StubbingInTestUsed { - @Test public void test() { + @Test + public void test() { IMethods mock = mock(IMethods.class); when(mock.simpleMethod(1)).thenReturn("1"); assertEquals("1", mock.simpleMethod(1)); @@ -118,10 +133,11 @@ public static class StubbingInTestUsed { @RunWith(MockitoJUnitRunner.class) public static class StubbingInTestUnused { - @Test public void test() { + @Test + public void test() { IMethods mock = mock(IMethods.class); when(mock.simpleMethod(1)).thenReturn("1"); - mock.simpleMethod(2); //different arg + mock.simpleMethod(2); // different arg } } @@ -133,16 +149,19 @@ public static class WithUnrelatedAssertionFailure { IMethods mock = mock(IMethods.class); IMethods mock2 = mock(IMethods.class); - @Before public void before() { + @Before + public void before() { when(mock2.simpleMethod("unused stubbing")).thenReturn(""); } - @Test public void passing_test() { + @Test + public void passing_test() { when(mock.simpleMethod(1)).thenReturn("1"); assertEquals("1", mock.simpleMethod(1)); } - @Test public void failing_test() { + @Test + public void failing_test() { throw new MyAssertionError(); } } @@ -153,7 +172,8 @@ public static class RunnerAndRule { public @Rule MockitoRule rule = MockitoJUnit.rule(); IMethods mock = mock(IMethods.class); - @Test public void passing_test() { + @Test + public void passing_test() { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); } @@ -164,17 +184,19 @@ public static class StubUsedFromDifferentThread { IMethods mock = mock(IMethods.class); - @Test public void passing_test() throws Exception { - //stubbing is done in main thread: + @Test + public void passing_test() throws Exception { + // stubbing is done in main thread: when(mock.simpleMethod(1)).thenReturn("1"); - //stubbing is used in a different thread - //stubbing should not be reported as unused by the runner - Thread t = new Thread() { - public void run() { - mock.simpleMethod(1); - } - }; + // stubbing is used in a different thread + // stubbing should not be reported as unused by the runner + Thread t = + new Thread() { + public void run() { + mock.simpleMethod(1); + } + }; t.start(); t.join(); } diff --git a/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java index 7fc857de97..efe2f74b9d 100644 --- a/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java @@ -23,34 +23,40 @@ public class StrictStubsRunnerTest extends TestBase { JUnitCore runner = new JUnitCore(); - @Test public void detects_unnecessary_stubbings() { - //when + @Test + public void detects_unnecessary_stubbings() { + // when Result result = runner.run(UnnecessaryStubbing.class); - //then + // then JUnitResultAssert.assertThat(result) .fails(1, UnnecessaryStubbingException.class) .succeeds(2); } - @Test public void fails_fast_on_argument_mismatch() { - //when + @Test + public void fails_fast_on_argument_mismatch() { + // when Result result = runner.run(StubbingArgMismatch.class); - //then - JUnitResultAssert.assertThat(result) - .succeeds(2) - .fails(1, PotentialStubbingProblem.class); + // then + JUnitResultAssert.assertThat(result).succeeds(2).fails(1, PotentialStubbingProblem.class); } @RunWith(MockitoJUnitRunner.StrictStubs.class) public static class UnnecessaryStubbing { @Mock IMethods mock; - @Test public void unused_stubbing_1() { + + @Test + public void unused_stubbing_1() { when(mock.simpleMethod()).thenReturn(""); } - @Test public void unused_stubbing_2() { + + @Test + public void unused_stubbing_2() { when(mock.simpleMethod()).thenReturn(""); } - @Test public void correct_stubbing() { + + @Test + public void correct_stubbing() { when(mock.simpleMethod()).thenReturn(""); mock.simpleMethod(); } @@ -59,12 +65,18 @@ public static class UnnecessaryStubbing { @RunWith(MockitoJUnitRunner.StrictStubs.class) public static class StubbingArgMismatch { @Mock IMethods mock; - @Test public void passing1() {} - @Test public void passing2() { + + @Test + public void passing1() {} + + @Test + public void passing2() { when(mock.simpleMethod()).thenReturn(""); mock.simpleMethod(); } - @Test public void argument_mismatch() { + + @Test + public void argument_mismatch() { when(mock.simpleMethod(10)).thenReturn(""); ProductionCode.simpleMethod(mock, 20); } diff --git a/src/test/java/org/mockitousage/junitrunner/StubbingWarningsJUnitRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/StubbingWarningsJUnitRunnerTest.java index e878683625..05be05d5fc 100644 --- a/src/test/java/org/mockitousage/junitrunner/StubbingWarningsJUnitRunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/StubbingWarningsJUnitRunnerTest.java @@ -25,46 +25,59 @@ public class StubbingWarningsJUnitRunnerTest extends TestBase { JUnitCore runner = new JUnitCore(); SimpleMockitoLogger logger = TestableJUnitRunner.refreshedLogger(); - @Test public void no_arg_mismatch_warnings() { - //when - runner.run(PassingArgMismatch.class, FailingWithMatchingArgs.class, MismatchButStubAlreadyUsed.class); - - //then + @Test + public void no_arg_mismatch_warnings() { + // when + runner.run( + PassingArgMismatch.class, + FailingWithMatchingArgs.class, + MismatchButStubAlreadyUsed.class); + + // then assertEquals("", filterLineNo(logger.getLoggedInfo())); } - @Test public void shows_arg_mismatch_warnings_when_test_fails() { - //when + @Test + public void shows_arg_mismatch_warnings_when_test_fails() { + // when runner.run(FailingWithArgMismatch.class); - //then - assertEquals("[MockitoHint] FailingWithArgMismatch.test (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithArgMismatch.test(StubbingWarningsJUnitRunnerTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithArgMismatch.test(StubbingWarningsJUnitRunnerTest.java:0)\n", filterLineNo(logger.getLoggedInfo())); + // then + assertEquals( + "[MockitoHint] FailingWithArgMismatch.test (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithArgMismatch.test(StubbingWarningsJUnitRunnerTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithArgMismatch.test(StubbingWarningsJUnitRunnerTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); } - @Test public void shows_arg_mismatch_warnings_only_for_mismatches() { - //when + @Test + public void shows_arg_mismatch_warnings_only_for_mismatches() { + // when runner.run(FailingWithSomeStubMismatches.class); - //then - assertEquals("[MockitoHint] FailingWithSomeStubMismatches.test (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithSomeStubMismatches.test(StubbingWarningsJUnitRunnerTest.java:0)\n" + - "[MockitoHint] ...args ok? -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithSomeStubMismatches.test(StubbingWarningsJUnitRunnerTest.java:0)\n", filterLineNo(logger.getLoggedInfo())); + // then + assertEquals( + "[MockitoHint] FailingWithSomeStubMismatches.test (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused... -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithSomeStubMismatches.test(StubbingWarningsJUnitRunnerTest.java:0)\n" + + "[MockitoHint] ...args ok? -> at org.mockitousage.junitrunner.StubbingWarningsJUnitRunnerTest$FailingWithSomeStubMismatches.test(StubbingWarningsJUnitRunnerTest.java:0)\n", + filterLineNo(logger.getLoggedInfo())); } - @Test public void validates_mockito_usage() { - //when + @Test + public void validates_mockito_usage() { + // when Result result = runner.run(InvalidMockitoUsage.class); - //then + // then assertThat(result).fails(1, UnfinishedStubbingException.class); } @RunWith(TestableJUnitRunner.class) public static class PassingArgMismatch { IMethods mock = mock(IMethods.class); - @Test public void test() throws Exception { + + @Test + public void test() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); } @@ -73,7 +86,9 @@ public static class PassingArgMismatch { @RunWith(TestableJUnitRunner.class) public static class FailingWithArgMismatch { @Mock IMethods mock; - @Test public void test() throws Exception { + + @Test + public void test() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); throw new RuntimeException("x"); @@ -83,7 +98,9 @@ public static class FailingWithArgMismatch { @RunWith(TestableJUnitRunner.class) public static class FailingWithMatchingArgs { @Mock IMethods mock; - @Test public void test() throws Exception { + + @Test + public void test() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(1); throw new RuntimeException("x"); @@ -93,7 +110,9 @@ public static class FailingWithMatchingArgs { @RunWith(TestableJUnitRunner.class) public static class FailingWithSomeStubMismatches { @Mock IMethods mock; - @Test public void test() throws Exception { + + @Test + public void test() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); // <- used when(mock.simpleMethod(2)).thenReturn("2"); // <- unused @@ -107,7 +126,9 @@ public static class FailingWithSomeStubMismatches { @RunWith(TestableJUnitRunner.class) public static class MismatchButStubAlreadyUsed { @Mock IMethods mock; - @Test public void test() throws Exception { + + @Test + public void test() throws Exception { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(1); // <-- used mock.simpleMethod(2); // <-- arg mismatch, but the stub was already used @@ -119,8 +140,10 @@ public static class MismatchButStubAlreadyUsed { @RunWith(TestableJUnitRunner.class) public static class InvalidMockitoUsage { @Mock IMethods mock; + @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void test() throws Exception { + @Test + public void test() throws Exception { when(mock.simpleMethod()); // <-- unfinished stubbing } } diff --git a/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java b/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java index 09e1e70923..db804f856c 100644 --- a/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java +++ b/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java @@ -19,9 +19,10 @@ public class UnusedStubsExceptionMessageTest extends TestBase { - //Moving the code around this class is tricky and may cause the test to fail - //We're asserting on full exception message which contains line numbers - //Let's leave it for now, updating the test is cheap and if it turns out hindrance we can make the assertion smarter. + // Moving the code around this class is tricky and may cause the test to fail + // We're asserting on full exception message which contains line numbers + // Let's leave it for now, updating the test is cheap and if it turns out hindrance we can make + // the assertion smarter. @RunWith(MockitoJUnitRunner.class) public static class HasUnnecessaryStubs { IMethods mock1 = when(mock(IMethods.class).simpleMethod(1)).thenReturn("1").getMock(); @@ -43,17 +44,18 @@ public void usesStubWithDifferentArg() { @Test public void lists_all_unused_stubs_cleanly() { JUnitCore runner = new JUnitCore(); - //when + // when Result result = runner.run(HasUnnecessaryStubs.class); - //then + // then Failure failure = result.getFailures().get(0); - assertEquals("\n" + - "Unnecessary stubbings detected in test class: HasUnnecessaryStubs\n" + - "Clean & maintainable test code requires zero unnecessary code.\n" + - "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" + - " 1. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.(UnusedStubsExceptionMessageTest.java:0)\n" + - " 2. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.(UnusedStubsExceptionMessageTest.java:0)\n" + - "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.", - filterLineNo(failure.getException().getMessage())); + assertEquals( + "\n" + + "Unnecessary stubbings detected in test class: HasUnnecessaryStubs\n" + + "Clean & maintainable test code requires zero unnecessary code.\n" + + "Following stubbings are unnecessary (click to navigate to relevant line of code):\n" + + " 1. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.(UnusedStubsExceptionMessageTest.java:0)\n" + + " 2. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.(UnusedStubsExceptionMessageTest.java:0)\n" + + "Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.", + filterLineNo(failure.getException().getMessage())); } } diff --git a/src/test/java/org/mockitousage/junitrunner/VerboseMockitoRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/VerboseMockitoRunnerTest.java index 44f6407aae..d6cfd6ef02 100644 --- a/src/test/java/org/mockitousage/junitrunner/VerboseMockitoRunnerTest.java +++ b/src/test/java/org/mockitousage/junitrunner/VerboseMockitoRunnerTest.java @@ -20,9 +20,9 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//@RunWith(ConsoleSpammingMockitoJUnitRunner.class) +// @RunWith(ConsoleSpammingMockitoJUnitRunner.class) @RunWith(VerboseMockitoJUnitRunner.class) -//TODO +// TODO public class VerboseMockitoRunnerTest extends TestBase { @Mock private IMethods mock; @@ -52,15 +52,15 @@ public void testIgnored() {} public void _test() { IMethods mock = mock(IMethods.class); - //some stubbing + // some stubbing when(mock.simpleMethod(1)).thenReturn("foo"); when(mock.otherMethod()).thenReturn("foo"); when(mock.booleanObjectReturningMethod()).thenReturn(false); - //stub called with different args: + // stub called with different args: String ret = mock.simpleMethod(2); - //assertion fails due to stub called with different args + // assertion fails due to stub called with different args assertEquals("foo", ret); } } @@ -72,9 +72,9 @@ public void cleanStackTraces() { @Test @Ignore public void shouldContainWarnings() throws Exception { - //when + // when Result result = new JUnitCore().run(new ContainsWarnings()); - //then + // then assertEquals(1, result.getFailures().size()); Throwable exception = result.getFailures().get(0).getException(); assertTrue(exception instanceof ExceptionIncludingMockitoWarnings); diff --git a/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java b/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java index fc0f123c1d..b4b6e1a335 100644 --- a/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java +++ b/src/test/java/org/mockitousage/matchers/CapturingArgumentsTest.java @@ -42,7 +42,7 @@ public BulkEmailService(EmailService service) { this.service = service; } - public void email(Integer ... personId) { + public void email(Integer... personId) { for (Integer i : personId) { Person person = new Person(i); service.sendEmailTo(person); @@ -61,26 +61,26 @@ interface EmailService { @SuppressWarnings("deprecation") @Test public void should_allow_assertions_on_captured_argument() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); - //when + // when bulkEmailService.email(12); - //then + // then verify(emailService).sendEmailTo(argument.capture()); assertEquals(12, argument.getValue().getAge()); } @Test public void should_allow_assertions_on_all_captured_arguments() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); - //when + // when bulkEmailService.email(11, 12); - //then + // then verify(emailService, times(2)).sendEmailTo(argument.capture()); assertEquals(11, argument.getAllValues().get(0).getAge()); assertEquals(12, argument.getAllValues().get(1).getAge()); @@ -88,84 +88,84 @@ public void should_allow_assertions_on_all_captured_arguments() { @Test public void should_allow_assertions_on_last_argument() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); - //when + // when bulkEmailService.email(11, 12, 13); - //then + // then verify(emailService, times(3)).sendEmailTo(argument.capture()); assertEquals(13, argument.getValue().getAge()); } @Test public void should_print_captor_matcher() { - //given + // given ArgumentCaptor person = ArgumentCaptor.forClass(Person.class); try { - //when + // when verify(emailService).sendEmailTo(person.capture()); fail(); - } catch(WantedButNotInvoked e) { - //then + } catch (WantedButNotInvoked e) { + // then assertThat(e).hasMessageContaining(""); } } @Test public void should_allow_assertions_on_captured_null() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); - //when + // when emailService.sendEmailTo(null); - //then + // then verify(emailService).sendEmailTo(argument.capture()); assertEquals(null, argument.getValue()); } @Test - public void should_allow_construction_of_captor_for_parameterized_type_in_a_convenient_way() { - //the test passes if this expression compiles + public void should_allow_construction_of_captor_for_parameterized_type_in_a_convenient_way() { + // the test passes if this expression compiles @SuppressWarnings("unchecked") ArgumentCaptor> argument = ArgumentCaptor.forClass(List.class); assertNotNull(argument); } @Test - public void should_allow_construction_of_captor_for_a_more_specific_type() { - //the test passes if this expression compiles + public void should_allow_construction_of_captor_for_a_more_specific_type() { + // the test passes if this expression compiles ArgumentCaptor> argument = ArgumentCaptor.forClass(ArrayList.class); assertNotNull(argument); } @Test public void should_allow_capturing_for_stubbing() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class); when(emailService.sendEmailTo(argument.capture())).thenReturn(false); - //when + // when emailService.sendEmailTo(new Person(10)); - //then + // then assertEquals(10, argument.getValue().getAge()); } @Test public void should_capture_when_stubbing_only_when_entire_invocation_matches() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); when(mock.simpleMethod(argument.capture(), eq(2))).thenReturn("blah"); - //when + // when mock.simpleMethod("foo", 200); mock.simpleMethod("bar", 2); - //then + // then Assertions.assertThat(argument.getAllValues()).containsOnly("bar"); } @@ -175,19 +175,20 @@ public void should_say_something_smart_when_misused() { try { argument.getValue(); fail(); - } catch (MockitoException expected) { } + } catch (MockitoException expected) { + } } @Test public void should_capture_when_full_arg_list_matches() throws Exception { - //given + // given ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); - //when + // when mock.simpleMethod("foo", 1); mock.simpleMethod("bar", 2); - //then + // then verify(mock).simpleMethod(captor.capture(), eq(1)); assertEquals(1, captor.getAllValues().size()); assertEquals("foo", captor.getValue()); @@ -195,26 +196,26 @@ public void should_capture_when_full_arg_list_matches() throws Exception { @Test public void should_capture_int_by_creating_captor_with_primitive_wrapper() { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(Integer.class); - //when + // when mock.intArgumentMethod(10); - //then + // then verify(mock).intArgumentMethod(argument.capture()); assertEquals(10, (int) argument.getValue()); } @Test public void should_capture_int_by_creating_captor_with_primitive() throws Exception { - //given + // given ArgumentCaptor argument = ArgumentCaptor.forClass(int.class); - //when + // when mock.intArgumentMethod(10); - //then + // then verify(mock).intArgumentMethod(argument.capture()); assertEquals(10, (int) argument.getValue()); } @@ -234,7 +235,8 @@ public void should_capture_byte_vararg_by_creating_captor_with_primitive() throw } @Test - public void should_capture_byte_vararg_by_creating_captor_with_primitive_wrapper() throws Exception { + public void should_capture_byte_vararg_by_creating_captor_with_primitive_wrapper() + throws Exception { // given ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Byte.class); @@ -272,11 +274,13 @@ public void should_capture_all_vararg() throws Exception { // then verify(mock, times(2)).mixedVarargs(any(), argumentCaptor.capture()); - Assertions.assertThat(argumentCaptor.getAllValues()).containsExactly("a", "b", "c", "again ?!"); + Assertions.assertThat(argumentCaptor.getAllValues()) + .containsExactly("a", "b", "c", "again ?!"); } @Test - public void should_capture_one_arg_even_when_using_vararg_captor_on_nonvararg_method() throws Exception { + public void should_capture_one_arg_even_when_using_vararg_captor_on_nonvararg_method() + throws Exception { // given ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); @@ -298,7 +302,12 @@ public void captures_correctly_when_captor_used_multiple_times() throws Exceptio // then // this is only for backwards compatibility. It does not make sense in real to do so. - verify(mock).mixedVarargs(any(), argumentCaptor.capture(), argumentCaptor.capture(), argumentCaptor.capture()); + verify(mock) + .mixedVarargs( + any(), + argumentCaptor.capture(), + argumentCaptor.capture(), + argumentCaptor.capture()); Assertions.assertThat(argumentCaptor.getAllValues()).containsExactly("a", "b", "c"); } diff --git a/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java b/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java index ff6362d707..540f36a321 100644 --- a/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java +++ b/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java @@ -17,8 +17,7 @@ public class CustomMatcherDoesYieldCCETest extends TestBase { - @Mock - private IMethods mock; + @Mock private IMethods mock; @Test public void shouldNotThrowCCE() { diff --git a/src/test/java/org/mockitousage/matchers/CustomMatchersTest.java b/src/test/java/org/mockitousage/matchers/CustomMatchersTest.java index 42d73dd84a..ddcb32a7b6 100644 --- a/src/test/java/org/mockitousage/matchers/CustomMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/CustomMatchersTest.java @@ -145,15 +145,20 @@ public void shouldAnonymousCustomMatcherPrintDefaultDescription() { mock.simpleMethod("foo"); try { - verify(mock).simpleMethod((String) argThat(new ArgumentMatcher() { - public boolean matches(Object argument) { - return false; - }})); + verify(mock) + .simpleMethod( + (String) + argThat( + new ArgumentMatcher() { + public boolean matches(Object argument) { + return false; + } + })); fail(); } catch (AssertionError e) { assertThat(e) - .hasMessageContaining("") - .hasMessageContaining("foo"); + .hasMessageContaining("") + .hasMessageContaining("foo"); } } } diff --git a/src/test/java/org/mockitousage/matchers/GenericMatchersTest.java b/src/test/java/org/mockitousage/matchers/GenericMatchersTest.java index 1194c26b83..83a53bd1ce 100644 --- a/src/test/java/org/mockitousage/matchers/GenericMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/GenericMatchersTest.java @@ -19,6 +19,7 @@ public class GenericMatchersTest extends TestBase { private interface Foo { List sort(List otherList); + String convertDate(Date date); } @@ -30,7 +31,7 @@ public void shouldCompile() { when(sorter.convertDate(new Date())).thenReturn("one"); when(sorter.convertDate((Date) anyObject())).thenReturn("two"); - //following requires warning suppression but allows setting anyList() + // following requires warning suppression but allows setting anyList() when(sorter.sort(ArgumentMatchers.anyList())).thenReturn(null); } } diff --git a/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java b/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java index 0545e2f877..3f16618c2f 100644 --- a/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java @@ -33,8 +33,7 @@ public void describeTo(Description d) { } } - @Mock - private IMethods mock; + @Mock private IMethods mock; @Test public void stubs_with_hamcrest_matcher() { @@ -59,6 +58,7 @@ private class IntMatcher extends BaseMatcher { public boolean matches(Object o) { return true; } + public void describeTo(Description description) {} } @@ -92,6 +92,7 @@ private class NonGenericMatcher extends BaseMatcher { public boolean matches(Object o) { return true; } + public void describeTo(Description description) {} } @@ -109,11 +110,14 @@ private int nonGenericMatcher() { @Test public void coexists_with_mockito_matcher() { - when(mock.simpleMethod(Mockito.argThat(new ArgumentMatcher() { - public boolean matches(String argument) { - return true; - } - }))).thenReturn("x"); + when(mock.simpleMethod( + Mockito.argThat( + new ArgumentMatcher() { + public boolean matches(String argument) { + return true; + } + }))) + .thenReturn("x"); assertEquals("x", mock.simpleMethod("x")); } diff --git a/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java b/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java index 59977e25b2..ebcb08871c 100644 --- a/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java @@ -34,9 +34,7 @@ public void should_detect_wrong_number_of_matchers_when_stubbing() { when(mock.threeArgumentMethod(1, eq("2"), "3")).thenReturn(null); fail(); } catch (InvalidUseOfMatchersException e) { - assertThat(e.getMessage()) - .contains("3 matchers expected") - .contains("1 recorded"); + assertThat(e.getMessage()).contains("3 matchers expected").contains("1 recorded"); } } @@ -92,9 +90,7 @@ public void should_scream_when_Matchers_count_dont_match_parameter_count() { mock.threeArgumentMethod(1, "asd", eq("asd")); fail(); } catch (InvalidUseOfMatchersException e) { - assertThat(e.getMessage()) - .contains("3 matchers expected") - .contains("1 recorded"); + assertThat(e.getMessage()).contains("3 matchers expected").contains("1 recorded"); } } @@ -102,19 +98,19 @@ public void should_scream_when_Matchers_count_dont_match_parameter_count() { public void should_mention_matcher_when_misuse_detected() { // Given - // When Result run = new JUnitCore().run(ObjectMatcherMisuseOnPrimitiveSite.class); // Then assertThat(run.getFailures()).hasSize(2); - assertThat(run.getFailures().get(0).getException()).isInstanceOf(NullPointerException.class) - .hasMessage(null); - assertThat(run.getFailures().get(1).getException()).isInstanceOf(InvalidUseOfMatchersException.class) - .hasMessageContaining("primitive alternatives"); + assertThat(run.getFailures().get(0).getException()) + .isInstanceOf(NullPointerException.class) + .hasMessage(null); + assertThat(run.getFailures().get(1).getException()) + .isInstanceOf(InvalidUseOfMatchersException.class) + .hasMessageContaining("primitive alternatives"); new StateMaster().reset(); - } @RunWith(MockitoJUnitRunner.class) @@ -122,10 +118,9 @@ public static class ObjectMatcherMisuseOnPrimitiveSite { @Test public void fails_with_NPE() { IMethods mock = Mockito.mock(IMethods.class); - doNothing().when(mock) - .twoArgumentMethod(eq(73), - (Integer) any()); // <= Raise NPE on this call site + doNothing() + .when(mock) + .twoArgumentMethod(eq(73), (Integer) any()); // <= Raise NPE on this call site } - } } diff --git a/src/test/java/org/mockitousage/matchers/MatchersMixedWithRawArgumentsTest.java b/src/test/java/org/mockitousage/matchers/MatchersMixedWithRawArgumentsTest.java index fdaa80db3f..bea1960fd3 100644 --- a/src/test/java/org/mockitousage/matchers/MatchersMixedWithRawArgumentsTest.java +++ b/src/test/java/org/mockitousage/matchers/MatchersMixedWithRawArgumentsTest.java @@ -18,20 +18,21 @@ public class MatchersMixedWithRawArgumentsTest extends TestBase { @Mock private IMethods mock; - //description of an idea: - //types of arguments and descriptor value that identifies matcher: - //Object: objenesis instance to check for identity - //boolean: false - //byte: max-1 - //short: max-1 - //int: max-1 - //long: max-1 - //char: 'x' - //double: max-1 - //float: max-1 - - //1. how objenesis deal with primitive arrays (like byte[])? - //2. Analisys of all matchers used by R2 project finished before anyObject() and so far proves it's a good idea. + // description of an idea: + // types of arguments and descriptor value that identifies matcher: + // Object: objenesis instance to check for identity + // boolean: false + // byte: max-1 + // short: max-1 + // int: max-1 + // long: max-1 + // char: 'x' + // double: max-1 + // float: max-1 + + // 1. how objenesis deal with primitive arrays (like byte[])? + // 2. Analisys of all matchers used by R2 project finished before anyObject() and so far proves + // it's a good idea. @Ignore("prototyping new feature that allows to avoid eq() matchers when raw args passed") @Test diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java index 71cc1ff621..606cc76ec6 100644 --- a/src/test/java/org/mockitousage/matchers/MatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java @@ -60,7 +60,6 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; - @SuppressWarnings("unchecked") public class MatchersTest extends TestBase { private IMethods mock = Mockito.mock(IMethods.class); @@ -326,60 +325,61 @@ public void should_array_equals_deal_with_null_array() throws Exception { @Test public void should_use_smart_equals_for_arrays() throws Exception { - //issue 143 - mock.arrayMethod(new String[]{"one"}); - verify(mock).arrayMethod(eq(new String[]{"one"})); - verify(mock).arrayMethod(new String[]{"one"}); + // issue 143 + mock.arrayMethod(new String[] {"one"}); + verify(mock).arrayMethod(eq(new String[] {"one"})); + verify(mock).arrayMethod(new String[] {"one"}); } @Test public void should_use_smart_equals_for_primitive_arrays() throws Exception { - //issue 143 - mock.objectArgMethod(new int[]{1, 2}); - verify(mock).objectArgMethod(eq(new int[]{1, 2})); - verify(mock).objectArgMethod(new int[]{1, 2}); + // issue 143 + mock.objectArgMethod(new int[] {1, 2}); + verify(mock).objectArgMethod(eq(new int[] {1, 2})); + verify(mock).objectArgMethod(new int[] {1, 2}); } @SuppressWarnings("ReturnValueIgnored") @Test(expected = ArgumentsAreDifferent.class) - public void array_equals_should_throw_ArgumentsAreDifferentException_for_non_matching_arguments() { + public void + array_equals_should_throw_ArgumentsAreDifferentException_for_non_matching_arguments() { List list = Mockito.mock(List.class); list.add("test"); // testing fix for issue 20 - list.contains(new Object[]{"1"}); + list.contains(new Object[] {"1"}); - Mockito.verify(list).contains(new Object[]{"1", "2", "3"}); + Mockito.verify(list).contains(new Object[] {"1", "2", "3"}); } @Test public void array_equals_matcher() { - when(mock.oneArray(aryEq(new boolean[]{true, false, false}))).thenReturn("0"); - when(mock.oneArray(aryEq(new byte[]{1}))).thenReturn("1"); - when(mock.oneArray(aryEq(new char[]{1}))).thenReturn("2"); - when(mock.oneArray(aryEq(new double[]{1}))).thenReturn("3"); - when(mock.oneArray(aryEq(new float[]{1}))).thenReturn("4"); - when(mock.oneArray(aryEq(new int[]{1}))).thenReturn("5"); - when(mock.oneArray(aryEq(new long[]{1}))).thenReturn("6"); - when(mock.oneArray(aryEq(new short[]{1}))).thenReturn("7"); - when(mock.oneArray(aryEq(new String[]{"Test"}))).thenReturn("8"); - when(mock.oneArray(aryEq(new Object[]{"Test", new Integer(4)}))).thenReturn("9"); - - assertEquals("0", mock.oneArray(new boolean[]{true, false, false})); - assertEquals("1", mock.oneArray(new byte[]{1})); - assertEquals("2", mock.oneArray(new char[]{1})); - assertEquals("3", mock.oneArray(new double[]{1})); - assertEquals("4", mock.oneArray(new float[]{1})); - assertEquals("5", mock.oneArray(new int[]{1})); - assertEquals("6", mock.oneArray(new long[]{1})); - assertEquals("7", mock.oneArray(new short[]{1})); - assertEquals("8", mock.oneArray(new String[]{"Test"})); - assertEquals("9", mock.oneArray(new Object[]{"Test", new Integer(4)})); - - assertEquals(null, mock.oneArray(new Object[]{"Test", new Integer(999)})); - assertEquals(null, mock.oneArray(new Object[]{"Test", new Integer(4), "x"})); - - assertEquals(null, mock.oneArray(new boolean[]{true, false})); - assertEquals(null, mock.oneArray(new boolean[]{true, true, false})); + when(mock.oneArray(aryEq(new boolean[] {true, false, false}))).thenReturn("0"); + when(mock.oneArray(aryEq(new byte[] {1}))).thenReturn("1"); + when(mock.oneArray(aryEq(new char[] {1}))).thenReturn("2"); + when(mock.oneArray(aryEq(new double[] {1}))).thenReturn("3"); + when(mock.oneArray(aryEq(new float[] {1}))).thenReturn("4"); + when(mock.oneArray(aryEq(new int[] {1}))).thenReturn("5"); + when(mock.oneArray(aryEq(new long[] {1}))).thenReturn("6"); + when(mock.oneArray(aryEq(new short[] {1}))).thenReturn("7"); + when(mock.oneArray(aryEq(new String[] {"Test"}))).thenReturn("8"); + when(mock.oneArray(aryEq(new Object[] {"Test", new Integer(4)}))).thenReturn("9"); + + assertEquals("0", mock.oneArray(new boolean[] {true, false, false})); + assertEquals("1", mock.oneArray(new byte[] {1})); + assertEquals("2", mock.oneArray(new char[] {1})); + assertEquals("3", mock.oneArray(new double[] {1})); + assertEquals("4", mock.oneArray(new float[] {1})); + assertEquals("5", mock.oneArray(new int[] {1})); + assertEquals("6", mock.oneArray(new long[] {1})); + assertEquals("7", mock.oneArray(new short[] {1})); + assertEquals("8", mock.oneArray(new String[] {"Test"})); + assertEquals("9", mock.oneArray(new Object[] {"Test", new Integer(4)})); + + assertEquals(null, mock.oneArray(new Object[] {"Test", new Integer(999)})); + assertEquals(null, mock.oneArray(new Object[] {"Test", new Integer(4), "x"})); + + assertEquals(null, mock.oneArray(new boolean[] {true, false})); + assertEquals(null, mock.oneArray(new boolean[] {true, true, false})); } @Test diff --git a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java index 09ff888049..825902f7b4 100644 --- a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java @@ -48,25 +48,29 @@ public void any_class_should_be_actual_alias_to_isA() { mock.simpleMethod((String) null); - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock).simpleMethod(isA(String.class)); - } - }).isInstanceOf(ArgumentsAreDifferent.class); - - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock).simpleMethod(any(String.class)); - } - }).isInstanceOf(ArgumentsAreDifferent.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock).simpleMethod(isA(String.class)); + } + }) + .isInstanceOf(ArgumentsAreDifferent.class); + + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock).simpleMethod(any(String.class)); + } + }) + .isInstanceOf(ArgumentsAreDifferent.class); } @Test public void should_help_out_with_unnecessary_casting_of_lists() { - //Below yields compiler warning: - //when(mock.listArgMethod(anyList())).thenReturn("list"); + // Below yields compiler warning: + // when(mock.listArgMethod(anyList())).thenReturn("list"); when(mock.listArgMethod(anyListOf(String.class))).thenReturn("list"); assertEquals("list", mock.listArgMethod(new LinkedList())); @@ -75,8 +79,8 @@ public void should_help_out_with_unnecessary_casting_of_lists() { @Test public void should_help_out_with_unnecessary_casting_of_sets() { - //Below yields compiler warning: - //when(mock.setArgMethod(anySet())).thenReturn("set"); + // Below yields compiler warning: + // when(mock.setArgMethod(anySet())).thenReturn("set"); when(mock.setArgMethod(anySetOf(String.class))).thenReturn("set"); assertEquals("set", mock.setArgMethod(new HashSet())); @@ -85,8 +89,8 @@ public void should_help_out_with_unnecessary_casting_of_sets() { @Test public void should_help_out_with_unnecessary_casting_of_maps() { - //Below yields compiler warning: - //when(mock.setArgMethod(anySet())).thenReturn("set"); + // Below yields compiler warning: + // when(mock.setArgMethod(anySet())).thenReturn("set"); when(mock.forMap(anyMapOf(String.class, String.class))).thenReturn("map"); assertEquals("map", mock.forMap(new HashMap())); @@ -95,8 +99,8 @@ public void should_help_out_with_unnecessary_casting_of_maps() { @Test public void should_help_out_with_unnecessary_casting_of_collections() { - //Below yields compiler warning: - //when(mock.setArgMethod(anySet())).thenReturn("set"); + // Below yields compiler warning: + // when(mock.setArgMethod(anySet())).thenReturn("set"); when(mock.collectionArgMethod(anyCollectionOf(String.class))).thenReturn("collection"); assertEquals("collection", mock.collectionArgMethod(new ArrayList())); @@ -105,8 +109,8 @@ public void should_help_out_with_unnecessary_casting_of_collections() { @Test public void should_help_out_with_unnecessary_casting_of_iterables() { - //Below yields compiler warning: - //when(mock.setArgMethod(anySet())).thenReturn("set"); + // Below yields compiler warning: + // when(mock.setArgMethod(anySet())).thenReturn("set"); when(mock.iterableArgMethod(anyIterableOf(String.class))).thenReturn("iterable"); assertEquals("iterable", mock.iterableArgMethod(new ArrayList())); @@ -123,5 +127,4 @@ public void should_help_out_with_unnecessary_casting_of_nullity_checks() { assertEquals("string", mock.objectArgMethod("foo")); assertEquals("string", mock.objectArgMethod("foo")); } - } diff --git a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java index 14e4c6a093..a2d497e586 100644 --- a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java @@ -19,6 +19,7 @@ public class ReflectionMatchersTest extends TestBase { class Parent { private int parentField; protected String protectedParentField; + public Parent(int parentField, String protectedParentField) { this.parentField = parentField; this.protectedParentField = protectedParentField; @@ -28,7 +29,12 @@ public Parent(int parentField, String protectedParentField) { class Child extends Parent { private int childFieldOne; private Object childFieldTwo; - public Child(int parentField, String protectedParentField, int childFieldOne, Object childFieldTwo) { + + public Child( + int parentField, + String protectedParentField, + int childFieldOne, + Object childFieldTwo) { super(parentField, protectedParentField); this.childFieldOne = childFieldOne; this.childFieldTwo = childFieldTwo; @@ -55,25 +61,25 @@ public void shouldMatchWhenFieldValuesEqual() throws Exception { verify(mock).run(refEq(wanted)); } - @Test(expected=ArgumentsAreDifferent.class) + @Test(expected = ArgumentsAreDifferent.class) public void shouldNotMatchWhenFieldValuesDiffer() throws Exception { Child wanted = new Child(1, "foo", 2, "bar XXX"); verify(mock).run(refEq(wanted)); } - @Test(expected=ArgumentsAreDifferent.class) + @Test(expected = ArgumentsAreDifferent.class) public void shouldNotMatchAgain() throws Exception { Child wanted = new Child(1, "foo", 999, "bar"); verify(mock).run(refEq(wanted)); } - @Test(expected=ArgumentsAreDifferent.class) + @Test(expected = ArgumentsAreDifferent.class) public void shouldNotMatchYetAgain() throws Exception { Child wanted = new Child(1, "XXXXX", 2, "bar"); verify(mock).run(refEq(wanted)); } - @Test(expected=ArgumentsAreDifferent.class) + @Test(expected = ArgumentsAreDifferent.class) public void shouldNotMatch() throws Exception { Child wanted = new Child(234234, "foo", 2, "bar"); verify(mock).run(refEq(wanted)); @@ -92,7 +98,7 @@ public void shouldMatchWhenFieldValuesEqualWithTwoFieldsExcluded() throws Except verify(mock).run(refEq(wanted, "parentField", "childFieldTwo")); } - @Test(expected=ArgumentsAreDifferent.class) + @Test(expected = ArgumentsAreDifferent.class) public void shouldNotMatchWithFieldsExclusion() throws Exception { Child wanted = new Child(234234, "foo", 2, "excluded"); verify(mock).run(refEq(wanted, "childFieldTwo")); diff --git a/src/test/java/org/mockitousage/matchers/VarargsTest.java b/src/test/java/org/mockitousage/matchers/VarargsTest.java index 0562d7aed3..dbcee31dad 100644 --- a/src/test/java/org/mockitousage/matchers/VarargsTest.java +++ b/src/test/java/org/mockitousage/matchers/VarargsTest.java @@ -31,22 +31,19 @@ public class VarargsTest { - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Rule - public ExpectedException exception = ExpectedException.none(); - @Captor - private ArgumentCaptor captor; - @Mock - private IMethods mock; - - private static final Condition NULL = new Condition() { - - @Override - public boolean matches(Object value) { - return value == null; - } - }; + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Rule public ExpectedException exception = ExpectedException.none(); + @Captor private ArgumentCaptor captor; + @Mock private IMethods mock; + + private static final Condition NULL = + new Condition() { + + @Override + public boolean matches(Object value) { + return value == null; + } + }; @Test public void shouldMatchVarArgs_noArgs() { @@ -116,7 +113,7 @@ public void shouldnotMatchVarArgs_twoArgsOneMatcher() { public void shouldMatchVarArgs_emptyVarArgsOneAnyMatcher() { mock.varargs(); - verify(mock).varargs((String[])any()); // any() -> VarargMatcher + verify(mock).varargs((String[]) any()); // any() -> VarargMatcher } @Test @@ -146,7 +143,7 @@ public void shouldMatchVarArgs_twoArgsThreeAnyMatcher() { exception.expectMessage("Argument(s) are different"); - verify(mock).varargs(any(), any(), any()); //any() -> VarargMatcher + verify(mock).varargs(any(), any(), any()); // any() -> VarargMatcher } @Test @@ -267,7 +264,6 @@ public void shouldNotCaptureVarArgs_3args2captures() { exception.expect(ArgumentsAreDifferent.class); verify(mock).varargs(captor.capture(), captor.capture()); - } @Test @@ -277,7 +273,6 @@ public void shouldCaptureVarArgs_3argsCaptorMatcherMix() { verify(mock).varargs(captor.capture(), eq("2"), captor.capture()); assertThat(captor).containsExactly("1", "3"); - } @Test @@ -291,7 +286,6 @@ public void shouldNotCaptureVarArgs_3argsCaptorMatcherMix() { } assertThat(captor).isEmpty(); - } @Test @@ -301,7 +295,6 @@ public void shouldNotCaptureVarArgs_1args2captures() { exception.expect(ArgumentsAreDifferent.class); verify(mock).varargs(captor.capture(), captor.capture()); - } /** @@ -321,25 +314,27 @@ public void shouldCaptureVarArgsAsArray() { verify(mock).varargs(varargCaptor.capture()); - assertThat(varargCaptor).containsExactly(new String[] { "1", "2" }); + assertThat(varargCaptor).containsExactly(new String[] {"1", "2"}); } @Test - public void shouldNotMatchRegualrAndVaraArgs() { - mock.varargsString(1, "a","b"); + public void shouldNotMatchRegualrAndVaraArgs() { + mock.varargsString(1, "a", "b"); exception.expect(ArgumentsAreDifferent.class); verify(mock).varargsString(1); } + @Test - public void shouldNotMatchVaraArgs() { - when(mock.varargsObject(1, "a","b")).thenReturn("OK"); + public void shouldNotMatchVaraArgs() { + when(mock.varargsObject(1, "a", "b")).thenReturn("OK"); Assertions.assertThat(mock.varargsObject(1)).isNull(); } - private static AbstractListAssert> assertThat(ArgumentCaptor captor) { + private static AbstractListAssert> assertThat( + ArgumentCaptor captor) { return Assertions.assertThat(captor.getAllValues()); } } diff --git a/src/test/java/org/mockitousage/matchers/VerificationAndStubbingUsingMatchersTest.java b/src/test/java/org/mockitousage/matchers/VerificationAndStubbingUsingMatchersTest.java index 3da81c586f..d0d9cf9be1 100644 --- a/src/test/java/org/mockitousage/matchers/VerificationAndStubbingUsingMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/VerificationAndStubbingUsingMatchersTest.java @@ -44,7 +44,8 @@ public void shouldStubUsingMatchers() { try { three.simpleMethod("test three again"); fail(); - } catch (RuntimeException e) {} + } catch (RuntimeException e) { + } } @Test @@ -55,7 +56,8 @@ public void shouldVerifyUsingMatchers() { try { one.oneArg(true); fail(); - } catch (RuntimeException e) {} + } catch (RuntimeException e) { + } one.simpleMethod(100); two.simpleMethod("test Mockito"); @@ -74,6 +76,7 @@ public void shouldVerifyUsingMatchers() { try { verify(three).varargsObject(eq(10), eq("first arg"), startsWith("third")); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } } diff --git a/src/test/java/org/mockitousage/misuse/CleaningUpPotentialStubbingTest.java b/src/test/java/org/mockitousage/misuse/CleaningUpPotentialStubbingTest.java index 56dd8a282d..7a67d7bb02 100644 --- a/src/test/java/org/mockitousage/misuse/CleaningUpPotentialStubbingTest.java +++ b/src/test/java/org/mockitousage/misuse/CleaningUpPotentialStubbingTest.java @@ -45,10 +45,11 @@ public void shouldResetOngoingStubbingOnDoReturn() { private void assertOngoingStubbingIsReset() { try { - //In real, there might be a call to real object or a final method call - //I'm modelling it with null + // In real, there might be a call to real object or a final method call + // I'm modelling it with null when(null).thenReturn("anything"); fail(); - } catch (MissingMethodInvocationException e) {} + } catch (MissingMethodInvocationException e) { + } } } diff --git a/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java b/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java index 92dfc0057e..196f9d0675 100644 --- a/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java +++ b/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java @@ -29,74 +29,74 @@ public final String finalMethod() { public void tryDescriptiveMessagesOnMisuse() { Foo foo = mock(Foo.class); -// when(foo.finalMethod()).thenReturn("foo"); -// doReturn("foo").when(foo).finalMethod(); -// verify(foo).finalMethod(); - -// doReturn("foo"); -// doReturn("bar"); - -// verifyNoMoreInteractions(); -// verifyNoMoreInteractions(null); -// verifyNoMoreInteractions(""); -// verifyZeroInteractions(); -// verifyZeroInteractions(null); -// verifyZeroInteractions(""); -// -// inOrder(); -// inOrder(null); -// inOrder("test"); -// InOrder inOrder = inOrder(mock(List.class)); -// inOrder.verify(mock).simpleMethod(); - -// verify(null); -// verify(mock.booleanReturningMethod()); - -// verify(mock).varargs("test", anyString()); - -// when("x").thenReturn("x"); - -// when(mock.simpleMethod()); -// when(mock.differentMethod()).thenReturn(""); + // when(foo.finalMethod()).thenReturn("foo"); + // doReturn("foo").when(foo).finalMethod(); + // verify(foo).finalMethod(); + + // doReturn("foo"); + // doReturn("bar"); + + // verifyNoMoreInteractions(); + // verifyNoMoreInteractions(null); + // verifyNoMoreInteractions(""); + // verifyZeroInteractions(); + // verifyZeroInteractions(null); + // verifyZeroInteractions(""); + // + // inOrder(); + // inOrder(null); + // inOrder("test"); + // InOrder inOrder = inOrder(mock(List.class)); + // inOrder.verify(mock).simpleMethod(); + + // verify(null); + // verify(mock.booleanReturningMethod()); + + // verify(mock).varargs("test", anyString()); + + // when("x").thenReturn("x"); + + // when(mock.simpleMethod()); + // when(mock.differentMethod()).thenReturn(""); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test(expected=NotAMockException.class) + @Test(expected = NotAMockException.class) public void shouldScreamWhenWholeMethodPassedToVerify() { verify(mock.booleanReturningMethod()); } - @Test(expected=NotAMockException.class) + @Test(expected = NotAMockException.class) public void shouldScreamWhenWholeMethodPassedToVerifyNoMoreInteractions() { verifyNoMoreInteractions(mock.byteReturningMethod()); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected=NotAMockException.class) + @Test(expected = NotAMockException.class) public void shouldScreamWhenInOrderCreatedWithDodgyMock() { inOrder("not a mock"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected=NullInsteadOfMockException.class) + @Test(expected = NullInsteadOfMockException.class) public void shouldScreamWhenInOrderCreatedWithNulls() { inOrder(mock, null); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test(expected=NullInsteadOfMockException.class) + @Test(expected = NullInsteadOfMockException.class) public void shouldScreamNullPassedToVerify() { verify(null); } - @Test(expected=NullInsteadOfMockException.class) + @Test(expected = NullInsteadOfMockException.class) public void shouldScreamWhenNotMockPassedToVerifyNoMoreInteractions() { verifyNoMoreInteractions(null, "blah"); } @SuppressWarnings("all") - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldScreamWhenNullPassedToVerifyNoMoreInteractions() { - verifyNoMoreInteractions((Object[])null); + verifyNoMoreInteractions((Object[]) null); } } diff --git a/src/test/java/org/mockitousage/misuse/DetectingFinalMethodsTest.java b/src/test/java/org/mockitousage/misuse/DetectingFinalMethodsTest.java index 0b59c0b1ef..71b507ba2a 100644 --- a/src/test/java/org/mockitousage/misuse/DetectingFinalMethodsTest.java +++ b/src/test/java/org/mockitousage/misuse/DetectingFinalMethodsTest.java @@ -31,7 +31,8 @@ public void shouldFailWithUnfinishedVerification() { try { verify(withFinal).foo(); fail(); - } catch (UnfinishedVerificationException e) {} + } catch (UnfinishedVerificationException e) { + } } @Test @@ -41,6 +42,7 @@ public void shouldFailWithUnfinishedStubbing() { try { when(withFinal.foo()).thenReturn(null); fail(); - } catch (MissingMethodInvocationException e) {} + } catch (MissingMethodInvocationException e) { + } } } diff --git a/src/test/java/org/mockitousage/misuse/DetectingMisusedMatchersTest.java b/src/test/java/org/mockitousage/misuse/DetectingMisusedMatchersTest.java index 5e06bacccc..a1c2459dd0 100644 --- a/src/test/java/org/mockitousage/misuse/DetectingMisusedMatchersTest.java +++ b/src/test/java/org/mockitousage/misuse/DetectingMisusedMatchersTest.java @@ -77,13 +77,15 @@ public void should_report_argument_locations_when_argument_matchers_misused() { fail(); } catch (InvalidUseOfMatchersException e) { assertThat(e) - .hasMessageContaining("DetectingMisusedMatchersTest.misplaced_anyInt_argument_matcher") - .hasMessageContaining("DetectingMisusedMatchersTest.misplaced_anyObject_argument_matcher") - .hasMessageContaining("DetectingMisusedMatchersTest.misplaced_anyBoolean_argument_matcher"); + .hasMessageContaining( + "DetectingMisusedMatchersTest.misplaced_anyInt_argument_matcher") + .hasMessageContaining( + "DetectingMisusedMatchersTest.misplaced_anyObject_argument_matcher") + .hasMessageContaining( + "DetectingMisusedMatchersTest.misplaced_anyBoolean_argument_matcher"); } } - @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) @Test public void shouldSayUnfinishedVerificationButNotInvalidUseOfMatchers() { @@ -92,6 +94,7 @@ public void shouldSayUnfinishedVerificationButNotInvalidUseOfMatchers() { try { verify(withFinal); fail(); - } catch (UnfinishedVerificationException e) {} + } catch (UnfinishedVerificationException e) { + } } } diff --git a/src/test/java/org/mockitousage/misuse/ExplicitFrameworkValidationTest.java b/src/test/java/org/mockitousage/misuse/ExplicitFrameworkValidationTest.java index 69be81614a..3fc1f56973 100644 --- a/src/test/java/org/mockitousage/misuse/ExplicitFrameworkValidationTest.java +++ b/src/test/java/org/mockitousage/misuse/ExplicitFrameworkValidationTest.java @@ -29,7 +29,8 @@ public void shouldValidateExplicitly() { try { Mockito.validateMockitoUsage(); fail(); - } catch (UnfinishedVerificationException e) {} + } catch (UnfinishedVerificationException e) { + } } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) @@ -39,7 +40,8 @@ public void shouldDetectUnfinishedStubbing() { try { Mockito.validateMockitoUsage(); fail(); - } catch (UnfinishedStubbingException e) {} + } catch (UnfinishedStubbingException e) { + } } @Test @@ -48,6 +50,7 @@ public void shouldDetectMisplacedArgumentMatcher() { try { Mockito.validateMockitoUsage(); fail(); - } catch (InvalidUseOfMatchersException e) {} + } catch (InvalidUseOfMatchersException e) { + } } } diff --git a/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java b/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java index d14d928f9b..8b07e9a021 100644 --- a/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java +++ b/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java @@ -26,76 +26,81 @@ public void resetState() { super.resetState(); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldRequireArgumentsWhenVerifyingNoMoreInteractions() { verifyNoMoreInteractions(); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldRequireArgumentsWhenVerifyingZeroInteractions() { verifyZeroInteractions(); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldRequireArgumentsWhenVerifyingNoInteractions() { verifyNoInteractions(); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotCreateInOrderObjectWithoutMocks() { inOrder(); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowVerifyingInOrderUnfamilarMocks() { InOrder inOrder = inOrder(mock); inOrder.verify(mockTwo).simpleMethod(); } - @Test(expected=MissingMethodInvocationException.class) + @Test(expected = MissingMethodInvocationException.class) public void shouldReportMissingMethodInvocationWhenStubbing() { - when(mock.simpleMethod()).thenReturn("this stubbing is required to make sure Stubbable is pulled"); + when(mock.simpleMethod()) + .thenReturn("this stubbing is required to make sure Stubbable is pulled"); when("".toString()).thenReturn("x"); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowSettingInvalidCheckedException() throws Exception { when(mock.simpleMethod()).thenThrow(new Exception()); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowSettingNullThrowable() throws Exception { when(mock.simpleMethod()).thenThrow(new Throwable[] {null}); } @SuppressWarnings("all") - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowSettingNullThrowableVararg() throws Exception { when(mock.simpleMethod()).thenThrow((Throwable) null); } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowSettingNullConsecutiveThrowable() throws Exception { when(mock.simpleMethod()).thenThrow(new RuntimeException(), null); } final class FinalClass {} - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowMockingFinalClassesIfDisabled() throws Exception { - assumeFalse("Inlining mock allows mocking final classes", mock(FinalClass.class).getClass() == FinalClass.class); + assumeFalse( + "Inlining mock allows mocking final classes", + mock(FinalClass.class).getClass() == FinalClass.class); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldNotAllowMockingPrimitives() throws Exception { mock(Integer.TYPE); } interface ObjectLikeInterface { boolean equals(Object o); + String toString(); + int hashCode(); } diff --git a/src/test/java/org/mockitousage/misuse/RestrictedObjectMethodsTest.java b/src/test/java/org/mockitousage/misuse/RestrictedObjectMethodsTest.java index 39d054810a..01323400be 100644 --- a/src/test/java/org/mockitousage/misuse/RestrictedObjectMethodsTest.java +++ b/src/test/java/org/mockitousage/misuse/RestrictedObjectMethodsTest.java @@ -39,24 +39,24 @@ public void shouldScreamWhenVerifyToString() { @Test public void shouldBeSilentWhenVerifyHashCode() { - //because it leads to really weird behavior sometimes - //it's because cglib & my code can occasionelly call those methods + // because it leads to really weird behavior sometimes + // it's because cglib & my code can occasionelly call those methods // and when user has verification started at that time there will be a mess verify(mock).hashCode(); } @Test public void shouldBeSilentWhenVerifyEquals() { - //because it leads to really weird behavior sometimes - //it's because cglib & my code can occasionelly call those methods + // because it leads to really weird behavior sometimes + // it's because cglib & my code can occasionelly call those methods // and when user has verification started at that time there will be a mess verify(mock).equals(null); } @Test public void shouldBeSilentWhenVerifyEqualsInOrder() { - //because it leads to really weird behavior sometimes - //it's because cglib & my code can occasionelly call those methods + // because it leads to really weird behavior sometimes + // it's because cglib & my code can occasionelly call those methods // and when user has verification started at that time there will be a mess InOrder inOrder = inOrder(mock); inOrder.verify(mock).equals(null); diff --git a/src/test/java/org/mockitousage/misuse/SpyStubbingMisuseTest.java b/src/test/java/org/mockitousage/misuse/SpyStubbingMisuseTest.java index 361b9c0c8c..9f0acfee4e 100644 --- a/src/test/java/org/mockitousage/misuse/SpyStubbingMisuseTest.java +++ b/src/test/java/org/mockitousage/misuse/SpyStubbingMisuseTest.java @@ -23,11 +23,14 @@ public void nestedWhenTest() { when(out.produce()).thenReturn(mpoo); fail(); } catch (WrongTypeOfReturnValue e) { - assertThat(e.getMessage()).contains("spy").contains("syntax").contains("doReturn|Throw"); + assertThat(e.getMessage()) + .contains("spy") + .contains("syntax") + .contains("doReturn|Throw"); } } - public class Sample { } + public class Sample {} public class Strategy { Sample getSample() { @@ -37,6 +40,7 @@ Sample getSample() { public class Sampler { Sample sample; + Sampler(Strategy f) { sample = f.getSample(); } @@ -44,9 +48,11 @@ public class Sampler { public class Producer { Strategy strategy; + Producer(Strategy f) { strategy = f; } + Sampler produce() { return new Sampler(strategy); } diff --git a/src/test/java/org/mockitousage/packageprotected/PackageProtected.java b/src/test/java/org/mockitousage/packageprotected/PackageProtected.java index 0c1ed91ba4..627b0de463 100644 --- a/src/test/java/org/mockitousage/packageprotected/PackageProtected.java +++ b/src/test/java/org/mockitousage/packageprotected/PackageProtected.java @@ -4,6 +4,4 @@ */ package org.mockitousage.packageprotected; -class PackageProtected { - -} +class PackageProtected {} diff --git a/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java b/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java index 7f2bf5048e..a0b993dd07 100644 --- a/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java +++ b/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java @@ -40,7 +40,8 @@ public void provides_built_in_plugins() { @Test public void instantiator_provider_backwards_compatibility() { InstantiatorProvider provider = plugins.getDefaultPlugin(InstantiatorProvider.class); - Instantiator instantiator = provider.getInstantiator(withSettings().build(MockitoPluginsTest.class)); + Instantiator instantiator = + provider.getInstantiator(withSettings().build(MockitoPluginsTest.class)); assertNotNull(instantiator.newInstance(MockitoPluginsTest.class)); } diff --git a/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java b/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java index 4f79419150..849a16a79c 100644 --- a/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java +++ b/src/test/java/org/mockitousage/puzzlers/BridgeMethodPuzzleTest.java @@ -31,7 +31,7 @@ public String say(T t) { private class Sub extends Super { @Override - public String say(String t) { + public String say(String t) { return "Dummy says: " + t; } } @@ -48,8 +48,8 @@ public void shouldHaveBridgeMethod() throws Exception { @Test public void shouldVerifyCorrectlyWhenBridgeMethodCalled() throws Exception { - //Super has following erasure: say(Object) which differs from Dummy.say(String) - //mock has to detect it and do the super.say() + // Super has following erasure: say(Object) which differs from Dummy.say(String) + // mock has to detect it and do the super.say() Sub s = mock(Sub.class); Super s_down = s; s_down.say("Hello"); @@ -59,8 +59,8 @@ public void shouldVerifyCorrectlyWhenBridgeMethodCalled() throws Exception { @Test public void shouldVerifyCorrectlyWhenBridgeMethodVerified() throws Exception { - //Super has following erasure: say(Object) which differs from Dummy.say(String) - //mock has to detect it and do the super.say() + // Super has following erasure: say(Object) which differs from Dummy.say(String) + // mock has to detect it and do the super.say() Sub s = mock(Sub.class); Super s_down = s; s.say("Hello"); diff --git a/src/test/java/org/mockitousage/puzzlers/OverloadingPuzzleTest.java b/src/test/java/org/mockitousage/puzzlers/OverloadingPuzzleTest.java index 6018056062..981dee5156 100644 --- a/src/test/java/org/mockitousage/puzzlers/OverloadingPuzzleTest.java +++ b/src/test/java/org/mockitousage/puzzlers/OverloadingPuzzleTest.java @@ -40,6 +40,7 @@ public void shouldUseArgumentTypeWhenOverloadingPuzzleDetected() throws Exceptio try { verify(sub).say("Hello"); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } } diff --git a/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java b/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java index 101598c787..2b2106755f 100644 --- a/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java +++ b/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java @@ -29,46 +29,49 @@ public void reproduce_CCE_by_creating_a_mock_with_IMethods_before() throws Excep } @Test - public void check_that_mock_can_be_serialized_in_a_classloader_and_deserialized_in_another() throws Exception { + public void check_that_mock_can_be_serialized_in_a_classloader_and_deserialized_in_another() + throws Exception { byte[] bytes = create_mock_and_serialize_it_in_class_loader_A(); Object the_deserialized_mock = read_stream_and_deserialize_it_in_class_loader_B(bytes); - assertThat(the_deserialized_mock.getClass().getName()).startsWith("org.mockito.codegen.AClassToBeMockedInThisTestOnlyAndInCallablesOnly"); + assertThat(the_deserialized_mock.getClass().getName()) + .startsWith("org.mockito.codegen.AClassToBeMockedInThisTestOnlyAndInCallablesOnly"); } private Object read_stream_and_deserialize_it_in_class_loader_B(byte[] bytes) throws Exception { - return new SimplePerRealmReloadingClassLoader(this.getClass().getClassLoader(), isolating_test_classes()) + return new SimplePerRealmReloadingClassLoader( + this.getClass().getClassLoader(), isolating_test_classes()) .doInRealm( "org.mockitousage.serialization.AcrossClassLoaderSerializationTest$ReadStreamAndDeserializeIt", - new Class[]{ byte[].class }, - new Object[]{ bytes } - ); + new Class[] {byte[].class}, + new Object[] {bytes}); } private byte[] create_mock_and_serialize_it_in_class_loader_A() throws Exception { - return (byte[]) new SimplePerRealmReloadingClassLoader(this.getClass().getClassLoader(), isolating_test_classes()) - .doInRealm("org.mockitousage.serialization.AcrossClassLoaderSerializationTest$CreateMockAndSerializeIt"); + return (byte[]) + new SimplePerRealmReloadingClassLoader( + this.getClass().getClassLoader(), isolating_test_classes()) + .doInRealm( + "org.mockitousage.serialization.AcrossClassLoaderSerializationTest$CreateMockAndSerializeIt"); } - private SimplePerRealmReloadingClassLoader.ReloadClassPredicate isolating_test_classes() { return new SimplePerRealmReloadingClassLoader.ReloadClassPredicate() { public boolean acceptReloadOf(String qualifiedName) { return qualifiedName.contains("org.mockitousage") - || qualifiedName.contains("org.mockitoutil") - ; + || qualifiedName.contains("org.mockitoutil"); } }; } - // see create_mock_and_serialize_it_in_class_loader_A public static class CreateMockAndSerializeIt implements Callable { public byte[] call() throws Exception { - AClassToBeMockedInThisTestOnlyAndInCallablesOnly mock = Mockito.mock( - AClassToBeMockedInThisTestOnlyAndInCallablesOnly.class, - Mockito.withSettings().serializable(SerializableMode.ACROSS_CLASSLOADERS) - ); + AClassToBeMockedInThisTestOnlyAndInCallablesOnly mock = + Mockito.mock( + AClassToBeMockedInThisTestOnlyAndInCallablesOnly.class, + Mockito.withSettings() + .serializable(SerializableMode.ACROSS_CLASSLOADERS)); // use MethodProxy before mock.returningSomething(); @@ -87,14 +90,13 @@ public ReadStreamAndDeserializeIt(byte[] bytes) { public Object call() throws Exception { ByteArrayInputStream to_unserialize = new ByteArrayInputStream(bytes); return SimpleSerializationUtil.deserializeMock( - to_unserialize, - AClassToBeMockedInThisTestOnlyAndInCallablesOnly.class - ); + to_unserialize, AClassToBeMockedInThisTestOnlyAndInCallablesOnly.class); } } - public static class AClassToBeMockedInThisTestOnlyAndInCallablesOnly { - List returningSomething() { return Collections.emptyList(); } + List returningSomething() { + return Collections.emptyList(); + } } } diff --git a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java index b75847db33..06f74b9854 100644 --- a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java +++ b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java @@ -23,7 +23,10 @@ public class DeepStubsSerializableTest { @Test public void should_serialize_and_deserialize_mock_created_with_deep_stubs() throws Exception { // given - SampleClass sampleClass = mock(SampleClass.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); + SampleClass sampleClass = + mock( + SampleClass.class, + withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); when(sampleClass.getSample().isFalse()).thenReturn(true); when(sampleClass.getSample().number()).thenReturn(999); @@ -36,32 +39,48 @@ public void should_serialize_and_deserialize_mock_created_with_deep_stubs() thro } @Test - public void should_serialize_and_deserialize_parameterized_class_mocked_with_deep_stubs() throws Exception { + public void should_serialize_and_deserialize_parameterized_class_mocked_with_deep_stubs() + throws Exception { // given - ListContainer deep_stubbed = mock(ListContainer.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); + ListContainer deep_stubbed = + mock( + ListContainer.class, + withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); when(deep_stubbed.iterator().next().add("yes")).thenReturn(true); // when ListContainer deserialized_deep_stub = serializeAndBack(deep_stubbed); // then - assertThat(deserialized_deep_stub.iterator().next().add("not stubbed but mock already previously resolved")).isEqualTo(false); + assertThat( + deserialized_deep_stub + .iterator() + .next() + .add("not stubbed but mock already previously resolved")) + .isEqualTo(false); assertThat(deserialized_deep_stub.iterator().next().add("yes")).isEqualTo(true); } @Test - public void should_discard_generics_metadata_when_serialized_then_disabling_deep_stubs_with_generics() throws Exception { + public void + should_discard_generics_metadata_when_serialized_then_disabling_deep_stubs_with_generics() + throws Exception { // given - ListContainer deep_stubbed = mock(ListContainer.class, withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); + ListContainer deep_stubbed = + mock( + ListContainer.class, + withSettings().defaultAnswer(RETURNS_DEEP_STUBS).serializable()); when(deep_stubbed.iterator().hasNext()).thenReturn(true); ListContainer deserialized_deep_stub = serializeAndBack(deep_stubbed); try { // when stubbing on a deserialized mock - // then revert to the default RETURNS_DEEP_STUBS and the code will raise a ClassCastException + // then revert to the default RETURNS_DEEP_STUBS and the code will raise a + // ClassCastException when(deserialized_deep_stub.iterator().next().get(42)).thenReturn("no"); - fail("Expected an exception to be thrown as deep stubs and serialization does not play well together"); + fail( + "Expected an exception to be thrown as deep stubs and serialization does not play well together"); } catch (NullPointerException e) { assertThat(e).hasMessage(null); } @@ -107,8 +126,7 @@ public E next() { return e; } - public void remove() { - } + public void remove() {} }; } } diff --git a/src/test/java/org/mockitousage/serialization/ParallelSerializationTest.java b/src/test/java/org/mockitousage/serialization/ParallelSerializationTest.java index d448ecd7b6..e2caf7c275 100644 --- a/src/test/java/org/mockitousage/serialization/ParallelSerializationTest.java +++ b/src/test/java/org/mockitousage/serialization/ParallelSerializationTest.java @@ -20,40 +20,48 @@ public class ParallelSerializationTest { @Test - public void single_mock_being_serialized_in_different_classloaders_by_multiple_threads() throws ExecutionException, InterruptedException { + public void single_mock_being_serialized_in_different_classloaders_by_multiple_threads() + throws ExecutionException, InterruptedException { // given int iterations = 2; int threadingFactor = 200; final ExecutorService executorService = Executors.newFixedThreadPool(threadingFactor); - final IMethods iMethods_that_store_invocations = mock(IMethods.class, withSettings().serializable()); + final IMethods iMethods_that_store_invocations = + mock(IMethods.class, withSettings().serializable()); // when for (int i = 0; i <= iterations; i++) { List> futures = new ArrayList>(threadingFactor); - final CyclicBarrier barrier_that_will_wait_until_threads_are_ready = new CyclicBarrier(threadingFactor); + final CyclicBarrier barrier_that_will_wait_until_threads_are_ready = + new CyclicBarrier(threadingFactor); // prepare all threads by submitting a callable // - that will serialize the mock a 'threadingFactor' times // - that will use the mock a 'threadingFactor' times for (int j = 0; j < threadingFactor; j++) { // submit a callable that will serialize the mock 'iMethods' - futures.add(executorService.submit(new Callable() { - public Object call() throws Exception { - barrier_that_will_wait_until_threads_are_ready.await(); + futures.add( + executorService.submit( + new Callable() { + public Object call() throws Exception { + barrier_that_will_wait_until_threads_are_ready.await(); - randomCallOn(iMethods_that_store_invocations); + randomCallOn(iMethods_that_store_invocations); - return SimpleSerializationUtil.serializeMock(iMethods_that_store_invocations).toByteArray(); - } - })); + return SimpleSerializationUtil.serializeMock( + iMethods_that_store_invocations) + .toByteArray(); + } + })); // submit a callable that will only use the mock 'iMethods' - executorService.submit(new Callable() { - public Object call() throws Exception { - barrier_that_will_wait_until_threads_are_ready.await(); - return iMethods_that_store_invocations.longObjectReturningMethod(); - } - }); + executorService.submit( + new Callable() { + public Object call() throws Exception { + barrier_that_will_wait_until_threads_are_ready.await(); + return iMethods_that_store_invocations.longObjectReturningMethod(); + } + }); } // ensure we are getting the futures @@ -66,16 +74,36 @@ public Object call() throws Exception { private void randomCallOn(IMethods iMethods) throws CharacterCodingException { int random = new Random().nextInt(10); switch (random) { - case 0 : iMethods.arrayReturningMethod(); break; - case 1 : iMethods.longObjectReturningMethod(); break; - case 2 : iMethods.linkedListReturningMethod(); break; - case 3 : iMethods.iMethodsReturningMethod(); break; - case 4 : iMethods.canThrowException(); break; - case 5 : iMethods.differentMethod(); break; - case 6 : iMethods.voidMethod(); break; - case 7 : iMethods.varargsString(1, ""); break; - case 8 : iMethods.forMap(null); break; - case 9 : iMethods.throwsNothing(false); break; + case 0: + iMethods.arrayReturningMethod(); + break; + case 1: + iMethods.longObjectReturningMethod(); + break; + case 2: + iMethods.linkedListReturningMethod(); + break; + case 3: + iMethods.iMethodsReturningMethod(); + break; + case 4: + iMethods.canThrowException(); + break; + case 5: + iMethods.differentMethod(); + break; + case 6: + iMethods.voidMethod(); + break; + case 7: + iMethods.varargsString(1, ""); + break; + case 8: + iMethods.forMap(null); + break; + case 9: + iMethods.throwsNothing(false); + break; default: } } diff --git a/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java index fd24c61322..456cde2102 100644 --- a/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java +++ b/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java @@ -18,10 +18,12 @@ @RunWith(MockitoJUnitRunner.StrictStubs.class) public class StrictStubsSerializableTest { - @Mock(serializable = true) private SampleClass sampleClass; + @Mock(serializable = true) + private SampleClass sampleClass; @Test - public void should_serialize_and_deserialize_mock_created_with_serializable_and_strict_stubs() throws Exception { + public void should_serialize_and_deserialize_mock_created_with_serializable_and_strict_stubs() + throws Exception { // given when(sampleClass.isFalse()).thenReturn(true); diff --git a/src/test/java/org/mockitousage/session/MockitoSessionTest.java b/src/test/java/org/mockitousage/session/MockitoSessionTest.java index 8edf96ebde..958e569e32 100644 --- a/src/test/java/org/mockitousage/session/MockitoSessionTest.java +++ b/src/test/java/org/mockitousage/session/MockitoSessionTest.java @@ -32,98 +32,111 @@ public class MockitoSessionTest extends TestBase { private JUnitCore junit = new JUnitCore(); - @Test public void session_without_any_configuration() { - //when + @Test + public void session_without_any_configuration() { + // when Result result = junit.run(MockitoSessionTest.SessionWithoutAnyConfiguration.class); - //expect + // expect JUnitResultAssert.assertThat(result).succeeds(1); } - @Test public void session_without_init_mocks_configured() { - //when + @Test + public void session_without_init_mocks_configured() { + // when Result result = junit.run(MockitoSessionTest.SessionWithoutInitMocksConfigured.class); - //expect + // expect JUnitResultAssert.assertThat(result).succeeds(1); } - @Test public void session_without_strictness_configured() { - //when + @Test + public void session_without_strictness_configured() { + // when Result result = junit.run(MockitoSessionTest.SessionWithoutStrictnessConfigured.class); - //expect + // expect JUnitResultAssert.assertThat(result).succeeds(1); } - @Test public void session_with_incorrect_mockito_usage() { - //when + @Test + public void session_with_incorrect_mockito_usage() { + // when Result result = junit.run(MockitoSessionTest.SessionWithIncorrectMockitoUsage.class); - //expect + // expect JUnitResultAssert.assertThat(result).fails(1, UnfinishedStubbingException.class); } - @Test public void reports_other_failure_and_incorrect_mockito_usage() { - //when - Result result = junit.run(MockitoSessionTest.SessionWithTestFailureAndIncorrectMockitoUsage.class); + @Test + public void reports_other_failure_and_incorrect_mockito_usage() { + // when + Result result = + junit.run(MockitoSessionTest.SessionWithTestFailureAndIncorrectMockitoUsage.class); - //expect + // expect JUnitResultAssert.assertThat(result) .failsExactly(AssertionError.class, UnfinishedStubbingException.class); } - @Test public void allows_initializing_mocks_manually() { - //when + @Test + public void allows_initializing_mocks_manually() { + // when Result result = junit.run(MockitoSessionTest.SessionWithManuallyInitializedMock.class); - //expect + // expect JUnitResultAssert.assertThat(result).succeeds(1); } - @Test public void allows_updating_strictness() { - //when + @Test + public void allows_updating_strictness() { + // when Result result = junit.run(MockitoSessionTest.SessionWithUpdatedStrictness.class); - //expect + // expect JUnitResultAssert.assertThat(result).succeeds(1); } - @Test public void allows_overriding_failure() { - //when + @Test + public void allows_overriding_failure() { + // when Result result = junit.run(MockitoSessionTest.SessionWithOverriddenFailure.class); - //expect + // expect JUnitResultAssert.assertThat(result).isSuccessful(); - //in order to demonstrate feature, we intentionally misuse Mockito and need to clean up state + // in order to demonstrate feature, we intentionally misuse Mockito and need to clean up + // state resetState(); } - @Test public void cleans_up_state_when_init_fails() { - //when + @Test + public void cleans_up_state_when_init_fails() { + // when Result result = junit.run(MockitoSessionTest.SessionWithInitMocksFailure.class); - //expect that both failures are the same, indicating correct listener cleanup - //incorrect cleanup causes 1 failure to be InjectMocksException - // but the next test method would have failed with unuseful error that session was not cleaned up - JUnitResultAssert.assertThat(result) - .fails(2, InjectMocksException.class); + // expect that both failures are the same, indicating correct listener cleanup + // incorrect cleanup causes 1 failure to be InjectMocksException + // but the next test method would have failed with unuseful error that session was not + // cleaned up + JUnitResultAssert.assertThat(result).fails(2, InjectMocksException.class); } public static class SessionWithoutAnyConfiguration { @Mock IMethods mock; - //session without initMocks is not currently supported + // session without initMocks is not currently supported MockitoSession mockito = Mockito.mockitoSession().startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(); } - @Test public void some_test() { - assertNull(mock); //initMocks() was not used when configuring session + @Test + public void some_test() { + assertNull(mock); // initMocks() was not used when configuring session } } @@ -131,14 +144,17 @@ public static class SessionWithoutInitMocksConfigured { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().strictness(Strictness.LENIENT).startMocking(); + MockitoSession mockito = + Mockito.mockitoSession().strictness(Strictness.LENIENT).startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(); } - @Test public void some_test() { - assertNull(mock); //initMocks() was not used when configuring session + @Test + public void some_test() { + assertNull(mock); // initMocks() was not used when configuring session } } @@ -147,11 +163,13 @@ public static class SessionWithoutStrictnessConfigured { MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(); } - @Test public void some_test() { + @Test + public void some_test() { assertNotNull(mock); } } @@ -161,12 +179,14 @@ public static class SessionWithIncorrectMockitoUsage { MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void unfinished_stubbing() { + @Test + public void unfinished_stubbing() { when(mock.simpleMethod()); } } @@ -176,12 +196,14 @@ public static class SessionWithTestFailureAndIncorrectMockitoUsage { MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void unfinished_stubbing_with_other_failure() { + @Test + public void unfinished_stubbing_with_other_failure() { when(mock.simpleMethod()); assertTrue(false); } @@ -193,31 +215,43 @@ public static class SessionWithManuallyInitializedMock { MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(); } - @Test public void manual_mock_preserves_its_settings() { - assertEquals("mock", mockingDetails(mock).getMockCreationSettings().getMockName().toString()); - assertEquals("manual mock", mockingDetails(mock2).getMockCreationSettings().getMockName().toString()); + @Test + public void manual_mock_preserves_its_settings() { + assertEquals( + "mock", + mockingDetails(mock).getMockCreationSettings().getMockName().toString()); + assertEquals( + "manual mock", + mockingDetails(mock2).getMockCreationSettings().getMockName().toString()); } } public static class SessionWithUpdatedStrictness { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); - - @After public void after() { + MockitoSession mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); + + @After + public void after() { mockito.finishMocking(); } - @Test public void manual_mock_preserves_its_settings() { + @Test + public void manual_mock_preserves_its_settings() { when(mock.simpleMethod(1)).thenReturn("foo"); - //when + // when mockito.setStrictness(Strictness.LENIENT); - //then no exception is thrown, even though the arg is different + // then no exception is thrown, even though the arg is different mock.simpleMethod(2); } } @@ -226,12 +260,14 @@ public static class SessionWithOverriddenFailure { @Mock IMethods mock; MockitoSession mockito = Mockito.mockitoSession().initMocks(this).startMocking(); - @After public void after() { + @After + public void after() { mockito.finishMocking(new RuntimeException("Boo!")); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void invalid_mockito_usage() { + @Test + public void invalid_mockito_usage() { verify(mock); } } @@ -245,20 +281,23 @@ public void before() { mockito = Mockito.mockitoSession().initMocks(this).startMocking(); } - @After public void after() { + @After + public void after() { if (mockito != null) { - //so that we reduce amount of exceptions for easier assertions - //otherwise we would get an NPE here + // so that we reduce amount of exceptions for easier assertions + // otherwise we would get an NPE here mockito.finishMocking(); } } - @Test public void test1() { - //should fail the same way + @Test + public void test1() { + // should fail the same way } - @Test public void test2() { - //should fail the same way + @Test + public void test2() { + // should fail the same way } static class ConstructorFail { diff --git a/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java b/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java index 4bf343f179..bf616f8d9f 100644 --- a/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java +++ b/src/test/java/org/mockitousage/spies/PartialMockingWithSpiesTest.java @@ -27,6 +27,7 @@ public void pleaseMakeStackTracesClean() { class InheritMe { private String inherited = "100$"; + protected String getInherited() { return inherited; } @@ -89,13 +90,14 @@ public void shouldAllowStubbingOfMethodsThatDelegateToOtherMethods() { public void shouldAllowStubbingWithThrowablesMethodsThatDelegateToOtherMethods() { // when doThrow(new RuntimeException("appetite for destruction")) - .when(spy).getNameButDelegateToMethodThatThrows(); + .when(spy) + .getNameButDelegateToMethodThatThrows(); // then try { spy.getNameButDelegateToMethodThatThrows(); fail(); - } catch(Exception e) { + } catch (Exception e) { assertEquals("appetite for destruction", e.getMessage()); } } @@ -108,15 +110,16 @@ public void shouldStackTraceGetFilteredOnUserExceptions() { fail(); } catch (Throwable t) { // then - Assertions.assertThat(t).has(methodsInStackTrace( - "throwSomeException", - "getNameButDelegateToMethodThatThrows", - "shouldStackTraceGetFilteredOnUserExceptions" - )); + Assertions.assertThat(t) + .has( + methodsInStackTrace( + "throwSomeException", + "getNameButDelegateToMethodThatThrows", + "shouldStackTraceGetFilteredOnUserExceptions")); } } -// @Test //manual verification + // @Test //manual verification public void verifyTheStackTrace() { spy.getNameButDelegateToMethodThatThrows(); } diff --git a/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java b/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java index 503c246953..ec8d5933d2 100644 --- a/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java +++ b/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java @@ -32,9 +32,9 @@ public class SpyingOnInterfacesTest extends TestBase { public void shouldFailFastWhenCallingRealMethodOnInterface() throws Exception { List list = mock(List.class); try { - //when + // when when(list.get(0)).thenCallRealMethod(); - //then + // then fail(); } catch (MockitoException e) { } @@ -42,19 +42,19 @@ public void shouldFailFastWhenCallingRealMethodOnInterface() throws Exception { @Test public void shouldFailInRuntimeWhenCallingRealMethodOnInterface() throws Exception { - //given + // given List list = mock(List.class); - when(list.get(0)).thenAnswer( - new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return invocation.callRealMethod(); - } - } - ); + when(list.get(0)) + .thenAnswer( + new Answer() { + public Object answer(InvocationOnMock invocation) throws Throwable { + return invocation.callRealMethod(); + } + }); try { - //when + // when list.get(0); - //then + // then fail(); } catch (MockitoException e) { } @@ -62,48 +62,55 @@ public Object answer(InvocationOnMock invocation) throws Throwable { @Test public void shouldAllowDelegatingToDefaultMethod() throws Exception { - assumeTrue("Test can only be executed on Java 8 capable VMs", ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V8)); + assumeTrue( + "Test can only be executed on Java 8 capable VMs", + ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V8)); - Class type = new ByteBuddy() - .makeInterface() - .defineMethod("foo", String.class, Visibility.PUBLIC) - .intercept(FixedValue.value("bar")) - .make() - .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) - .getLoaded(); + Class type = + new ByteBuddy() + .makeInterface() + .defineMethod("foo", String.class, Visibility.PUBLIC) + .intercept(FixedValue.value("bar")) + .make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); Object object = mock(type); - //when + // when when(type.getMethod("foo").invoke(object)).thenCallRealMethod(); - //then + // then Assertions.assertThat(type.getMethod("foo").invoke(object)).isEqualTo((Object) "bar"); type.getMethod("foo").invoke(verify(object)); } @Test public void shouldAllowSpyingOnDefaultMethod() throws Exception { - assumeTrue("Test can only be executed on Java 8 capable VMs", ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V8)); + assumeTrue( + "Test can only be executed on Java 8 capable VMs", + ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V8)); - Class iFace = new ByteBuddy() - .makeInterface() - .defineMethod("foo", String.class, Visibility.PUBLIC) - .intercept(FixedValue.value("bar")) - .make() - .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) - .getLoaded(); + Class iFace = + new ByteBuddy() + .makeInterface() + .defineMethod("foo", String.class, Visibility.PUBLIC) + .intercept(FixedValue.value("bar")) + .make() + .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); - Class impl = new ByteBuddy() - .subclass(iFace) - .make() - .load(iFace.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) - .getLoaded(); + Class impl = + new ByteBuddy() + .subclass(iFace) + .make() + .load(iFace.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) + .getLoaded(); Object object = spy(impl.newInstance()); - //when + // when Assertions.assertThat(impl.getMethod("foo").invoke(object)).isEqualTo((Object) "bar"); - //then + // then impl.getMethod("foo").invoke(verify(object)); } } diff --git a/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java b/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java index 495686144d..a3ed58cfd4 100644 --- a/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java +++ b/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java @@ -48,9 +48,7 @@ public void shouldBeAbleToMockObjectBecauseWhyNot() { @Test public void shouldStub() { spy.add("one"); - when(spy.get(0)) - .thenReturn("1") - .thenReturn("1 again"); + when(spy.get(0)).thenReturn("1").thenReturn("1 again"); assertEquals("1", spy.get(0)); assertEquals("1 again", spy.get(0)); @@ -70,26 +68,22 @@ public void shouldAllowOverridingStubs() { @Test public void shouldStubVoid() { - doNothing() - .doThrow(new RuntimeException()) - .when(spy) - .clear(); + doNothing().doThrow(new RuntimeException()).when(spy).clear(); spy.add("one"); spy.clear(); try { spy.clear(); fail(); - } catch (RuntimeException e) {} + } catch (RuntimeException e) { + } assertEquals(1, spy.size()); } @Test public void shouldStubWithDoReturnAndVerify() { - doReturn("foo") - .doReturn("bar") - .when(spy).get(0); + doReturn("foo").doReturn("bar").when(spy).get(0); assertEquals("foo", spy.get(0)); assertEquals("bar", spy.get(0)); @@ -120,7 +114,8 @@ public void shouldVerifyInOrderAndFail() { try { inOrder.verify(spy).add("one"); fail(); - } catch (VerificationInOrderFailure f) {} + } catch (VerificationInOrderFailure f) { + } } @Test @@ -140,7 +135,8 @@ public void shouldVerifyNumberOfTimesAndFail() { try { verify(spy, times(3)).add("one"); fail(); - } catch (TooFewActualInvocations e) {} + } catch (TooFewActualInvocations e) { + } } @Test @@ -152,13 +148,14 @@ public void shouldVerifyNoMoreInteractionsAndFail() { try { verifyNoMoreInteractions(spy); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test public void shouldToString() { spy.add("foo"); - assertEquals("[foo]" , spy.toString()); + assertEquals("[foo]", spy.toString()); } interface Foo { @@ -167,14 +164,16 @@ interface Foo { @Test public void shouldAllowSpyingAnonymousClasses() { - //when - Foo spy = spy(new Foo() { - public String print() { - return "foo"; - } - }); - - //then + // when + Foo spy = + spy( + new Foo() { + public String print() { + return "foo"; + } + }); + + // then assertEquals("foo", spy.print()); } @@ -183,10 +182,14 @@ public void shouldSayNiceMessageWhenSpyingOnPrivateClass() throws Exception { List real = Arrays.asList("first", "second"); try { List spy = spy(real); - assumeTrue("Using inline mocks, it is possible to spy on private types", spy.getClass() != real.getClass()); + assumeTrue( + "Using inline mocks, it is possible to spy on private types", + spy.getClass() != real.getClass()); fail(); } catch (MockitoException e) { - assertThat(e).hasMessageContaining("Most likely it is due to mocking a private class that is not visible to Mockito"); + assertThat(e) + .hasMessageContaining( + "Most likely it is due to mocking a private class that is not visible to Mockito"); } } } diff --git a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java index 9591411647..e204784d0c 100644 --- a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java +++ b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java @@ -34,7 +34,9 @@ public void shouldShowActualAndExpectedWhenArgumentsAreDifferent() { verifyTheMock(1, "not foo"); fail(); } catch (ArgumentsAreDifferent e) { - assertThat(e).hasMessageContaining("callMethodOnMock(").hasMessageContaining("verifyTheMock("); + assertThat(e) + .hasMessageContaining("callMethodOnMock(") + .hasMessageContaining("verifyTheMock("); } } } diff --git a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesWhenFrameworkMisusedTest.java b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesWhenFrameworkMisusedTest.java index 5fc186e7fc..94ae0714d5 100644 --- a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesWhenFrameworkMisusedTest.java +++ b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesWhenFrameworkMisusedTest.java @@ -38,8 +38,8 @@ public void shouldPointOutMisplacedMatcher() { fail(); } catch (InvalidUseOfMatchersException e) { assertThat(e) - .hasMessageContaining("-> at ") - .hasMessageContaining("misplacedArgumentMatcherHere("); + .hasMessageContaining("-> at ") + .hasMessageContaining("misplacedArgumentMatcherHere("); } } @@ -57,8 +57,8 @@ public void shouldPointOutUnfinishedStubbing() { fail(); } catch (UnfinishedStubbingException e) { assertThat(e) - .hasMessageContaining("-> at ") - .hasMessageContaining("unfinishedStubbingHere("); + .hasMessageContaining("-> at ") + .hasMessageContaining("unfinishedStubbingHere("); } } diff --git a/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java b/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java index f57b024318..48aa3023bc 100644 --- a/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java +++ b/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java @@ -34,7 +34,7 @@ public void cleanStackTrace() { @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) @Test public void makeSureStateIsValidatedInTheVeryFirstTestThanksToTheRunner() { - //mess up the state: + // mess up the state: verify(mock); } diff --git a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java index 39b67bd804..4a2b7b75be 100644 --- a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java +++ b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java @@ -39,14 +39,17 @@ private void firstChunk() { mock.simpleMethod(1); mock.simpleMethod(1); } + private void secondChunk() { mockTwo.simpleMethod(2); mockTwo.simpleMethod(2); } + private void thirdChunk() { mock.simpleMethod(3); mock.simpleMethod(3); } + private void fourthChunk() { mockTwo.simpleMethod(4); mockTwo.simpleMethod(4); diff --git a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java index 3e17a8147f..a85252da07 100644 --- a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java +++ b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java @@ -18,7 +18,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//This is required to make sure stack trace is well filtered when runner is ON +// This is required to make sure stack trace is well filtered when runner is ON @RunWith(MockitoJUnitRunner.class) public class PointingStackTraceToActualInvocationInOrderTest extends TestBase { @@ -39,12 +39,15 @@ public void setup() { private void first() { mock.simpleMethod(1); } + private void second() { mockTwo.simpleMethod(2); } + private void third() { mock.simpleMethod(3); } + private void fourth() { mockTwo.simpleMethod(4); } diff --git a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java index 3ac3d9bb67..41c2f044b3 100644 --- a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java +++ b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationTest.java @@ -18,7 +18,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//This is required to make sure stack trace is well filtered when runner is ON +// This is required to make sure stack trace is well filtered when runner is ON @RunWith(MockitoJUnitRunner.class) public class PointingStackTraceToActualInvocationTest extends TestBase { @@ -36,12 +36,15 @@ public void setup() { private void first() { mock.simpleMethod(1); } + private void second() { mockTwo.simpleMethod(2); } + private void third() { mock.simpleMethod(3); } + private void fourth() { mockTwo.simpleMethod(4); } diff --git a/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java b/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java index 9b7df28705..ec3a7335eb 100644 --- a/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java +++ b/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java @@ -57,7 +57,10 @@ public void shouldFilterStackTraceOnVerifyNoMoreInteractions() { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { - Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyNoMoreInteractions")); + Assertions.assertThat(e) + .has( + firstMethodInStackTrace( + "shouldFilterStackTraceOnVerifyNoMoreInteractions")); } } @@ -68,7 +71,8 @@ public void shouldFilterStackTraceOnVerifyZeroInteractions() { verifyZeroInteractions(mock); fail(); } catch (NoInteractionsWanted e) { - Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyZeroInteractions")); + Assertions.assertThat(e) + .has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyZeroInteractions")); } } @@ -79,7 +83,8 @@ public void shouldFilterStackTraceOnVerifyNoInteractions() { verifyNoInteractions(mock); fail(); } catch (NoInteractionsWanted e) { - Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyNoInteractions")); + Assertions.assertThat(e) + .has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyNoInteractions")); } } @@ -91,7 +96,8 @@ public void shouldFilterStacktraceOnMockitoException() { verify(mock).oneArg(true); fail(); } catch (MockitoException expected) { - Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStacktraceOnMockitoException")); + Assertions.assertThat(expected) + .has(firstMethodInStackTrace("shouldFilterStacktraceOnMockitoException")); } } @@ -106,7 +112,8 @@ public void shouldFilterStacktraceWhenVerifyingInOrder() { inOrder.verify(mock).oneArg(true); fail(); } catch (VerificationInOrderFailure e) { - Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStacktraceWhenVerifyingInOrder")); + Assertions.assertThat(e) + .has(firstMethodInStackTrace("shouldFilterStacktraceWhenVerifyingInOrder")); } } @@ -116,7 +123,10 @@ public void shouldFilterStacktraceWhenInOrderThrowsMockitoException() { inOrder(); fail(); } catch (MockitoException expected) { - Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStacktraceWhenInOrderThrowsMockitoException")); + Assertions.assertThat(expected) + .has( + firstMethodInStackTrace( + "shouldFilterStacktraceWhenInOrderThrowsMockitoException")); } } @@ -127,7 +137,8 @@ public void shouldFilterStacktraceWhenInOrderVerifies() { inOrder.verify(null); fail(); } catch (MockitoException expected) { - Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStacktraceWhenInOrderVerifies")); + Assertions.assertThat(expected) + .has(firstMethodInStackTrace("shouldFilterStacktraceWhenInOrderVerifies")); } } @@ -137,7 +148,10 @@ public void shouldFilterStackTraceWhenThrowingExceptionFromMockHandler() { when(mock.oneArg(true)).thenThrow(new Exception()); fail(); } catch (MockitoException expected) { - Assertions.assertThat(expected).has(firstMethodInStackTrace("shouldFilterStackTraceWhenThrowingExceptionFromMockHandler")); + Assertions.assertThat(expected) + .has( + firstMethodInStackTrace( + "shouldFilterStackTraceWhenThrowingExceptionFromMockHandler")); } } @@ -149,7 +163,8 @@ public void shouldShowProperExceptionStackTrace() throws Exception { mock.simpleMethod(); fail(); } catch (RuntimeException e) { - Assertions.assertThat(e).has(firstMethodInStackTrace("shouldShowProperExceptionStackTrace")); + Assertions.assertThat(e) + .has(firstMethodInStackTrace("shouldShowProperExceptionStackTrace")); } } } diff --git a/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java b/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java index e98c26d925..e2f4b7eb8c 100644 --- a/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java +++ b/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java @@ -20,7 +20,10 @@ public class LenientMockAnnotationTest { public @Rule MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - @Mock(lenient = true) IMethods lenientMock; + + @Mock(lenient = true) + IMethods lenientMock; + @Mock IMethods regularMock; @Test @@ -28,14 +31,16 @@ public void mock_is_lenient() { when(lenientMock.simpleMethod("1")).thenReturn("1"); when(regularMock.simpleMethod("2")).thenReturn("2"); - //then lenient mock does not throw: + // then lenient mock does not throw: ProductionCode.simpleMethod(lenientMock, "3"); - //but regular mock throws: - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - ProductionCode.simpleMethod(regularMock,"4"); - } - }).isInstanceOf(PotentialStubbingProblem.class); + // but regular mock throws: + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + ProductionCode.simpleMethod(regularMock, "4"); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); } } diff --git a/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java b/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java index 635b59deca..9b468ffe83 100644 --- a/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java +++ b/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java @@ -30,18 +30,19 @@ public void setup() { @Test public void allows_stubbing_with_different_arg_in_test_code() { - //although we are calling 'simpleMethod' with different argument - //Mockito understands that this is stubbing in the test code and does not trigger PotentialStubbingProblem + // although we are calling 'simpleMethod' with different argument + // Mockito understands that this is stubbing in the test code and does not trigger + // PotentialStubbingProblem when(mock.simpleMethod("2")).thenReturn("2"); - //methods in anonymous inner classes are ok, too + // methods in anonymous inner classes are ok, too new Runnable() { public void run() { when(mock.simpleMethod("3")).thenReturn("3"); } }.run(); - //avoiding unnecessary stubbing failures: + // avoiding unnecessary stubbing failures: mock.simpleMethod("1"); mock.simpleMethod("2"); mock.simpleMethod("3"); @@ -49,11 +50,13 @@ public void run() { @Test public void reports_potential_stubbing_problem_in_production_code() { - //when - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - ProductionCode.simpleMethod(mock, "2"); - } - }).isInstanceOf(PotentialStubbingProblem.class); + // when + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + ProductionCode.simpleMethod(mock, "2"); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); } } diff --git a/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java b/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java index 010fa89a0b..fd1c05323f 100644 --- a/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java +++ b/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java @@ -28,7 +28,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -//TODO 792 also move other Strictness tests to this package (unless they already have good package) +// TODO 792 also move other Strictness tests to this package (unless they already have good package) public class StrictnessPerMockTest { MockitoSession mockito; @@ -37,7 +37,11 @@ public class StrictnessPerMockTest { @Before public void before() { - mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); + mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); assertNull(lenientMock); lenientMock = mock(IMethods.class, withSettings().lenient()); } @@ -50,62 +54,73 @@ public void knows_if_mock_is_lenient() { @Test public void potential_stubbing_problem() { - //when + // when given(lenientMock.simpleMethod(100)).willReturn("100"); given(strictStubsMock.simpleMethod(100)).willReturn("100"); - //then on lenient mock (created by hand), we can call the stubbed method with different arg: + // then on lenient mock (created by hand), we can call the stubbed method with different + // arg: lenientMock.simpleMethod(200); - //and on strict stub mock (created by session), we cannot call stubbed method with different arg: - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - ProductionCode.simpleMethod(strictStubsMock, 200); - } - }).isInstanceOf(PotentialStubbingProblem.class); + // and on strict stub mock (created by session), we cannot call stubbed method with + // different arg: + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + ProductionCode.simpleMethod(strictStubsMock, 200); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); } @Test public void unnecessary_stubbing() { - //when + // when given(lenientMock.simpleMethod(100)).willReturn("100"); given(strictStubsMock.simpleMethod(100)).willReturn("100"); - //then unnecessary stubbing flags method only on the strict stub mock: - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - mockito.finishMocking(); - } - }).isInstanceOf(UnnecessaryStubbingException.class) - .hasMessageContaining("1. -> ") - //good enough to prove that we're flagging just one unnecessary stubbing: - //TODO 792: let's make UnnecessaryStubbingException exception contain the Invocation instance - //so that we can write clean assertion rather than depending on string - .isNot(TestBase.hasMessageContaining("2. ->")); + // then unnecessary stubbing flags method only on the strict stub mock: + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + mockito.finishMocking(); + } + }) + .isInstanceOf(UnnecessaryStubbingException.class) + .hasMessageContaining("1. -> ") + // good enough to prove that we're flagging just one unnecessary stubbing: + // TODO 792: let's make UnnecessaryStubbingException exception contain the + // Invocation instance + // so that we can write clean assertion rather than depending on string + .isNot(TestBase.hasMessageContaining("2. ->")); } @Test public void verify_no_more_invocations() { - //when + // when given(lenientMock.simpleMethod(100)).willReturn("100"); given(strictStubsMock.simpleMethod(100)).willReturn("100"); - //and: + // and: strictStubsMock.simpleMethod(100); lenientMock.simpleMethod(100); - //then 'verifyNoMoreInteractions' ignores strict stub (implicitly verified) but flags the lenient mock - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - verifyNoMoreInteractions(strictStubsMock, lenientMock); - } - }).isInstanceOf(NoInteractionsWanted.class) - .hasMessageContaining("But found this interaction on mock 'iMethods'") - //TODO 792: let's make NoInteractionsWanted exception contain the Invocation instances - //so that we can write clean assertion rather than depending on string - .hasMessageContaining("Actually, above is the only interaction with this mock"); + // then 'verifyNoMoreInteractions' ignores strict stub (implicitly verified) but flags the + // lenient mock + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + verifyNoMoreInteractions(strictStubsMock, lenientMock); + } + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContaining("But found this interaction on mock 'iMethods'") + // TODO 792: let's make NoInteractionsWanted exception contain the Invocation + // instances + // so that we can write clean assertion rather than depending on string + .hasMessageContaining("Actually, above is the only interaction with this mock"); } @After diff --git a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java index 4a70467f8b..cc78e2ab8a 100644 --- a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java +++ b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java @@ -34,135 +34,155 @@ public class StrictnessPerStubbingTest { @Before public void before() { - mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); + mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); } @Test public void potential_stubbing_problem() { - //when + // when when(mock.simpleMethod("1")).thenReturn("1"); lenient().when(mock.differentMethod("2")).thenReturn("2"); - //then on lenient stubbing, we can call it with different argument: + // then on lenient stubbing, we can call it with different argument: mock.differentMethod("200"); - //but on strict stubbing, we cannot: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - ProductionCode.simpleMethod(mock, "100"); - } - }).isInstanceOf(PotentialStubbingProblem.class); + // but on strict stubbing, we cannot: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + ProductionCode.simpleMethod(mock, "100"); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); } @Test public void doReturn_syntax() { - //when - lenient().doReturn("2").doReturn("3") - .when(mock).simpleMethod(1); + // when + lenient().doReturn("2").doReturn("3").when(mock).simpleMethod(1); - //then on lenient stubbing, we can call it with different argument: + // then on lenient stubbing, we can call it with different argument: mock.simpleMethod(200); - //and stubbing works, too: + // and stubbing works, too: assertEquals("2", mock.simpleMethod(1)); assertEquals("3", mock.simpleMethod(1)); } @Test public void doReturn_varargs_syntax() { - //when - lenient().doReturn("2", "3") - .when(mock).simpleMethod(1); + // when + lenient().doReturn("2", "3").when(mock).simpleMethod(1); - //then on lenient stubbing, we can call it with different argument with no exception: + // then on lenient stubbing, we can call it with different argument with no exception: mock.simpleMethod(200); - //and stubbing works, too: + // and stubbing works, too: assertEquals("2", mock.simpleMethod(1)); assertEquals("3", mock.simpleMethod(1)); } @Test public void doThrow_syntax() { - //when + // when lenient() - .doThrow(IllegalArgumentException.class) - .doThrow(IllegalStateException.class) - .when(mock).simpleMethod(1); + .doThrow(IllegalArgumentException.class) + .doThrow(IllegalStateException.class) + .when(mock) + .simpleMethod(1); - //then on lenient stubbing, we can call it with different argument with no exception: + // then on lenient stubbing, we can call it with different argument with no exception: mock.simpleMethod(200); - //and stubbing works, too: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - mock.simpleMethod(1); - } - }).isInstanceOf(IllegalArgumentException.class); - - //testing consecutive call: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - mock.simpleMethod(1); - } - }).isInstanceOf(IllegalStateException.class); + // and stubbing works, too: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + mock.simpleMethod(1); + } + }) + .isInstanceOf(IllegalArgumentException.class); + + // testing consecutive call: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + mock.simpleMethod(1); + } + }) + .isInstanceOf(IllegalStateException.class); } @Test public void doThrow_vararg_syntax() { - //when + // when lenient() - .doThrow(IllegalArgumentException.class, IllegalStateException.class) - .when(mock).simpleMethod(1); + .doThrow(IllegalArgumentException.class, IllegalStateException.class) + .when(mock) + .simpleMethod(1); - //then on lenient stubbing, we can call it with different argument with no exception: + // then on lenient stubbing, we can call it with different argument with no exception: mock.simpleMethod(200); - //and stubbing works, too: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - mock.simpleMethod(1); - } - }).isInstanceOf(IllegalArgumentException.class); - - //testing consecutive call: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - mock.simpleMethod(1); - } - }).isInstanceOf(IllegalStateException.class); + // and stubbing works, too: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + mock.simpleMethod(1); + } + }) + .isInstanceOf(IllegalArgumentException.class); + + // testing consecutive call: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + mock.simpleMethod(1); + } + }) + .isInstanceOf(IllegalStateException.class); } @Test public void doThrow_instance_vararg_syntax() { - //when + // when lenient() - .doThrow(new IllegalArgumentException(), new IllegalStateException()) - .when(mock).simpleMethod(1); + .doThrow(new IllegalArgumentException(), new IllegalStateException()) + .when(mock) + .simpleMethod(1); - //then on lenient stubbing, we can call it with different argument with no exception: + // then on lenient stubbing, we can call it with different argument with no exception: mock.simpleMethod(200); - //and stubbing works, too: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - mock.simpleMethod(1); - } - }).isInstanceOf(IllegalArgumentException.class); - - //testing consecutive call: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() throws Throwable { - mock.simpleMethod(1); - } - }).isInstanceOf(IllegalStateException.class); + // and stubbing works, too: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + mock.simpleMethod(1); + } + }) + .isInstanceOf(IllegalArgumentException.class); + + // testing consecutive call: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() throws Throwable { + mock.simpleMethod(1); + } + }) + .isInstanceOf(IllegalStateException.class); } static class Counter { int increment(int x) { return x + 1; } + void scream(String message) { throw new RuntimeException(message); } @@ -170,97 +190,104 @@ void scream(String message) { @Test public void doCallRealMethod_syntax() { - //when + // when Counter mock = mock(Counter.class); lenient().doCallRealMethod().when(mock).increment(1); - //then no exception and default return value if we call it with different arg: + // then no exception and default return value if we call it with different arg: assertEquals(0, mock.increment(0)); - //and real method is called when using correct arg: + // and real method is called when using correct arg: assertEquals(2, mock.increment(1)); } @Test public void doNothing_syntax() { - //when + // when final Counter spy = spy(Counter.class); lenient().doNothing().when(spy).scream("1"); - //then no stubbing exception and real method is called if we call stubbed method with different arg: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - spy.scream("2"); - } - }).hasMessage("2"); - - //and we do nothing when stubbing called with correct arg: + // then no stubbing exception and real method is called if we call stubbed method with + // different arg: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + spy.scream("2"); + } + }) + .hasMessage("2"); + + // and we do nothing when stubbing called with correct arg: spy.scream("1"); } @Test public void doAnswer_syntax() { - //when + // when lenient().doAnswer(AdditionalAnswers.returnsFirstArg()).when(mock).simpleMethod("1"); - //then on lenient stubbing, we can call it with different argument: + // then on lenient stubbing, we can call it with different argument: mock.simpleMethod("200"); - //and stubbing works, too: + // and stubbing works, too: assertEquals("1", mock.simpleMethod("1")); } @Test public void unnecessary_stubbing() { - //when + // when when(mock.simpleMethod("1")).thenReturn("1"); lenient().when(mock.differentMethod("2")).thenReturn("2"); - //then unnecessary stubbing flags method only on the strict stubbing: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - mockito.finishMocking(); - } - }).isInstanceOf(UnnecessaryStubbingException.class) - .hasMessageContaining("1. -> ") - //good enough to prove that we're flagging just one unnecessary stubbing: - //TODO 792: this assertion is duplicated with StrictnessPerMockTest - .isNot(TestBase.hasMessageContaining("2. ->")); + // then unnecessary stubbing flags method only on the strict stubbing: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + mockito.finishMocking(); + } + }) + .isInstanceOf(UnnecessaryStubbingException.class) + .hasMessageContaining("1. -> ") + // good enough to prove that we're flagging just one unnecessary stubbing: + // TODO 792: this assertion is duplicated with StrictnessPerMockTest + .isNot(TestBase.hasMessageContaining("2. ->")); } @Test public void unnecessary_stubbing_with_doReturn() { - //when + // when lenient().doReturn("2").when(mock).differentMethod("2"); - //then no exception is thrown: + // then no exception is thrown: mockito.finishMocking(); } @Test public void verify_no_more_invocations() { - //when + // when when(mock.simpleMethod("1")).thenReturn("1"); lenient().when(mock.differentMethod("2")).thenReturn("2"); - //and: + // and: mock.simpleMethod("1"); mock.differentMethod("200"); // <- different arg - //then 'verifyNoMoreInteractions' flags the lenient stubbing (called with different arg) - //and reports it with [?] in the exception message - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - verifyNoMoreInteractions(mock); - } - }).isInstanceOf(NoInteractionsWanted.class) - .hasMessageContaining("1. ->") - .hasMessageContaining("2. [?]->"); - //TODO 792: assertion duplicated with StrictnessPerMockTest - // and we should use assertions based on content of the exception rather than the string + // then 'verifyNoMoreInteractions' flags the lenient stubbing (called with different arg) + // and reports it with [?] in the exception message + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + verifyNoMoreInteractions(mock); + } + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContaining("1. ->") + .hasMessageContaining("2. [?]->"); + // TODO 792: assertion duplicated with StrictnessPerMockTest + // and we should use assertions based on content of the exception rather than the string } @After diff --git a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java index aea447e679..b8a5dc4a38 100644 --- a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java +++ b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java @@ -23,27 +23,29 @@ public class StrictnessPerStubbingWithRunnerTest { @Test public void potential_stubbing_problem() { - //when + // when when(mock.simpleMethod("1")).thenReturn("1"); lenient().when(mock.differentMethod("2")).thenReturn("2"); - //then on lenient stubbing, we can call it with different argument: + // then on lenient stubbing, we can call it with different argument: mock.differentMethod("200"); - //but on strict stubbing, we cannot: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - ProductionCode.simpleMethod(mock, "100"); - } - }).isInstanceOf(PotentialStubbingProblem.class); + // but on strict stubbing, we cannot: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + ProductionCode.simpleMethod(mock, "100"); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); - //let's use the strict stubbing so that it is not reported as failure by the runner: + // let's use the strict stubbing so that it is not reported as failure by the runner: mock.simpleMethod("1"); } @Test public void unnecessary_stubbing() { - //this unnecessary stubbing is not flagged by the runner: + // this unnecessary stubbing is not flagged by the runner: lenient().when(mock.differentMethod("2")).thenReturn("2"); } } diff --git a/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java b/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java index afacfaa246..c1081278cb 100644 --- a/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java +++ b/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java @@ -27,18 +27,20 @@ public class StrictnessWhenRuleStrictnessIsUpdatedTest { @Test public void strictness_per_mock() { - //when + // when rule.strictness(Strictness.STRICT_STUBS); - //then previous mock is strict: + // then previous mock is strict: when(mock.simpleMethod(1)).thenReturn("1"); - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - ProductionCode.simpleMethod(mock, 2); - } - }).isInstanceOf(PotentialStubbingProblem.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + ProductionCode.simpleMethod(mock, 2); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); - //but the new mock is lenient, even though the rule is not: + // but the new mock is lenient, even though the rule is not: final IMethods lenientMock = mock(IMethods.class, withSettings().lenient()); when(lenientMock.simpleMethod(1)).thenReturn("1"); lenientMock.simpleMethod(100); @@ -46,18 +48,20 @@ public void call() { @Test public void strictness_per_stubbing() { - //when + // when rule.strictness(Strictness.STRICT_STUBS); - //then previous mock is strict: + // then previous mock is strict: when(mock.simpleMethod(1)).thenReturn("1"); - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - ProductionCode.simpleMethod(mock, 2); - } - }).isInstanceOf(PotentialStubbingProblem.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + ProductionCode.simpleMethod(mock, 2); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); - //but the new mock is lenient, even though the rule is not: + // but the new mock is lenient, even though the rule is not: lenient().when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(100); } diff --git a/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java b/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java index 9af022008e..1bc9574e71 100644 --- a/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java +++ b/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java @@ -25,27 +25,29 @@ public class StrictnessWithRulesTest { @Test public void potential_stubbing_problem() { - //when + // when when(mock.simpleMethod("1")).thenReturn("1"); lenient().when(mock.differentMethod("2")).thenReturn("2"); - //then on lenient stubbing, we can call it with different argument: + // then on lenient stubbing, we can call it with different argument: mock.differentMethod("200"); - //but on strict stubbing, we cannot: - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - ProductionCode.simpleMethod(mock, "100"); - } - }).isInstanceOf(PotentialStubbingProblem.class); + // but on strict stubbing, we cannot: + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + ProductionCode.simpleMethod(mock, "100"); + } + }) + .isInstanceOf(PotentialStubbingProblem.class); - //let's use the strict stubbing so that it is not reported as failure by the rule: + // let's use the strict stubbing so that it is not reported as failure by the rule: mock.simpleMethod("1"); } @Test public void unnecessary_stubbing() { - //this unnecessary stubbing is not flagged by the rule: + // this unnecessary stubbing is not flagged by the rule: lenient().when(mock.differentMethod("2")).thenReturn("2"); } } diff --git a/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java b/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java index 022cadc64d..375a204d51 100644 --- a/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java +++ b/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java @@ -33,7 +33,8 @@ public void should_evaluate_latest_stubbing_first() throws Exception { assertEquals(200, mock.objectReturningMethod(200)); assertEquals(100, mock.objectReturningMethod(666)); - assertEquals("default behavior should return null", null, mock.objectReturningMethod("blah")); + assertEquals( + "default behavior should return null", null, mock.objectReturningMethod("blah")); } @Test @@ -45,7 +46,8 @@ public void should_stubbing_be_treated_as_interaction() throws Exception { try { verifyNoMoreInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -79,9 +81,10 @@ public void unfinished_stubbing_cleans_up_the_state() { try { when("").thenReturn(""); fail(); - } catch (MissingMethodInvocationException e) {} + } catch (MissingMethodInvocationException e) { + } - //anything that can cause state validation + // anything that can cause state validation verifyZeroInteractions(mock); } @@ -91,9 +94,10 @@ public void unfinished_stubbing_cleans_up_the_state_verify_no_interactions() { try { when("").thenReturn(""); fail(); - } catch (MissingMethodInvocationException e) {} + } catch (MissingMethodInvocationException e) { + } - //anything that can cause state validation + // anything that can cause state validation verifyNoInteractions(mock); } @@ -127,12 +131,16 @@ public void test_stub_only_not_verifiable() throws Exception { assertEquals(200, localMock.objectReturningMethod(200)); assertEquals(100, localMock.objectReturningMethod(666)); - assertEquals("default behavior should return null", null, localMock.objectReturningMethod("blah")); + assertEquals( + "default behavior should return null", + null, + localMock.objectReturningMethod("blah")); try { verify(localMock, atLeastOnce()).objectReturningMethod(eq(200)); fail(); - } catch (CannotVerifyStubOnlyMock e) {} + } catch (CannotVerifyStubOnlyMock e) { + } } @SuppressWarnings("MockitoUsage") @@ -144,9 +152,11 @@ public void test_stub_only_not_verifiable_fail_fast() { verify(localMock); // throws exception before method invocation fail(); } catch (CannotVerifyStubOnlyMock e) { - assertEquals("\n" + - "Argument \"iMethods\" passed to verify is a stubOnly() mock which cannot be verified.\n" + - "If you intend to verify invocations on this mock, don't use stubOnly() in its MockSettings.", e.getMessage()); + assertEquals( + "\n" + + "Argument \"iMethods\" passed to verify is a stubOnly() mock which cannot be verified.\n" + + "If you intend to verify invocations on this mock, don't use stubOnly() in its MockSettings.", + e.getMessage()); } } @@ -157,7 +167,8 @@ public void test_stub_only_not_verifiable_verify_no_more_interactions() { try { verifyNoMoreInteractions(localMock); fail(); - } catch (CannotVerifyStubOnlyMock e) {} + } catch (CannotVerifyStubOnlyMock e) { + } } @Test @@ -167,6 +178,7 @@ public void test_stub_only_not_verifiable_in_order() { try { inOrder(localMock); fail(); - } catch (CannotVerifyStubOnlyMock e) {} + } catch (CannotVerifyStubOnlyMock e) { + } } } diff --git a/src/test/java/org/mockitousage/stubbing/CallingRealMethodTest.java b/src/test/java/org/mockitousage/stubbing/CallingRealMethodTest.java index 43917d120a..333661df33 100644 --- a/src/test/java/org/mockitousage/stubbing/CallingRealMethodTest.java +++ b/src/test/java/org/mockitousage/stubbing/CallingRealMethodTest.java @@ -13,8 +13,7 @@ public class CallingRealMethodTest extends TestBase { - @Mock - TestedObject mock; + @Mock TestedObject mock; static class TestedObject { diff --git a/src/test/java/org/mockitousage/stubbing/CloningParameterTest.java b/src/test/java/org/mockitousage/stubbing/CloningParameterTest.java index 465bd21c85..000f76666d 100644 --- a/src/test/java/org/mockitousage/stubbing/CloningParameterTest.java +++ b/src/test/java/org/mockitousage/stubbing/CloningParameterTest.java @@ -55,14 +55,14 @@ public void shouldCloneArrays() throws Exception { EmailSender emailSender = mock(EmailSender.class, new ClonesArguments()); // 1. Pass an array into a mock that "ClonesArguments" - Person[] ccList = new Person[] { new Person("Wes") }; + Person[] ccList = new Person[] {new Person("Wes")}; emailSender.sendGroupEmail(1, ccList); // 2. Mutate the array ccList[0] = new Person("Joe"); // 3. Verify that the mock made a copy of the array - verify(emailSender).sendGroupEmail(1, new Person[] { new Person("Wes") }); + verify(emailSender).sendGroupEmail(1, new Person[] {new Person("Wes")}); } @Test @@ -71,10 +71,10 @@ public void shouldNotThrowNPEWhenCloningNulls() throws Exception { EmailSender emailSender = mock(EmailSender.class, new ClonesArguments()); // 1. Pass a null into a mock that "ClonesArguments" - emailSender.sendEmail(1, (Person)null); + emailSender.sendEmail(1, (Person) null); // 2. Verify that the null argument was captured - verify(emailSender).sendEmail(eq(1), (Person)isNull()); + verify(emailSender).sendEmail(eq(1), (Person) isNull()); } public class Person { @@ -102,29 +102,21 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Person other = (Person) obj; - if (!getOuterType().equals(other.getOuterType())) - return false; - if (emailSent != other.emailSent) - return false; + if (!getOuterType().equals(other.getOuterType())) return false; + if (emailSent != other.emailSent) return false; if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; return true; } private CloningParameterTest getOuterType() { return CloningParameterTest.this; } - } public interface EmailSender { @@ -134,6 +126,5 @@ public interface EmailSender { void sendGroupEmail(int i, Person[] persons); List getAllEmails(Person person); - } } diff --git a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java index d1297a059e..5e39714cfd 100644 --- a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java +++ b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java @@ -27,7 +27,6 @@ import org.mockito.exceptions.verification.TooManyActualInvocations; import org.mockitoutil.TestBase; - public class DeepStubbingTest extends TestBase { static class Person { @@ -167,7 +166,7 @@ public void withArguments() throws Exception { public void withAnyPatternArguments() throws Exception { OutputStream out = new ByteArrayOutputStream(); - //TODO: should not use javax in case it changes + // TODO: should not use javax in case it changes SocketFactory sf = mock(SocketFactory.class, RETURNS_DEEP_STUBS); when(sf.createSocket(anyString(), anyInt()).getOutputStream()).thenReturn(out); @@ -232,8 +231,8 @@ public void unnamed_to_string() { @Test public void named_to_string() { - MockSettings settings = withSettings().name("name of mock") - .defaultAnswer(RETURNS_DEEP_STUBS); + MockSettings settings = + withSettings().name("name of mock").defaultAnswer(RETURNS_DEEP_STUBS); SocketFactory sf = mock(SocketFactory.class, settings); assertEquals("name of mock", sf.toString()); } @@ -242,32 +241,32 @@ public void named_to_string() { @Test public void shouldStubbingBasicallyWorkFine() { - //given + // given given(person.getAddress().getStreet().getName()).willReturn("Norymberska"); - //when + // when String street = person.getAddress().getStreet().getName(); - //then + // then assertEquals("Norymberska", street); } @Test public void shouldVerificationBasicallyWorkFine() { - //given + // given person.getAddress().getStreet().getName(); - //then + // then verify(person.getAddress().getStreet()).getName(); } @Test public void verification_work_with_argument_Matchers_in_nested_calls() { - //given + // given person.getAddress("111 Mock Lane").getStreet(); person.getAddress("111 Mock Lane").getStreet(Locale.ITALIAN).getName(); - //then + // then verify(person.getAddress(anyString())).getStreet(); verify(person.getAddress(anyString()).getStreet(Locale.CHINESE), never()).getName(); verify(person.getAddress(anyString()).getStreet(eq(Locale.ITALIAN))).getName(); @@ -279,11 +278,21 @@ public void deep_stub_return_same_mock_instance_if_invocation_matchers_matches() person.getAddress("the docks").getStreet().getName(); - assertSame(person.getAddress("the docks").getStreet(), person.getAddress(anyString()).getStreet()); - assertSame(person.getAddress(anyString()).getStreet(), person.getAddress(anyString()).getStreet()); - assertSame(person.getAddress("the docks").getStreet(), person.getAddress("the docks").getStreet()); - assertSame(person.getAddress(anyString()).getStreet(), person.getAddress("the docks").getStreet()); - assertSame(person.getAddress("111 Mock Lane").getStreet(), person.getAddress("the docks").getStreet()); + assertSame( + person.getAddress("the docks").getStreet(), + person.getAddress(anyString()).getStreet()); + assertSame( + person.getAddress(anyString()).getStreet(), + person.getAddress(anyString()).getStreet()); + assertSame( + person.getAddress("the docks").getStreet(), + person.getAddress("the docks").getStreet()); + assertSame( + person.getAddress(anyString()).getStreet(), + person.getAddress("the docks").getStreet()); + assertSame( + person.getAddress("111 Mock Lane").getStreet(), + person.getAddress("the docks").getStreet()); } @Test @@ -300,7 +309,6 @@ public void times_never_atLeast_atMost_verificationModes_should_work() { verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atMostOnce()).getName(); } - @Test public void inOrder_only_work_on_the_very_last_mock_but_it_works() { when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep"); @@ -312,14 +320,15 @@ public void inOrder_only_work_on_the_very_last_mock_but_it_works() { person.getAddress("the docks").getStreet(Locale.ITALIAN).getName(); person.getAddress("the docks").getStreet(Locale.CHINESE).getName(); - InOrder inOrder = inOrder( - person.getAddress("the docks").getStreet(), - person.getAddress("the docks").getStreet(Locale.CHINESE), - person.getAddress("the docks").getStreet(Locale.ITALIAN) - ); + InOrder inOrder = + inOrder( + person.getAddress("the docks").getStreet(), + person.getAddress("the docks").getStreet(Locale.CHINESE), + person.getAddress("the docks").getStreet(Locale.ITALIAN)); inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName(); inOrder.verify(person.getAddress("the docks").getStreet()).getLongName(); - inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName(); + inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)) + .getName(); inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName(); } @@ -338,19 +347,17 @@ public void verificationMode_only_work_on_the_last_returned_mock() { verify(person.getAddress("the docks"), times(1)).getStreet(); fail(); } catch (TooManyActualInvocations e) { - assertThat(e.getMessage()) - .contains("Wanted 1 time") - .contains("But was 3 times"); + assertThat(e.getMessage()).contains("Wanted 1 time").contains("But was 3 times"); } } @Test public void shouldFailGracefullyWhenClassIsFinal() { - //when + // when FinalClass value = new FinalClass(); given(person.getFinalClass()).willReturn(value); - //then + // then assertEquals(value, person.getFinalClass()); } @@ -369,5 +376,4 @@ public void deep_stub_does_not_stack_overflow_on_reversed_generics() { assertThat(mock.reverse().finalMethod()).isEqualTo(5L); } - } diff --git a/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java b/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java index c799d618d4..556bc56368 100644 --- a/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java +++ b/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java @@ -15,21 +15,19 @@ public class MisusingStubbingTest extends TestBase { @Test public void clean_state_after_not_a_mock() { - //when - assertThatThrownBy(() -> - doReturn(100).when("not a mock")); + // when + assertThatThrownBy(() -> doReturn(100).when("not a mock")); - //then + // then validateMockitoUsage(); } @Test public void clean_state_after_null_passed() { - //when - assertThatThrownBy(() -> - doReturn(100).when(null)); + // when + assertThatThrownBy(() -> doReturn(100).when(null)); - //then + // then validateMockitoUsage(); } } diff --git a/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java b/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java index 277c6a19c5..38f5ff6821 100644 --- a/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java +++ b/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java @@ -11,62 +11,68 @@ import org.junit.Test; import org.mockito.Answers; -//Reproduces issue #1551 +// Reproduces issue #1551 public class SmartNullsGenericBugTest { @Test public void smart_nulls_generic_bug_generic_T() { - ConcreteDao concreteDao = mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); + ConcreteDao concreteDao = + mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); final Entity result = concreteDao.findById(); - Assertions.assertThat(result) - .as("#1551") - .isNotNull(); + Assertions.assertThat(result).as("#1551").isNotNull(); } @Test public void smart_nulls_generic_bug_generic_M() { - ConcreteDao concreteDao = mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); + ConcreteDao concreteDao = + mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); final String other = concreteDao.find(); - Assertions.assertThat(other) - .as("#1551 - CCannot resolve type") - .isNull(); + Assertions.assertThat(other).as("#1551 - CCannot resolve type").isNull(); } @Test public void smart_nulls_generic_bug_generic_M_provided_in_args() { - ConcreteDao concreteDao = mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); + ConcreteDao concreteDao = + mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); final String other = concreteDao.findArgs(1, "plop"); - Assertions.assertThat(other) - .as("#1551") - .isEqualTo(""); + Assertions.assertThat(other).as("#1551").isEqualTo(""); } @Test public void smart_nulls_generic_bug_generic_M_provided_as_varargs() { - ConcreteDao concreteDao = mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); + ConcreteDao concreteDao = + mock(ConcreteDao.class, withSettings().defaultAnswer(Answers.RETURNS_SMART_NULLS)); final String other = concreteDao.findVarargs(42, "plip", "plop"); - Assertions.assertThat(other) - .as("#1551") - .isEqualTo(""); + Assertions.assertThat(other).as("#1551").isEqualTo(""); } static class AbstractDao { T findById() { return null; } - M find() { return null; } - M findArgs(int idx, M arg) { return null; } - M findVarargs(int idx, M... args) { return null; } + + M find() { + return null; + } + + M findArgs(int idx, M arg) { + return null; + } + + M findVarargs(int idx, M... args) { + return null; + } } - static class Entity { } - static class ConcreteDao extends AbstractDao { } + static class Entity {} + + static class ConcreteDao extends AbstractDao {} } diff --git a/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java b/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java index 304d062a31..9f129cc11e 100644 --- a/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java +++ b/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java @@ -67,7 +67,9 @@ Bar getBarWithParams(int x, String y) { return null; } - T returnsFromArg(T arg) { return arg; } + T returnsFromArg(T arg) { + return arg; + } void boo() {} } @@ -79,7 +81,8 @@ public void shouldThrowSmartNPEWhenMethodReturnsClass() throws Exception { try { foo.boo(); fail(); - } catch (SmartNullPointerException e) {} + } catch (SmartNullPointerException e) { + } } @Test @@ -89,10 +92,10 @@ public void shouldThrowSmartNPEWhenMethodReturnsInterface() throws Exception { try { bar.boo(); fail(); - } catch (SmartNullPointerException e) {} + } catch (SmartNullPointerException e) { + } } - @Test public void shouldReturnOrdinaryEmptyValuesForOrdinaryTypes() throws Exception { IMethods mock = mock(IMethods.class, RETURNS_SMART_NULLS); @@ -109,7 +112,8 @@ public void shouldNotThrowSmartNullPointerOnToString() { try { verify(mock).simpleMethod(smartNull); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } @Test @@ -134,7 +138,8 @@ public void shouldShowParameters() { @Test public void shouldShowParametersWhenParamsAreHuge() { Foo foo = mock(Foo.class, RETURNS_SMART_NULLS); - String longStr = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; + String longStr = + "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; Bar smartNull = foo.getBarWithParams(10, longStr); try { diff --git a/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java b/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java index 2abbb4f90a..71ae85727d 100644 --- a/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java +++ b/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java @@ -30,50 +30,65 @@ public class StrictStubbingEndToEndTest { JUnitCore junit = new JUnitCore(); - @After public void after() { + @After + public void after() { new StateMaster().clearMockitoListeners(); } - @Test public void finish_mocking_exception_does_not_hide_the_exception_from_test() { + @Test + public void finish_mocking_exception_does_not_hide_the_exception_from_test() { Result result = junit.run(UnnecessaryStubbing.class); assertThat(result) - //both exceptions are reported to JUnit: + // both exceptions are reported to JUnit: .fails("unnecessary_stubbing", IllegalStateException.class) .fails("unnecessary_stubbing", UnnecessaryStubbingException.class); } - @Test public void does_not_report_unused_stubbing_if_mismatch_reported() { + @Test + public void does_not_report_unused_stubbing_if_mismatch_reported() { Result result = junit.run(ReportMismatchButNotUnusedStubbing.class); assertThat(result).fails(1, PotentialStubbingProblem.class); } - @Test public void strict_stubbing_does_not_leak_to_other_tests() { - Result result = junit.run(LenientStrictness1.class, StrictStubsPassing.class, LenientStrictness2.class); - //all tests pass, lenient test cases contain incorrect stubbing + @Test + public void strict_stubbing_does_not_leak_to_other_tests() { + Result result = + junit.run( + LenientStrictness1.class, + StrictStubsPassing.class, + LenientStrictness2.class); + // all tests pass, lenient test cases contain incorrect stubbing assertThat(result).succeeds(5); } - @Test public void detects_unfinished_session() { + @Test + public void detects_unfinished_session() { Result result = junit.run(UnfinishedMocking.class); assertThat(result) - .fails(UnfinishedMockingSessionException.class, "\n" + - "Unfinished mocking session detected.\n" + - "Previous MockitoSession was not concluded with 'finishMocking()'.\n" + - "For examples of correct usage see javadoc for MockitoSession class."); + .fails( + UnfinishedMockingSessionException.class, + "\n" + + "Unfinished mocking session detected.\n" + + "Previous MockitoSession was not concluded with 'finishMocking()'.\n" + + "For examples of correct usage see javadoc for MockitoSession class."); } - @Test public void concurrent_sessions_in_different_threads() throws Exception { + @Test + public void concurrent_sessions_in_different_threads() throws Exception { final Map results = new ConcurrentHashMap(); - concurrently(new Runnable() { - public void run() { - results.put(StrictStubsPassing.class, junit.run(StrictStubsPassing.class)); - } - }, new Runnable() { - public void run() { - results.put(ReportMismatchButNotUnusedStubbing.class, junit.run(ReportMismatchButNotUnusedStubbing.class)); - } - } - ); + concurrently( + new Runnable() { + public void run() { + results.put(StrictStubsPassing.class, junit.run(StrictStubsPassing.class)); + } + }, + new Runnable() { + public void run() { + results.put( + ReportMismatchButNotUnusedStubbing.class, + junit.run(ReportMismatchButNotUnusedStubbing.class)); + } + }); assertThat(results.get(StrictStubsPassing.class)).succeeds(1); assertThat(results.get(ReportMismatchButNotUnusedStubbing.class)).fails(1); @@ -81,13 +96,19 @@ public void run() { public static class UnnecessaryStubbing { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); - - @After public void after() { + MockitoSession mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); + + @After + public void after() { mockito.finishMocking(); } - @Test public void unnecessary_stubbing() { + @Test + public void unnecessary_stubbing() { given(mock.simpleMethod("1")).willReturn("one"); throw new IllegalStateException(); } @@ -95,13 +116,19 @@ public static class UnnecessaryStubbing { public static class ReportMismatchButNotUnusedStubbing { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); - - @After public void after() { + MockitoSession mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); + + @After + public void after() { mockito.finishMocking(); } - @Test public void mismatch() { + @Test + public void mismatch() { given(mock.simpleMethod(1)).willReturn(""); ProductionCode.simpleMethod(mock, 2); } @@ -109,13 +136,19 @@ public static class ReportMismatchButNotUnusedStubbing { public static class StrictStubsPassing { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); - - @After public void after() { + MockitoSession mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); + + @After + public void after() { mockito.finishMocking(); } - @Test public void used() { + @Test + public void used() { given(mock.simpleMethod(1)).willReturn(""); mock.simpleMethod(1); } @@ -124,11 +157,13 @@ public static class StrictStubsPassing { public static class LenientStrictness1 { @Mock IMethods mock = Mockito.mock(IMethods.class); - @Test public void unused() { + @Test + public void unused() { given(mock.simpleMethod(1)).willReturn(""); } - @Test public void mismatch() { + @Test + public void mismatch() { given(mock.simpleMethod(2)).willReturn(""); mock.simpleMethod(3); } @@ -137,11 +172,13 @@ public static class LenientStrictness1 { public static class LenientStrictness2 { @Mock IMethods mock = Mockito.mock(IMethods.class); - @Test public void unused() { + @Test + public void unused() { given(mock.simpleMethod(1)).willReturn(""); } - @Test public void mismatch() { + @Test + public void mismatch() { given(mock.simpleMethod(2)).willReturn(""); mock.simpleMethod(3); } @@ -149,13 +186,19 @@ public static class LenientStrictness2 { public static class UnfinishedMocking { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); - - @Test public void unused() { + MockitoSession mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); + + @Test + public void unused() { given(mock.simpleMethod("1")).willReturn("one"); } - @Test public void unused2() { + @Test + public void unused2() { given(mock.simpleMethod("1")).willReturn("one"); } } diff --git a/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java b/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java index 96e6a9f346..dfc0323e26 100644 --- a/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java +++ b/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java @@ -25,78 +25,96 @@ public class StrictStubbingTest { @Mock IMethods mock; - MockitoSession mockito = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); - - @After public void after() { - //Some tests already invoke below but that's ok + MockitoSession mockito = + Mockito.mockitoSession() + .initMocks(this) + .strictness(Strictness.STRICT_STUBS) + .startMocking(); + + @After + public void after() { + // Some tests already invoke below but that's ok mockito.finishMocking(); } - @Test public void no_interactions() throws Throwable { - //expect no exception + @Test + public void no_interactions() throws Throwable { + // expect no exception mockito.finishMocking(); } - @Test public void few_interactions() throws Throwable { + @Test + public void few_interactions() throws Throwable { mock.simpleMethod(100); mock.otherMethod(); } - @Test public void few_verified_interactions() throws Throwable { - //when + @Test + public void few_verified_interactions() throws Throwable { + // when mock.simpleMethod(100); mock.otherMethod(); - //and + // and verify(mock).simpleMethod(100); verify(mock).otherMethod(); verifyNoMoreInteractions(mock); } - @Test public void stubbed_method_is_implicitly_verified() throws Throwable { - //when + @Test + public void stubbed_method_is_implicitly_verified() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(100); - //no exceptions: + // no exceptions: verifyNoMoreInteractions(mock); } - @Test public void unused_stubbed_is_not_implicitly_verified() throws Throwable { - //when + @Test + public void unused_stubbed_is_not_implicitly_verified() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(100); // <- implicitly verified mock.simpleMethod(200); // <- unverified - //expect - assertThat(new Runnable() { - public void run() { - verifyNoMoreInteractions(mock); - } - }).throwsException(NoInteractionsWanted.class); + // expect + assertThat( + new Runnable() { + public void run() { + verifyNoMoreInteractions(mock); + } + }) + .throwsException(NoInteractionsWanted.class); } - @Test public void stubbing_argument_mismatch() throws Throwable { - //when + @Test + public void stubbing_argument_mismatch() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); - //stubbing argument mismatch is detected - assertThat(new Runnable() { - public void run() { - ProductionCode.simpleMethod(mock, 200); - } - }).throwsException(PotentialStubbingProblem.class); + // stubbing argument mismatch is detected + assertThat( + new Runnable() { + public void run() { + ProductionCode.simpleMethod(mock, 200); + } + }) + .throwsException(PotentialStubbingProblem.class); } - @Test public void unused_stubbing() throws Throwable { - //when + @Test + public void unused_stubbing() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); - //unused stubbing is reported - assertThat(new Runnable() { - public void run() { - mockito.finishMocking(); - } - }).throwsException(UnnecessaryStubbingException.class); + // unused stubbing is reported + assertThat( + new Runnable() { + public void run() { + mockito.finishMocking(); + } + }) + .throwsException(UnnecessaryStubbingException.class); } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java index 863b7a88b4..6098805e1c 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java @@ -15,15 +15,11 @@ public class StubbingConsecutiveAnswersTest extends TestBase { - @Mock - private IMethods mock; + @Mock private IMethods mock; @Test public void should_return_consecutive_values() throws Exception { - when(mock.simpleMethod()) - .thenReturn("one") - .thenReturn("two") - .thenReturn("three"); + when(mock.simpleMethod()).thenReturn("one").thenReturn("two").thenReturn("three"); assertEquals("one", mock.simpleMethod()); assertEquals("two", mock.simpleMethod()); @@ -69,7 +65,8 @@ public void should_return_consecutive_values_var_args_contain_null() throws Exce } @Test - public void should_return_consecutive_values_set_by_shorten_then_return_method() throws Exception { + public void should_return_consecutive_values_set_by_shorten_then_return_method() + throws Exception { when(mock.simpleMethod()).thenReturn("one", "two", "three"); assertEquals("one", mock.simpleMethod()); @@ -80,12 +77,14 @@ public void should_return_consecutive_values_set_by_shorten_then_return_method() } @Test - public void should_return_consecutive_value_and_throw_exceptions_set_by_shorten_return_methods() { - when(mock.simpleMethod()).thenReturn("zero") - .thenReturn("one", "two") - .thenThrow(new NullPointerException(), new RuntimeException()) - .thenReturn("three") - .thenThrow(new IllegalArgumentException()); + public void + should_return_consecutive_value_and_throw_exceptions_set_by_shorten_return_methods() { + when(mock.simpleMethod()) + .thenReturn("zero") + .thenReturn("one", "two") + .thenThrow(new NullPointerException(), new RuntimeException()) + .thenReturn("three") + .thenThrow(new IllegalArgumentException()); assertEquals("zero", mock.simpleMethod()); assertEquals("one", mock.simpleMethod()); @@ -93,70 +92,84 @@ public void should_return_consecutive_value_and_throw_exceptions_set_by_shorten_ try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } try { mock.simpleMethod(); fail(); - } catch (RuntimeException expected) { } + } catch (RuntimeException expected) { + } assertEquals("three", mock.simpleMethod()); try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } } @Test public void should_throw_consecutively() throws Exception { - when(mock.simpleMethod()).thenThrow(new RuntimeException()) - .thenThrow(new IllegalArgumentException()) - .thenThrow(new NullPointerException()); + when(mock.simpleMethod()) + .thenThrow(new RuntimeException()) + .thenThrow(new IllegalArgumentException()) + .thenThrow(new NullPointerException()); try { mock.simpleMethod(); fail(); - } catch (RuntimeException expected) { } + } catch (RuntimeException expected) { + } try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } } @Test public void should_throw_consecutively_set_by_shorten_then_throw_method() throws Exception { - when(mock.simpleMethod()).thenThrow(new RuntimeException(), - new IllegalArgumentException(), - new NullPointerException()); + when(mock.simpleMethod()) + .thenThrow( + new RuntimeException(), + new IllegalArgumentException(), + new NullPointerException()); try { mock.simpleMethod(); fail(); - } catch (RuntimeException expected) { } + } catch (RuntimeException expected) { + } try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } } @Test @@ -167,41 +180,50 @@ public void should_throw_classes() throws Exception { try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } } @Test @SuppressWarnings("unchecked") - public void should_throw_consecutively_classes_set_by_shorten_then_throw_method() throws Exception { + public void should_throw_consecutively_classes_set_by_shorten_then_throw_method() + throws Exception { // Unavoidable JDK7+ 'unchecked generic array creation' warning - when(mock.simpleMethod()).thenThrow(RuntimeException.class, - IllegalArgumentException.class, - NullPointerException.class); + when(mock.simpleMethod()) + .thenThrow( + RuntimeException.class, + IllegalArgumentException.class, + NullPointerException.class); try { mock.simpleMethod(); fail(); - } catch (RuntimeException expected) { } + } catch (RuntimeException expected) { + } try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } } @Test @@ -215,14 +237,16 @@ public void should_mix_consecutive_returns_with_exceptions() throws Exception { try { mock.simpleMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } assertEquals("one", mock.simpleMethod()); try { mock.simpleMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } assertEquals(null, mock.simpleMethod()); assertEquals(null, mock.simpleMethod()); @@ -230,50 +254,49 @@ public void should_mix_consecutive_returns_with_exceptions() throws Exception { @Test(expected = MockitoException.class) public void should_validate_consecutive_exception() throws Exception { - when(mock.simpleMethod()) - .thenReturn("one") - .thenThrow(new Exception()); + when(mock.simpleMethod()).thenReturn("one").thenThrow(new Exception()); } @Test public void should_stub_void_method_and_continue_throwing() throws Exception { doThrow(new IllegalArgumentException()) - .doNothing() - .doThrow(new NullPointerException()) - .when(mock).voidMethod(); + .doNothing() + .doThrow(new NullPointerException()) + .when(mock) + .voidMethod(); try { mock.voidMethod(); fail(); - } catch (IllegalArgumentException expected) { } + } catch (IllegalArgumentException expected) { + } mock.voidMethod(); try { mock.voidMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } try { mock.voidMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } } @Test public void should_stub_void_method() throws Exception { - doNothing() - .doThrow(new NullPointerException()) - .doNothing() - .when(mock) - .voidMethod(); + doNothing().doThrow(new NullPointerException()).doNothing().when(mock).voidMethod(); mock.voidMethod(); try { mock.voidMethod(); fail(); - } catch (NullPointerException expected) { } + } catch (NullPointerException expected) { + } mock.voidMethod(); mock.voidMethod(); @@ -281,9 +304,6 @@ public void should_stub_void_method() throws Exception { @Test(expected = MockitoException.class) public void should_validate_consecutive_exception_for_void_method() throws Exception { - doNothing() - .doThrow(new Exception()) - .when(mock) - .voidMethod(); + doNothing().doThrow(new Exception()).when(mock).voidMethod(); } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingReturnsSelfTest.java b/src/test/java/org/mockitousage/stubbing/StubbingReturnsSelfTest.java index b90827106e..4e75dfb5c6 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingReturnsSelfTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingReturnsSelfTest.java @@ -150,6 +150,5 @@ public HttpBuilder withHeader(String header) { public String request() { return uri + headers.toString(); } - } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java b/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java index b530d2c941..e9776f4f45 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java @@ -27,7 +27,8 @@ public class StubbingUsingDoReturnTest extends TestBase { @Mock private IMethods mock; - @After public void reset_state() { + @After + public void reset_state() { super.resetState(); } @@ -57,7 +58,8 @@ public void should_stub_with_throwable() throws Exception { try { mock.voidMethod(); fail(); - } catch (FooRuntimeException e) {} + } catch (FooRuntimeException e) { + } } @Test @@ -67,7 +69,8 @@ public void should_allow_setting_valid_checked_exception() throws Exception { try { mock.throwsIOException(0); fail(); - } catch (IOException e) {} + } catch (IOException e) { + } } class FooCheckedException extends Exception {} @@ -88,9 +91,7 @@ public void should_scream_when_return_set_for_void() throws Exception { doReturn("foo").when(mock).voidMethod(); fail(); } catch (MockitoException e) { - assertThat(e) - .hasMessageContaining("void method") - .hasMessageContaining("cannot"); + assertThat(e).hasMessageContaining("void method").hasMessageContaining("cannot"); } } @@ -116,16 +117,14 @@ public void should_scream_when_null_passed() throws Exception { @Test public void should_allow_chained_stubbing() { - doReturn("foo") - .doThrow(new RuntimeException()) - .doReturn("bar") - .when(mock).simpleMethod(); + doReturn("foo").doThrow(new RuntimeException()).doReturn("bar").when(mock).simpleMethod(); Assertions.assertThat(mock.simpleMethod()).isEqualTo("foo"); try { mock.simpleMethod(); fail(); - } catch (RuntimeException expected) { } + } catch (RuntimeException expected) { + } Assertions.assertThat(mock.simpleMethod()).isEqualTo("bar"); Assertions.assertThat(mock.simpleMethod()).isEqualTo("bar"); @@ -136,14 +135,16 @@ public void should_allow_consecutive_return_values() { doReturn("foo", "bar") .doThrow(new RuntimeException()) .doReturn(430L, new byte[0], "qix") - .when(mock).objectReturningMethodNoArgs(); + .when(mock) + .objectReturningMethodNoArgs(); Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("foo"); Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("bar"); try { mock.objectReturningMethodNoArgs(); fail("exception not raised"); - } catch (RuntimeException expected) { } + } catch (RuntimeException expected) { + } Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(430L); Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(new byte[0]); @@ -154,8 +155,7 @@ public void should_allow_consecutive_return_values() { @Test public void should_allow_do_call_real_method_in_chained_stubbing() throws Exception { MethodsImpl methods = mock(MethodsImpl.class); - doReturn("A").doCallRealMethod() - .when(methods).simpleMethod(); + doReturn("A").doCallRealMethod().when(methods).simpleMethod(); Assertions.assertThat(methods.simpleMethod()).isEqualTo("A"); Assertions.assertThat(methods.simpleMethod()).isEqualTo(null); @@ -171,31 +171,32 @@ public void should_allow_chained_stubbing_with_exception_class() throws Exceptio @Test public void should_allow_chained_stubbing_on_void_methods() { - doNothing() - .doNothing() - .doThrow(new RuntimeException()) - .when(mock).voidMethod(); + doNothing().doNothing().doThrow(new RuntimeException()).when(mock).voidMethod(); mock.voidMethod(); mock.voidMethod(); try { mock.voidMethod(); fail(); - } catch (RuntimeException e) {} + } catch (RuntimeException e) { + } try { mock.voidMethod(); fail(); - } catch (RuntimeException e) {} + } catch (RuntimeException e) { + } } @Test public void should_stub_with_generic_answer() { - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return "foo"; - } - }) - .when(mock).simpleMethod(); + doAnswer( + new Answer() { + public Object answer(InvocationOnMock invocation) throws Throwable { + return "foo"; + } + }) + .when(mock) + .simpleMethod(); Assertions.assertThat(mock.simpleMethod()).isEqualTo("foo"); } @@ -217,7 +218,8 @@ public void should_stubbing_be_treated_as_interaction() throws Exception { try { verifyNoMoreInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -242,9 +244,11 @@ public void should_detect_invalid_return_type() throws Exception { doReturn("foo").when(mock).booleanObjectReturningMethod(); fail(); } catch (Exception e) { - assertThat(e).hasMessageContaining("String cannot be returned by booleanObjectReturningMethod()" + - "\n" + - "booleanObjectReturningMethod() should return Boolean"); + assertThat(e) + .hasMessageContaining( + "String cannot be returned by booleanObjectReturningMethod()" + + "\n" + + "booleanObjectReturningMethod() should return Boolean"); } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java index 199eb86f3c..b959e99d8b 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java @@ -29,85 +29,102 @@ public class StubbingWarningsTest { @Mock IMethods mock; SimpleMockitoLogger logger = new SimpleMockitoLogger(); - MockitoSession mockito = new DefaultMockitoSession(singletonList((Object) this), TEST_NAME, Strictness.WARN, logger); + MockitoSession mockito = + new DefaultMockitoSession( + singletonList((Object) this), TEST_NAME, Strictness.WARN, logger); - @After public void after() { + @After + public void after() { StateMaster stateMaster = new StateMaster(); stateMaster.reset(); stateMaster.clearMockitoListeners(); } - @Test public void few_interactions() throws Throwable { - //when + @Test + public void few_interactions() throws Throwable { + // when mock.simpleMethod(100); mock.otherMethod(); - //expect no exception + // expect no exception mockito.finishMocking(); logger.assertEmpty(); } - @Test public void stubbing_used() throws Throwable { - //when + @Test + public void stubbing_used() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(100); - //then + // then mockito.finishMocking(); logger.assertEmpty(); } - @Test public void unused_stubbed_is_not_implicitly_verified() throws Throwable { - //when + @Test + public void unused_stubbed_is_not_implicitly_verified() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(100); // <- stubbing is used mock.simpleMethod(200); // <- other method should not generate arg mismatch - //then + // then mockito.finishMocking(); logger.assertEmpty(); } - @Test public void stubbing_argument_mismatch() throws Throwable { - //when + @Test + public void stubbing_argument_mismatch() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(200); mockito.finishMocking(); - //TODO - currently we warn about "Unused" instead of "Arg mismatch" below - //because it was simpler to implement. This can be improved given we put priority to improve the warnings. - //then - assertEquals(filterLineNo( - "[MockitoHint] " + TEST_NAME + " (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused -> at org.mockitousage.stubbing.StubbingWarningsTest.stubbing_argument_mismatch(StubbingWarningsTest.java:0)\n"), + // TODO - currently we warn about "Unused" instead of "Arg mismatch" below + // because it was simpler to implement. This can be improved given we put priority to + // improve the warnings. + // then + assertEquals( + filterLineNo( + "[MockitoHint] " + + TEST_NAME + + " (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused -> at org.mockitousage.stubbing.StubbingWarningsTest.stubbing_argument_mismatch(StubbingWarningsTest.java:0)\n"), filterLineNo(logger.getLoggedInfo())); } - @Test public void unused_stubbing() throws Throwable { - //when + @Test + public void unused_stubbing() throws Throwable { + // when given(mock.simpleMethod(100)).willReturn("100"); mockito.finishMocking(); - //then - assertEquals(filterLineNo( - "[MockitoHint] " + TEST_NAME + " (see javadoc for MockitoHint):\n" + - "[MockitoHint] 1. Unused -> at org.mockitousage.stubbing.StubbingWarningsTest.unused_stubbing(StubbingWarningsTest.java:0)\n"), + // then + assertEquals( + filterLineNo( + "[MockitoHint] " + + TEST_NAME + + " (see javadoc for MockitoHint):\n" + + "[MockitoHint] 1. Unused -> at org.mockitousage.stubbing.StubbingWarningsTest.unused_stubbing(StubbingWarningsTest.java:0)\n"), filterLineNo(logger.getLoggedInfo())); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test(expected = MockitoException.class) public void unfinished_verification_without_throwable() throws Throwable { - //when + @Test(expected = MockitoException.class) + public void unfinished_verification_without_throwable() throws Throwable { + // when verify(mock); mockito.finishMocking(); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test public void unfinished_verification_with_throwable() throws Throwable { - //when + @Test + public void unfinished_verification_with_throwable() throws Throwable { + // when verify(mock); mockito.finishMocking(new AssertionError()); diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java index 97dac76ab4..7dfed447a9 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java @@ -62,7 +62,8 @@ public void can_return_arguments_of_invocation() throws Exception { public void can_return_after_delay() throws Exception { final long sleepyTime = 500L; - given(iMethods.objectArgMethod(any())).will(answersWithDelay(sleepyTime, returnsFirstArg())); + given(iMethods.objectArgMethod(any())) + .will(answersWithDelay(sleepyTime, returnsFirstArg())); final Date before = new Date(); assertThat(iMethods.objectArgMethod("first")).isEqualTo("first"); @@ -76,7 +77,8 @@ public void can_return_after_delay() throws Exception { public void can_return_expanded_arguments_of_invocation() throws Exception { given(iMethods.varargsObject(eq(1), any())).will(returnsArgAt(3)); - assertThat(iMethods.varargsObject(1, "bob", "alexander", "alice", "carl")).isEqualTo("alice"); + assertThat(iMethods.varargsObject(1, "bob", "alexander", "alice", "carl")) + .isEqualTo("alice"); } @Test @@ -91,25 +93,30 @@ public void can_return_primitives_or_wrappers() throws Exception { @Test public void can_return_based_on_strongly_types_one_parameter_function() throws Exception { given(iMethods.simpleMethod(anyString())) - .will(answer(new Answer1() { - public String answer(String s) { - return s; - } - })); + .will( + answer( + new Answer1() { + public String answer(String s) { + return s; + } + })); assertThat(iMethods.simpleMethod("string")).isEqualTo("string"); } @Test - public void will_execute_a_void_based_on_strongly_typed_one_parameter_function() throws Exception { + public void will_execute_a_void_based_on_strongly_typed_one_parameter_function() + throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString())) - .will(answerVoid(new VoidAnswer1() { - public void answer(String s) { - target.simpleMethod(s); - } - })); + .will( + answerVoid( + new VoidAnswer1() { + public void answer(String s) { + target.simpleMethod(s); + } + })); // invoke on iMethods iMethods.simpleMethod("string"); @@ -121,28 +128,33 @@ public void answer(String s) { @Test public void can_return_based_on_strongly_typed_two_parameter_function() throws Exception { given(iMethods.simpleMethod(anyString(), anyInt())) - .will(answer(new Answer2() { - public String answer(String s, Integer i) { - return s + "-" + i; - } - })); - - assertThat(iMethods.simpleMethod("string",1)).isEqualTo("string-1"); + .will( + answer( + new Answer2() { + public String answer(String s, Integer i) { + return s + "-" + i; + } + })); + + assertThat(iMethods.simpleMethod("string", 1)).isEqualTo("string-1"); } @Test - public void will_execute_a_void_based_on_strongly_typed_two_parameter_function() throws Exception { + public void will_execute_a_void_based_on_strongly_typed_two_parameter_function() + throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString(), anyInt())) - .will(answerVoid(new VoidAnswer2() { - public void answer(String s, Integer i) { - target.simpleMethod(s, i); - } - })); + .will( + answerVoid( + new VoidAnswer2() { + public void answer(String s, Integer i) { + target.simpleMethod(s, i); + } + })); // invoke on iMethods - iMethods.simpleMethod("string",1); + iMethods.simpleMethod("string", 1); // expect the answer to write correctly to "target" verify(target, times(1)).simpleMethod("string", 1); @@ -152,27 +164,33 @@ public void answer(String s, Integer i) { public void can_return_based_on_strongly_typed_three_parameter_function() throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.threeArgumentMethodWithStrings(anyInt(), anyString(), anyString())) - .will(answer(new Answer3() { - public String answer(Integer i, String s1, String s2) { - target.threeArgumentMethodWithStrings(i, s1, s2); - return "answered"; - } - })); - - assertThat(iMethods.threeArgumentMethodWithStrings(1, "string1", "string2")).isEqualTo("answered"); + .will( + answer( + new Answer3() { + public String answer(Integer i, String s1, String s2) { + target.threeArgumentMethodWithStrings(i, s1, s2); + return "answered"; + } + })); + + assertThat(iMethods.threeArgumentMethodWithStrings(1, "string1", "string2")) + .isEqualTo("answered"); verify(target, times(1)).threeArgumentMethodWithStrings(1, "string1", "string2"); } @Test - public void will_execute_a_void_based_on_strongly_typed_three_parameter_function() throws Exception { + public void will_execute_a_void_based_on_strongly_typed_three_parameter_function() + throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.threeArgumentMethodWithStrings(anyInt(), anyString(), anyString())) - .will(answerVoid(new VoidAnswer3() { - public void answer(Integer i, String s1, String s2) { - target.threeArgumentMethodWithStrings(i, s1, s2); - } - })); + .will( + answerVoid( + new VoidAnswer3() { + public void answer(Integer i, String s1, String s2) { + target.threeArgumentMethodWithStrings(i, s1, s2); + } + })); // invoke on iMethods iMethods.threeArgumentMethodWithStrings(1, "string1", "string2"); @@ -185,31 +203,39 @@ public void answer(Integer i, String s1, String s2) { public void can_return_based_on_strongly_typed_four_parameter_function() throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.fourArgumentMethod(anyInt(), anyString(), anyString(), any(boolean[].class))) - .will(answer(new Answer4() { - public String answer(Integer i, String s1, String s2, boolean[] a) { - target.fourArgumentMethod(i, s1, s2, a); - return "answered"; - } - })); - - boolean[] booleanArray = { true, false }; - assertThat(iMethods.fourArgumentMethod(1, "string1", "string2", booleanArray)).isEqualTo("answered"); + .will( + answer( + new Answer4() { + public String answer( + Integer i, String s1, String s2, boolean[] a) { + target.fourArgumentMethod(i, s1, s2, a); + return "answered"; + } + })); + + boolean[] booleanArray = {true, false}; + assertThat(iMethods.fourArgumentMethod(1, "string1", "string2", booleanArray)) + .isEqualTo("answered"); verify(target, times(1)).fourArgumentMethod(1, "string1", "string2", booleanArray); } @Test - public void will_execute_a_void_based_on_strongly_typed_four_parameter_function() throws Exception { + public void will_execute_a_void_based_on_strongly_typed_four_parameter_function() + throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.fourArgumentMethod(anyInt(), anyString(), anyString(), any(boolean[].class))) - .will(answerVoid(new VoidAnswer4() { - public void answer(Integer i, String s1, String s2, boolean[] a) { - target.fourArgumentMethod(i, s1, s2, a); - } - })); + .will( + answerVoid( + new VoidAnswer4() { + public void answer( + Integer i, String s1, String s2, boolean[] a) { + target.fourArgumentMethod(i, s1, s2, a); + } + })); // invoke on iMethods - boolean[] booleanArray = { true, false }; + boolean[] booleanArray = {true, false}; iMethods.fourArgumentMethod(1, "string1", "string2", booleanArray); // expect the answer to write correctly to "target" @@ -220,27 +246,42 @@ public void answer(Integer i, String s1, String s2, boolean[] a) { public void can_return_based_on_strongly_typed_five_parameter_function() throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString(), anyInt(), anyInt(), anyInt(), anyInt())) - .will(answer(new Answer5() { - public String answer(String s1, Integer i1, Integer i2, Integer i3, Integer i4) { - target.simpleMethod(s1, i1, i2, i3, i4); - return "answered"; - } - })); + .will( + answer( + new Answer5() { + public String answer( + String s1, + Integer i1, + Integer i2, + Integer i3, + Integer i4) { + target.simpleMethod(s1, i1, i2, i3, i4); + return "answered"; + } + })); assertThat(iMethods.simpleMethod("hello", 1, 2, 3, 4)).isEqualTo("answered"); verify(target, times(1)).simpleMethod("hello", 1, 2, 3, 4); } @Test - public void will_execute_a_void_based_on_strongly_typed_five_parameter_function() throws Exception { + public void will_execute_a_void_based_on_strongly_typed_five_parameter_function() + throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString(), anyInt(), anyInt(), anyInt(), anyInt())) - .will(answerVoid(new VoidAnswer5() { - public void answer(String s1, Integer i1, Integer i2, Integer i3, Integer i4) { - target.simpleMethod(s1, i1, i2, i3, i4); - } - })); + .will( + answerVoid( + new VoidAnswer5() { + public void answer( + String s1, + Integer i1, + Integer i2, + Integer i3, + Integer i4) { + target.simpleMethod(s1, i1, i2, i3, i4); + } + })); // invoke on iMethods iMethods.simpleMethod("hello", 1, 2, 3, 4); @@ -253,27 +294,52 @@ public void answer(String s1, Integer i1, Integer i2, Integer i3, Integer i4) { public void can_return_based_on_strongly_typed_six_parameter_function() throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt())) - .will(answer(new Answer6() { - public String answer(String s1, Integer i1, Integer i2, Integer i3, Integer i4, Integer i5) { - target.simpleMethod(s1, i1, i2, i3, i4, i5); - return "answered"; - } - })); + .will( + answer( + new Answer6< + String, + String, + Integer, + Integer, + Integer, + Integer, + Integer>() { + public String answer( + String s1, + Integer i1, + Integer i2, + Integer i3, + Integer i4, + Integer i5) { + target.simpleMethod(s1, i1, i2, i3, i4, i5); + return "answered"; + } + })); assertThat(iMethods.simpleMethod("hello", 1, 2, 3, 4, 5)).isEqualTo("answered"); verify(target, times(1)).simpleMethod("hello", 1, 2, 3, 4, 5); } @Test - public void will_execute_a_void_returning_strongly_typed_six_parameter_function() throws Exception { + public void will_execute_a_void_returning_strongly_typed_six_parameter_function() + throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt())) - .will(answerVoid(new VoidAnswer6() { - public void answer(String s1, Integer i1, Integer i2, Integer i3, Integer i4, Integer i5) { - target.simpleMethod(s1, i1, i2, i3, i4, i5); - } - })); + .will( + answerVoid( + new VoidAnswer6< + String, Integer, Integer, Integer, Integer, Integer>() { + public void answer( + String s1, + Integer i1, + Integer i2, + Integer i3, + Integer i4, + Integer i5) { + target.simpleMethod(s1, i1, i2, i3, i4, i5); + } + })); // invoke on iMethods iMethods.simpleMethod("hello", 1, 2, 3, 4, 5); diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java index 71e96ad7db..43824bf680 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java @@ -15,21 +15,24 @@ import org.mockito.Mockito; import org.mockitoutil.TestBase; -//issue 1514 -@SuppressWarnings({ "serial", "unchecked", "rawtypes" }) +// issue 1514 +@SuppressWarnings({"serial", "unchecked", "rawtypes"}) public class StubbingWithBadThrowablesTest extends TestBase { @Mock List mock; @Test public void handles_bad_exception() { - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - doThrow(UninstantiableException.class).when(mock).clear(); - } - }).isInstanceOf(InstantiationError.class); //because the exception cannot be instantiated - - //ensure that the state is cleaned + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + doThrow(UninstantiableException.class).when(mock).clear(); + } + }) + .isInstanceOf( + InstantiationError.class); // because the exception cannot be instantiated + + // ensure that the state is cleaned Mockito.validateMockitoUsage(); } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java index b83161069e..bbbaa8a077 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithCustomAnswerTest.java @@ -18,18 +18,19 @@ import org.mockitoutil.TestBase; public class StubbingWithCustomAnswerTest extends TestBase { - @Mock - private IMethods mock; + @Mock private IMethods mock; @Test public void shouldAnswer() throws Exception { - when(mock.simpleMethod(anyString())).thenAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - String arg = invocation.getArgument(0); + when(mock.simpleMethod(anyString())) + .thenAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + String arg = invocation.getArgument(0); - return invocation.getMethod().getName() + "-" + arg; - } - }); + return invocation.getMethod().getName() + "-" + arg; + } + }); assertEquals("simpleMethod-test", mock.simpleMethod("test")); } @@ -47,17 +48,19 @@ public void shouldAnswerWithThenAnswerAlias() throws Exception { @Test public void shouldAnswerConsecutively() throws Exception { when(mock.simpleMethod()) - .thenAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getMethod().getName(); - } - }) + .thenAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + return invocation.getMethod().getName(); + } + }) .thenReturn("Hello") - .thenAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getMethod().getName() + "-1"; - } - }); + .thenAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + return invocation.getMethod().getName() + "-1"; + } + }); assertEquals("simpleMethod", mock.simpleMethod()); assertEquals("Hello", mock.simpleMethod()); @@ -81,9 +84,10 @@ public void shouldAnswerVoidMethodConsecutively() throws Exception { RecordCall call2 = new RecordCall(); doAnswer(call1) - .doThrow(new UnsupportedOperationException()) - .doAnswer(call2) - .when(mock).voidMethod(); + .doThrow(new UnsupportedOperationException()) + .doAnswer(call2) + .when(mock) + .voidMethod(); mock.voidMethod(); assertTrue(call1.isCalled()); @@ -101,14 +105,16 @@ public void shouldAnswerVoidMethodConsecutively() throws Exception { @Test public void shouldMakeSureTheInterfaceDoesNotChange() throws Exception { - when(mock.simpleMethod(anyString())).thenAnswer(new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - assertTrue(invocation.getArguments().getClass().isArray()); - assertEquals(Method.class, invocation.getMethod().getClass()); + when(mock.simpleMethod(anyString())) + .thenAnswer( + new Answer() { + public String answer(InvocationOnMock invocation) throws Throwable { + assertTrue(invocation.getArguments().getClass().isArray()); + assertEquals(Method.class, invocation.getMethod().getClass()); - return "assertions passed"; - } - }); + return "assertions passed"; + } + }); assertEquals("assertions passed", mock.simpleMethod("test")); } @@ -125,5 +131,4 @@ public Object answer(InvocationOnMock invocation) throws Throwable { return null; } } - } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java index d89be348ca..5d21e71630 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java @@ -144,7 +144,9 @@ public void calling_method_with_wrong_primitive_return_should_throw_exception() mock.size(); fail(); } catch (MockitoException e) { - assertThat(e.toString()).contains("Methods called on delegated instance must have compatible return type"); + assertThat(e.toString()) + .contains( + "Methods called on delegated instance must have compatible return type"); } } @@ -156,19 +158,25 @@ public void calling_method_with_wrong_reference_return_should_throw_exception() mock.subList(0, 0); fail(); } catch (MockitoException e) { - assertThat(e.toString()).contains("Methods called on delegated instance must have compatible return type"); + assertThat(e.toString()) + .contains( + "Methods called on delegated instance must have compatible return type"); } } @Test public void exception_should_be_propagated_from_delegate() throws Exception { final RuntimeException failure = new RuntimeException("angry-method"); - IMethods methods = mock(IMethods.class, delegatesTo(new MethodsImpl() { - @Override - public String simpleMethod() { - throw failure; - } - })); + IMethods methods = + mock( + IMethods.class, + delegatesTo( + new MethodsImpl() { + @Override + public String simpleMethod() { + throw failure; + } + })); try { methods.simpleMethod(); // delegate throws an exception @@ -184,18 +192,19 @@ interface Foo { @Test public void should_call_anonymous_class_method() throws Throwable { - Foo foo = new Foo() { - public int bar() { - return 0; - } - }; + Foo foo = + new Foo() { + public int bar() { + return 0; + } + }; Foo mock = mock(Foo.class); when(mock.bar()).thenAnswer(AdditionalAnswers.delegatesTo(foo)); - //when + // when mock.bar(); - //then no exception is thrown + // then no exception is thrown } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java index a5a83b163d..5bd3f33c0b 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateVarArgsTest.java @@ -23,28 +23,24 @@ private static final class FooImpl implements Foo { public int bar(String baz, Object... args) { return args != null ? args.length : -1; // simple return argument count } - } @Test public void should_not_fail_when_calling_varargs_method() { - Foo foo = mock(Foo.class, withSettings() - .defaultAnswer(delegatesTo(new FooImpl()))); + Foo foo = mock(Foo.class, withSettings().defaultAnswer(delegatesTo(new FooImpl()))); assertThat(foo.bar("baz", 12, "45", 67.8)).isEqualTo(3); } @Test public void should_not_fail_when_calling_varargs_method_without_arguments() { - Foo foo = mock(Foo.class, withSettings() - .defaultAnswer(delegatesTo(new FooImpl()))); + Foo foo = mock(Foo.class, withSettings().defaultAnswer(delegatesTo(new FooImpl()))); assertThat(foo.bar("baz")).isEqualTo(0); assertThat(foo.bar("baz", new Object[0])).isEqualTo(0); } @Test public void should_not_fail_when_calling_varargs_method_with_null_argument() { - Foo foo = mock(Foo.class, withSettings() - .defaultAnswer(delegatesTo(new FooImpl()))); + Foo foo = mock(Foo.class, withSettings().defaultAnswer(delegatesTo(new FooImpl()))); assertThat(foo.bar("baz", (Object[]) null)).isEqualTo(-1); } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java index 9818542368..b7f1cec527 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java @@ -25,26 +25,28 @@ public class StubbingWithExtraAnswersTest extends TestBase { @Test public void shouldWorkAsStandardMockito() throws Exception { - //when + // when List list = asList(1, 2, 3); - when(mock.objectReturningMethodNoArgs()).thenAnswer(AdditionalAnswers.returnsElementsOf(list)); + when(mock.objectReturningMethodNoArgs()) + .thenAnswer(AdditionalAnswers.returnsElementsOf(list)); - //then + // then assertEquals(1, mock.objectReturningMethodNoArgs()); assertEquals(2, mock.objectReturningMethodNoArgs()); assertEquals(3, mock.objectReturningMethodNoArgs()); - //last element is returned continuously + // last element is returned continuously assertEquals(3, mock.objectReturningMethodNoArgs()); assertEquals(3, mock.objectReturningMethodNoArgs()); } @Test public void shouldReturnNullIfNecessary() throws Exception { - //when + // when List list = asList(1, null); - when(mock.objectReturningMethodNoArgs()).thenAnswer(AdditionalAnswers.returnsElementsOf(list)); + when(mock.objectReturningMethodNoArgs()) + .thenAnswer(AdditionalAnswers.returnsElementsOf(list)); - //then + // then assertEquals(1, mock.objectReturningMethodNoArgs()); assertEquals(null, mock.objectReturningMethodNoArgs()); assertEquals(null, mock.objectReturningMethodNoArgs()); @@ -53,10 +55,11 @@ public void shouldReturnNullIfNecessary() throws Exception { @Test public void shouldScreamWhenNullPassed() throws Exception { try { - //when + // when AdditionalAnswers.returnsElementsOf(null); - //then + // then fail(); - } catch (MockitoException e) {} + } catch (MockitoException e) { + } } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java index 3b93f3c7db..625961c1a0 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java @@ -35,15 +35,14 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -@SuppressWarnings({ "serial", "unchecked", "rawtypes" }) +@SuppressWarnings({"serial", "unchecked", "rawtypes"}) public class StubbingWithThrowablesTest extends TestBase { private LinkedList mock; private Map mockTwo; - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); @Before public void setup() { @@ -55,52 +54,60 @@ public void setup() { public void throws_same_exception_consecutively() { when(mock.add("")).thenThrow(new ExceptionOne()); - //1st invocation - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.add(""); - } - }).isInstanceOf(ExceptionOne.class); + // 1st invocation + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + mock.add(""); + } + }) + .isInstanceOf(ExceptionOne.class); mock.add("1"); - //2nd invocation - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.add(""); - } - }).isInstanceOf(ExceptionOne.class); + // 2nd invocation + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + mock.add(""); + } + }) + .isInstanceOf(ExceptionOne.class); } @Test public void throws_same_exception_consecutively_with_doThrow() { doThrow(new ExceptionOne()).when(mock).clear(); - //1st invocation - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.clear(); - } - }).isInstanceOf(ExceptionOne.class); + // 1st invocation + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + mock.clear(); + } + }) + .isInstanceOf(ExceptionOne.class); mock.add("1"); - //2nd invocation - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.clear(); - } - }).isInstanceOf(ExceptionOne.class); + // 2nd invocation + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + mock.clear(); + } + }) + .isInstanceOf(ExceptionOne.class); } @Test public void throws_new_exception_consecutively_from_class() { when(mock.add(null)).thenThrow(NaughtyException.class); - NaughtyException first = Assertions.catchThrowableOfType(() -> mock.add(null), - NaughtyException.class); - NaughtyException second = Assertions.catchThrowableOfType(() -> mock.add(null), - NaughtyException.class); + NaughtyException first = + Assertions.catchThrowableOfType(() -> mock.add(null), NaughtyException.class); + NaughtyException second = + Assertions.catchThrowableOfType(() -> mock.add(null), NaughtyException.class); assertNotSame(first, second); } @@ -109,10 +116,10 @@ public void throws_new_exception_consecutively_from_class() { public void throws_new_exception_consecutively_from_class_with_doThrow() { doThrow(NaughtyException.class).when(mock).add(null); - NaughtyException first = Assertions.catchThrowableOfType(() -> mock.add(null), - NaughtyException.class); - NaughtyException second = Assertions.catchThrowableOfType(() -> mock.add(null), - NaughtyException.class); + NaughtyException first = + Assertions.catchThrowableOfType(() -> mock.add(null), NaughtyException.class); + NaughtyException second = + Assertions.catchThrowableOfType(() -> mock.add(null), NaughtyException.class); assertNotSame(first, second); } @@ -135,7 +142,6 @@ public void shouldSetThrowableToVoidMethod() throws Exception { exception.expect(sameInstance(expected)); mock.clear(); - } @Test @@ -149,7 +155,8 @@ public void shouldLastStubbingVoidBeImportant() throws Exception { } @Test - public void shouldFailStubbingThrowableOnTheSameInvocationDueToAcceptableLimitation() throws Exception { + public void shouldFailStubbingThrowableOnTheSameInvocationDueToAcceptableLimitation() + throws Exception { when(mock.size()).thenThrow(new ExceptionOne()); exception.expect(ExceptionOne.class); @@ -404,20 +411,15 @@ public void shouldStubbingWithThrowableFailVerification() { } } - private class ExceptionOne extends RuntimeException { - } + private class ExceptionOne extends RuntimeException {} - private class ExceptionTwo extends RuntimeException { - } + private class ExceptionTwo extends RuntimeException {} - private class ExceptionThree extends RuntimeException { - } + private class ExceptionThree extends RuntimeException {} - private class ExceptionFour extends RuntimeException { - } + private class ExceptionFour extends RuntimeException {} - private class CheckedException extends Exception { - } + private class CheckedException extends Exception {} public class NaughtyException extends RuntimeException { public NaughtyException() { diff --git a/src/test/java/org/mockitousage/verification/AtLeastXVerificationTest.java b/src/test/java/org/mockitousage/verification/AtLeastXVerificationTest.java index e84ee21248..8a3f6b1fc3 100644 --- a/src/test/java/org/mockitousage/verification/AtLeastXVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/AtLeastXVerificationTest.java @@ -20,12 +20,12 @@ public class AtLeastXVerificationTest extends TestBase { @Test public void shouldVerifyAtLeastXTimes() throws Exception { - //when + // when mock.clear(); mock.clear(); mock.clear(); - //then + // then verify(mock, atLeast(2)).clear(); } @@ -37,16 +37,18 @@ public void shouldFailVerificationAtLeastXTimes() throws Exception { try { verify(mock, atLeast(2)).add(anyString()); fail(); - } catch (MockitoAssertionError e) {} + } catch (MockitoAssertionError e) { + } } @Test - public void shouldAllowAtLeastZeroForTheSakeOfVerifyNoMoreInteractionsSometimes() throws Exception { - //when + public void shouldAllowAtLeastZeroForTheSakeOfVerifyNoMoreInteractionsSometimes() + throws Exception { + // when mock.add("one"); mock.clear(); - //then + // then verify(mock, atLeast(0)).add("one"); verify(mock, atLeast(0)).clear(); diff --git a/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java b/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java index 7ef39fe081..47c78f72ec 100644 --- a/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java @@ -39,7 +39,8 @@ public void shouldVerifyAtMostXTimes() throws Exception { try { verify(mock, atMostOnce()).clear(); fail(); - } catch (MoreThanAllowedActualInvocations e) {} + } catch (MoreThanAllowedActualInvocations e) { + } } @Test @@ -50,7 +51,8 @@ public void shouldWorkWithArgumentMatchers() throws Exception { try { verify(mock, atMost(0)).add(anyString()); fail(); - } catch (MoreThanAllowedActualInvocations e) {} + } catch (MoreThanAllowedActualInvocations e) { + } } @Test @@ -108,7 +110,7 @@ public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exceptio try { verifyNoMoreInteractions(mock); fail(); - } catch(NoInteractionsWanted e) { + } catch (NoInteractionsWanted e) { assertThat(e).hasMessageContaining("undesiredInteraction("); } } diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java index acffe23400..834af414c7 100644 --- a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java +++ b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java @@ -271,6 +271,6 @@ public void shouldFailOnVerifyNoInteractions() { @SuppressWarnings({"all", "CheckReturnValue", "MockitoUsage"}) @Test(expected = MockitoException.class) public void shouldScreamWhenNullPassed() { - inOrder((Object[])null); + inOrder((Object[]) null); } } diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationTest.java index 811edaf9e8..2f2f6b37a9 100644 --- a/src/test/java/org/mockitousage/verification/BasicVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/BasicVerificationTest.java @@ -36,7 +36,7 @@ public void shouldVerify() throws Exception { verifyNoMoreInteractions(mock); } - @Test(expected=WantedButNotInvoked.class) + @Test(expected = WantedButNotInvoked.class) public void shouldFailVerification() throws Exception { verify(mock).clear(); } @@ -48,12 +48,14 @@ public void shouldFailVerificationOnMethodArgument() throws Exception { verify(mock).clear(); - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock).add("bar"); - } - }).isInstanceOf(ArgumentsAreDifferent.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock).add("bar"); + } + }) + .isInstanceOf(ArgumentsAreDifferent.class); } @Test @@ -68,7 +70,8 @@ public void shouldFailOnWrongMethod() throws Exception { try { verify(mockTwo, atLeastOnce()).add("foo"); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } @Test @@ -83,7 +86,8 @@ public void shouldDetectRedundantInvocation() throws Exception { try { verifyNoMoreInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -97,7 +101,8 @@ public void shouldDetectWhenInvokedMoreThanOnce() throws Exception { try { verify(mock).clear(); fail(); - } catch (TooManyActualInvocations e) {} + } catch (TooManyActualInvocations e) { + } } @Test @@ -109,7 +114,6 @@ public void shouldVerifyStubbedMethods() throws Exception { verify(mock).add("test"); } - @Test public void shouldDetectWhenOverloadedMethodCalled() throws Exception { IMethods mockThree = mock(IMethods.class); @@ -118,6 +122,7 @@ public void shouldDetectWhenOverloadedMethodCalled() throws Exception { try { verify(mockThree).varargs((String[]) new String[] {}); fail(); - } catch(WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } } diff --git a/src/test/java/org/mockitousage/verification/CustomVerificationTest.java b/src/test/java/org/mockitousage/verification/CustomVerificationTest.java index 519f4648f0..766bb1d4a5 100644 --- a/src/test/java/org/mockitousage/verification/CustomVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/CustomVerificationTest.java @@ -23,40 +23,49 @@ public class CustomVerificationTest extends TestBase { @Test public void custom_verification_with_old_api() { - //given: + // given: mock.simpleMethod("a", 10); - //expect: + // expect: verify(mock, ignoreParametersUsingOldApi()).simpleMethod(); try { verify(mock, ignoreParametersUsingOldApi()).otherMethod(); fail(); - } catch (MockitoAssertionError e) {} + } catch (MockitoAssertionError e) { + } } - //Old api still supported, see https://github.com/mockito/mockito/issues/730 + // Old api still supported, see https://github.com/mockito/mockito/issues/730 private VerificationMode ignoreParametersUsingOldApi() { return new VerificationMode() { public void verify(VerificationData data) { - //use old api + // use old api InvocationMatcher target = data.getWanted(); - //sanity check the new api + // sanity check the new api if (data.getTarget() != target) { throw new RuntimeException("Sanity check"); } - //look for the relevant invocation and exit if found + // look for the relevant invocation and exit if found for (Invocation invocation : data.getAllInvocations()) { - if (target.getInvocation().getMethod().getName().equals(invocation.getMethod().getName())) { + if (target.getInvocation() + .getMethod() + .getName() + .equals(invocation.getMethod().getName())) { return; } } - //verification failed! - throw new MockitoAssertionError("Expected method with name: " + target + " not found in:\n" + data.getAllInvocations()); + // verification failed! + throw new MockitoAssertionError( + "Expected method with name: " + + target + + " not found in:\n" + + data.getAllInvocations()); } + public VerificationMode description(String description) { return this; } diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java index cdad5ed98b..9e5ffebc50 100644 --- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java +++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java @@ -49,24 +49,24 @@ public void shouldPrintVerificationInOrderErrorAndShowBothWantedAndPrevious() { fail(); } catch (VerificationInOrderFailure e) { String expected = - "\n" + - "Verification in order failure" + - "\n" + - "Wanted but not invoked:" + - "\n" + - "iMethods.simpleMethod(11);" + - "\n" + - "-> at "; + "\n" + + "Verification in order failure" + + "\n" + + "Wanted but not invoked:" + + "\n" + + "iMethods.simpleMethod(11);" + + "\n" + + "-> at "; assertThat(e).hasMessageContaining(expected); String expectedCause = - "\n" + - "Wanted anywhere AFTER following interaction:" + - "\n" + - "iMethods.simpleMethod(2);" + - "\n" + - "-> at "; + "\n" + + "Wanted anywhere AFTER following interaction:" + + "\n" + + "iMethods.simpleMethod(2);" + + "\n" + + "-> at "; assertThat(e).hasMessageContaining(expectedCause); } @@ -79,12 +79,12 @@ public void shouldPrintVerificationInOrderErrorAndShowWantedOnly() { fail(); } catch (WantedButNotInvoked e) { String expected = - "\n" + - "Wanted but not invoked:" + - "\n" + - "iMethods.differentMethod();" + - "\n" + - "-> at"; + "\n" + + "Wanted but not invoked:" + + "\n" + + "iMethods.differentMethod();" + + "\n" + + "-> at"; assertThat(e).hasMessageContaining(expected); } @@ -102,7 +102,8 @@ public void shouldPrintVerificationInOrderErrorAndShowWantedAndActual() { @Test public void shouldNotSayArgumentsAreDifferent() { - //this is the last invocation so any next verification in order should simply say wanted but not invoked + // this is the last invocation so any next verification in order should simply say wanted + // but not invoked inOrder.verify(three).simpleMethod(3); try { inOrder.verify(one).simpleMethod(999); @@ -123,12 +124,12 @@ public void shouldPrintMethodThatWasNotInvoked() { fail(); } catch (VerificationInOrderFailure e) { String expectedMessage = - "\n" + - "Verification in order failure" + - "\n" + - "Wanted but not invoked:" + - "\n" + - "iMethods.simpleMethod(999);"; + "\n" + + "Verification in order failure" + + "\n" + + "Wanted but not invoked:" + + "\n" + + "iMethods.simpleMethod(999);"; assertThat(e).hasMessageContaining(expectedMessage); } } @@ -142,21 +143,17 @@ public void shouldPrintTooManyInvocations() { fail(); } catch (VerificationInOrderFailure e) { String expectedMessage = - "\n" + - "Verification in order failure:" + - "\n" + - "iMethods.simpleMethod(2);" + - "\n" + - "Wanted 1 time:" + - "\n" + - "-> at"; + "\n" + + "Verification in order failure:" + + "\n" + + "iMethods.simpleMethod(2);" + + "\n" + + "Wanted 1 time:" + + "\n" + + "-> at"; assertThat(e).hasMessageContaining(expectedMessage); - String expectedCause = - "\n" + - "But was 2 times:" + - "\n" + - "-> at"; + String expectedCause = "\n" + "But was 2 times:" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expectedCause); } } @@ -174,21 +171,17 @@ public void shouldPrintTooFewInvocations() { fail(); } catch (VerificationInOrderFailure e) { String expectedMessage = - "\n" + - "Verification in order failure:" + - "\n" + - "iMethods.simpleMethod(2);" + - "\n" + - "Wanted 2 times:" + - "\n" + - "-> at"; + "\n" + + "Verification in order failure:" + + "\n" + + "iMethods.simpleMethod(2);" + + "\n" + + "Wanted 2 times:" + + "\n" + + "-> at"; assertThat(e).hasMessageContaining(expectedMessage); - String expectedCause = - "\n" + - "But was 1 time:" + - "\n" + - "-> at"; + String expectedCause = "\n" + "But was 1 time:" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expectedCause); } diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java index 98217d346f..7ad4627789 100644 --- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java +++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java @@ -34,9 +34,9 @@ public void shouldVerifyActualNumberOfInvocationsSmallerThanWanted() throws Exce fail(); } catch (TooFewActualInvocations e) { assertThat(e) - .hasMessageContaining("mock.clear();") - .hasMessageContaining("Wanted 100 times") - .hasMessageContaining("was 3"); + .hasMessageContaining("mock.clear();") + .hasMessageContaining("Wanted 100 times") + .hasMessageContaining("was 3"); } } @@ -53,9 +53,9 @@ public void shouldVerifyActualNumberOfInvocationsLargerThanWanted() throws Excep fail(); } catch (TooManyActualInvocations e) { assertThat(e) - .hasMessageContaining("mock.clear();") - .hasMessageContaining("Wanted 1 time") - .hasMessageContaining("was 4"); + .hasMessageContaining("mock.clear();") + .hasMessageContaining("Wanted 1 time") + .hasMessageContaining("was 4"); } } } diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java index 7452d0e627..f0350f93cf 100644 --- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java +++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java @@ -37,12 +37,12 @@ public void should_print_method_name() { fail(); } catch (WantedButNotInvoked e) { String expectedMessage = - "\n" + - "Wanted but not invoked:" + - "\n" + - "iMethods.simpleMethod();" + - "\n" + - "-> at"; + "\n" + + "Wanted but not invoked:" + + "\n" + + "iMethods.simpleMethod();" + + "\n" + + "-> at"; assertThat(e).hasMessageContaining(expectedMessage); } } @@ -72,18 +72,18 @@ public void should_print_actual_and_wanted_in_line() { fail(); } catch (ArgumentsAreDifferent e) { String wanted = - "\n" + - "Argument(s) are different! Wanted:" + - "\n" + - "iMethods.varargs(1, 1000);"; + "\n" + + "Argument(s) are different! Wanted:" + + "\n" + + "iMethods.varargs(1, 1000);"; assertThat(e).hasMessageContaining(wanted); String actual = - "\n" + - "Actual invocations have different arguments:" + - "\n" + - "iMethods.varargs(1, 2);"; + "\n" + + "Actual invocations have different arguments:" + + "\n" + + "iMethods.varargs(1, 2);"; assertThat(e).hasMessageContaining(actual); } @@ -98,46 +98,49 @@ public void should_print_actual_and_wanted_in_multiple_lines() { fail(); } catch (ArgumentsAreDifferent e) { String wanted = - "\n" + - "Argument(s) are different! Wanted:" + - "\n" + - "iMethods.varargs(" + - "\n" + - " \"x\"," + - "\n" + - " \"y\"," + - "\n" + - " \"z\"" + - "\n" + - ");"; + "\n" + + "Argument(s) are different! Wanted:" + + "\n" + + "iMethods.varargs(" + + "\n" + + " \"x\"," + + "\n" + + " \"y\"," + + "\n" + + " \"z\"" + + "\n" + + ");"; assertThat(e).hasMessageContaining(wanted); String actual = - "\n" + - "Actual invocations have different arguments:" + - "\n" + - "iMethods.varargs(" + - "\n" + - " \"this is very long string\"," + - "\n" + - " \"this is another very long string\"" + - "\n" + - ");"; + "\n" + + "Actual invocations have different arguments:" + + "\n" + + "iMethods.varargs(" + + "\n" + + " \"this is very long string\"," + + "\n" + + " \"this is another very long string\"" + + "\n" + + ");"; assertThat(e).hasMessageContaining(actual); } } @Test - public void should_print_actual_and_wanted_when_actual_method_name_and_wanted_method_name_are_the_same() { + public void + should_print_actual_and_wanted_when_actual_method_name_and_wanted_method_name_are_the_same() { mock.simpleMethod(); try { verify(mock).simpleMethod(10); fail(); } catch (ArgumentsAreDifferent e) { - assertThat(e).hasMessageContaining("simpleMethod(10)").hasMessageContaining("simpleMethod()"); + assertThat(e) + .hasMessageContaining("simpleMethod(10)") + .hasMessageContaining("simpleMethod()"); } } @@ -166,18 +169,11 @@ public void should_print_first_unexpected_invocation() { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { - String expectedMessage = - "\n" + - "No interactions wanted here:" + - "\n" + - "-> at"; + String expectedMessage = "\n" + "No interactions wanted here:" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expectedMessage); String expectedCause = - "\n" + - "But found this interaction on mock '" + mock + "':" + - "\n" + - "-> at"; + "\n" + "But found this interaction on mock '" + mock + "':" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expectedCause); } } @@ -191,19 +187,12 @@ public void should_print_first_unexpected_invocation_when_verifying_zero_interac verifyZeroInteractions(mock); fail(); } catch (NoInteractionsWanted e) { - String expected = - "\n" + - "No interactions wanted here:" + - "\n" + - "-> at"; + String expected = "\n" + "No interactions wanted here:" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expected); String expectedCause = - "\n" + - "But found this interaction on mock '" + mock + "':" + - "\n" + - "-> at"; + "\n" + "But found this interaction on mock '" + mock + "':" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expectedCause); } @@ -218,19 +207,12 @@ public void should_print_first_unexpected_invocation_when_verifying_no_interacti verifyNoInteractions(mock); fail(); } catch (NoInteractionsWanted e) { - String expected = - "\n" + - "No interactions wanted here:" + - "\n" + - "-> at"; + String expected = "\n" + "No interactions wanted here:" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expected); String expectedCause = - "\n" + - "But found these interactions on mock '" + mock + "':" + - "\n" + - "-> at"; + "\n" + "But found these interactions on mock '" + mock + "':" + "\n" + "-> at"; assertThat(e).hasMessageContaining(expectedCause); } @@ -253,28 +235,28 @@ public void should_print_method_when_matcher_used() throws Exception { fail(); } catch (WantedButNotInvoked e) { String expectedMessage = - "\n" + - "Wanted but not invoked:" + - "\n" + - "iMethods.twoArgumentMethod(\n" + - " ,\n" + - " 100\n" + - ");"; + "\n" + + "Wanted but not invoked:" + + "\n" + + "iMethods.twoArgumentMethod(\n" + + " ,\n" + + " 100\n" + + ");"; assertThat(e).hasMessageContaining(expectedMessage); } } @Test public void should_print_method_when_missing_invocation_with_array_matcher() { - mock.oneArray(new boolean[] { true, false, false }); + mock.oneArray(new boolean[] {true, false, false}); try { - verify(mock).oneArray(aryEq(new boolean[] { false, false, false })); + verify(mock).oneArray(aryEq(new boolean[] {false, false, false})); fail(); } catch (ArgumentsAreDifferent e) { assertThat(e) - .hasMessageContaining("[false, false, false]") - .hasMessageContaining("[true, false, false]"); + .hasMessageContaining("[false, false, false]") + .hasMessageContaining("[true, false, false]"); } } @@ -286,9 +268,7 @@ public void should_print_method_when_missing_invocation_with_vararg_matcher() { verify(mock).varargsString(10, "111", "222", "333"); fail(); } catch (ArgumentsAreDifferent e) { - assertThat(e) - .hasMessageContaining("111") - .hasMessageContaining("\"xxx\""); + assertThat(e).hasMessageContaining("111").hasMessageContaining("\"xxx\""); } } @@ -301,8 +281,8 @@ public void should_print_method_when_missing_invocation_with_matcher() { fail(); } catch (ArgumentsAreDifferent e) { assertThat(e) - .hasMessageContaining("matches(\"burrito from Exmouth\")") - .hasMessageContaining("\"foo\""); + .hasMessageContaining("matches(\"burrito from Exmouth\")") + .hasMessageContaining("\"foo\""); } } @@ -327,8 +307,8 @@ public void should_say_never_wanted_but_invoked() throws Exception { fail(); } catch (NeverWantedButInvoked e) { assertThat(e) - .hasMessageContaining("Never wanted here:") - .hasMessageContaining("But invoked here:"); + .hasMessageContaining("Never wanted here:") + .hasMessageContaining("But invoked here:"); } } @@ -341,9 +321,7 @@ public void should_show_right_actual_method() throws Exception { verify(mock).simpleMethod("bar"); fail(); } catch (ArgumentsAreDifferent e) { - assertThat(e) - .hasMessageContaining("bar") - .hasMessageContaining("foo"); + assertThat(e).hasMessageContaining("bar").hasMessageContaining("foo"); } } @@ -358,13 +336,14 @@ public void should_print_field_name_when_annotations_used() throws Exception { fail(); } catch (ArgumentsAreDifferent e) { assertThat(e) - .hasMessageContaining("iHavefunkyName.simpleMethod(20)") - .hasMessageContaining("iHavefunkyName.simpleMethod(10)"); + .hasMessageContaining("iHavefunkyName.simpleMethod(20)") + .hasMessageContaining("iHavefunkyName.simpleMethod(10)"); } } @Test - public void should_print_interactions_on_mock_when_ordinary_verification_fail() throws Exception { + public void should_print_interactions_on_mock_when_ordinary_verification_fail() + throws Exception { mock.otherMethod(); mock.booleanReturningMethod(); @@ -372,7 +351,7 @@ public void should_print_interactions_on_mock_when_ordinary_verification_fail() verify(mock).simpleMethod(); fail(); } catch (WantedButNotInvoked e) { -// assertContains("") + // assertContains("") } } @@ -383,13 +362,16 @@ public void should_never_break_method_string_when_no_args_in_method() throws Exc try { verify(veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock).simpleMethod(); fail(); - } catch(WantedButNotInvoked e) { - assertThat(e).hasMessageContaining("veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock.simpleMethod()"); + } catch (WantedButNotInvoked e) { + assertThat(e) + .hasMessageContaining("veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock.simpleMethod()"); } } @Test - public void should_print_method_name_and_arguments_of_other_interactions_with_different_methods() throws Exception { + public void + should_print_method_name_and_arguments_of_other_interactions_with_different_methods() + throws Exception { try { mock.arrayMethod(new String[] {"a", "b", "c"}); mock.forByte((byte) 25); @@ -398,15 +380,16 @@ public void should_print_method_name_and_arguments_of_other_interactions_with_di fail(); } catch (WantedButNotInvoked e) { assertThat(e) - .hasMessageContaining("iMethods.threeArgumentMethod(12, foo, \"xx\")") - .hasMessageContaining("iMethods.arrayMethod([\"a\", \"b\", \"c\"])") - .hasMessageContaining("iMethods.forByte((byte) 0x19)"); + .hasMessageContaining("iMethods.threeArgumentMethod(12, foo, \"xx\")") + .hasMessageContaining("iMethods.arrayMethod([\"a\", \"b\", \"c\"])") + .hasMessageContaining("iMethods.forByte((byte) 0x19)"); } } @Test @Ignore("issue 380 related") - public void should_print_method_name_and_arguments_of_other_interactions_of_same_method() throws Exception { + public void should_print_method_name_and_arguments_of_other_interactions_of_same_method() + throws Exception { try { mock.forByte((byte) 25); mock.forByte((byte) 12); @@ -415,9 +398,9 @@ public void should_print_method_name_and_arguments_of_other_interactions_of_same fail(); } catch (WantedButNotInvoked e) { assertThat(e) - .hasMessageContaining("iMethods.forByte(42)") - .hasMessageContaining("iMethods.forByte(25)") - .hasMessageContaining("iMethods.forByte(12)"); + .hasMessageContaining("iMethods.forByte(42)") + .hasMessageContaining("iMethods.forByte(25)") + .hasMessageContaining("iMethods.forByte(12)"); } } diff --git a/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java b/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java index 3cf4027e85..a3500b4012 100644 --- a/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java @@ -36,9 +36,7 @@ public void shouldDetectTooFewActualInvocations() throws Exception { verify(mock, times(100)).clear(); fail(); } catch (TooFewActualInvocations e) { - assertThat(e) - .hasMessageContaining("Wanted 100 times") - .hasMessageContaining("was 2"); + assertThat(e).hasMessageContaining("Wanted 100 times").hasMessageContaining("was 2"); } } @@ -52,9 +50,7 @@ public void shouldDetectTooManyActualInvocations() throws Exception { verify(mock, times(1)).clear(); fail(); } catch (TooManyActualInvocations e) { - assertThat(e) - .hasMessageContaining("Wanted 1 time") - .hasMessageContaining("was 2 times"); + assertThat(e).hasMessageContaining("Wanted 1 time").hasMessageContaining("was 2 times"); } } @@ -64,7 +60,8 @@ public void shouldDetectActualInvocationsCountIsMoreThanZero() throws Exception try { verify(mock, times(15)).clear(); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } @Test @@ -106,7 +103,8 @@ public void shouldAllowVerifyingInteractionNeverHappened() throws Exception { try { verify(mock, never()).add("one"); fail(); - } catch (NeverWantedButInvoked e) {} + } catch (NeverWantedButInvoked e) { + } } @Test @@ -123,6 +121,7 @@ public void shouldAllowVerifyingInteractionNeverHappenedInOrder() throws Excepti try { inOrder.verify(mock, never()).add("two"); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } } diff --git a/src/test/java/org/mockitousage/verification/FindingRedundantInvocationsInOrderTest.java b/src/test/java/org/mockitousage/verification/FindingRedundantInvocationsInOrderTest.java index 6fcf7d26c5..104f410f85 100644 --- a/src/test/java/org/mockitousage/verification/FindingRedundantInvocationsInOrderTest.java +++ b/src/test/java/org/mockitousage/verification/FindingRedundantInvocationsInOrderTest.java @@ -24,36 +24,36 @@ public class FindingRedundantInvocationsInOrderTest extends TestBase { @Test public void shouldWorkFineIfNoInvocations() throws Exception { - //when + // when InOrder inOrder = inOrder(mock); - //then + // then inOrder.verifyNoMoreInteractions(); } @Test public void shouldSayNoInteractionsWanted() throws Exception { - //when + // when mock.simpleMethod(); - //then + // then InOrder inOrder = inOrder(mock); try { inOrder.verifyNoMoreInteractions(); fail(); - } catch(VerificationInOrderFailure e) { + } catch (VerificationInOrderFailure e) { assertThat(e).hasMessageContaining("No interactions wanted"); } } @Test public void shouldVerifyNoMoreInteractionsInOrder() throws Exception { - //when + // when mock.simpleMethod(); mock.simpleMethod(10); mock.otherMethod(); - //then + // then InOrder inOrder = inOrder(mock); inOrder.verify(mock).simpleMethod(10); inOrder.verify(mock).otherMethod(); @@ -62,12 +62,12 @@ public void shouldVerifyNoMoreInteractionsInOrder() throws Exception { @Test public void shouldVerifyNoMoreInteractionsInOrderWithMultipleMocks() throws Exception { - //when + // when mock.simpleMethod(); mock2.simpleMethod(); mock.otherMethod(); - //then + // then InOrder inOrder = inOrder(mock, mock2); inOrder.verify(mock2).simpleMethod(); inOrder.verify(mock).otherMethod(); @@ -76,47 +76,50 @@ public void shouldVerifyNoMoreInteractionsInOrderWithMultipleMocks() throws Exce @Test public void shouldFailToVerifyNoMoreInteractionsInOrder() throws Exception { - //when + // when mock.simpleMethod(); mock.simpleMethod(10); mock.otherMethod(); - //then + // then InOrder inOrder = inOrder(mock); inOrder.verify(mock).simpleMethod(10); try { inOrder.verifyNoMoreInteractions(); fail(); - } catch(VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test public void shouldFailToVerifyNoMoreInteractionsInOrderWithMultipleMocks() throws Exception { - //when + // when mock.simpleMethod(); mock2.simpleMethod(); mock.otherMethod(); - //then + // then InOrder inOrder = inOrder(mock, mock2); inOrder.verify(mock2).simpleMethod(); try { inOrder.verifyNoMoreInteractions(); fail(); - } catch(VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) @Test public void shouldValidateState() throws Exception { - //when + // when InOrder inOrder = inOrder(mock); verify(mock); // mess up state - //then + // then try { inOrder.verifyNoMoreInteractions(); fail(); - } catch(UnfinishedVerificationException e) {} + } catch (UnfinishedVerificationException e) { + } } } diff --git a/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java b/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java index 841387d789..367975dc4a 100644 --- a/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java @@ -69,7 +69,8 @@ public void shouldFailZeroInteractionsVerification() throws Exception { try { verifyZeroInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -79,7 +80,8 @@ public void shouldFailNoMoreInteractionsVerification() throws Exception { try { verifyNoMoreInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -89,7 +91,8 @@ public void shouldFailNoInteractionsVerification() throws Exception { try { verifyNoInteractions(mock); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -135,7 +138,8 @@ public void shouldVerifyOneMockButFailOnOther() throws Exception { try { verifyZeroInteractions(map); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -154,12 +158,13 @@ public void shouldVerifyOneMockButFailOnOtherVerifyNoInteractions() throws Excep try { verifyNoInteractions(map); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @SuppressWarnings("all") - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void verifyNoMoreInteractionsShouldScreamWhenNullPassed() throws Exception { - verifyNoMoreInteractions((Object[])null); + verifyNoMoreInteractions((Object[]) null); } } diff --git a/src/test/java/org/mockitousage/verification/OnlyVerificationTest.java b/src/test/java/org/mockitousage/verification/OnlyVerificationTest.java index 7385008279..02015e0e2a 100644 --- a/src/test/java/org/mockitousage/verification/OnlyVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/OnlyVerificationTest.java @@ -41,7 +41,8 @@ public void shouldFailIfMethodWasNotInvoked() { try { verify(mock, only()).get(0); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } @Test @@ -51,7 +52,8 @@ public void shouldFailIfMethodWasInvokedMoreThanOnce() { try { verify(mock, only()).clear(); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -61,7 +63,8 @@ public void shouldFailIfMethodWasInvokedButWithDifferentArguments() { try { verify(mock, only()).get(999); fail(); - } catch (WantedButNotInvoked e) {} + } catch (WantedButNotInvoked e) { + } } @Test @@ -71,7 +74,8 @@ public void shouldFailIfExtraMethodWithDifferentArgsFound() { try { verify(mock, only()).get(2); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -81,5 +85,4 @@ public void shouldVerifyMethodWasInvokedExclusivelyWhenTwoMocksInUse() { verify(mock, only()).clear(); verify(mock2, only()).get(0); } - } diff --git a/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java b/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java index 6f912989af..0bf65fa6b6 100644 --- a/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java +++ b/src/test/java/org/mockitousage/verification/OrdinaryVerificationPrintsAllInteractionsTest.java @@ -21,21 +21,22 @@ public class OrdinaryVerificationPrintsAllInteractionsTest extends TestBase { @Test public void shouldShowAllInteractionsOnMockWhenOrdinaryVerificationFail() throws Exception { - //given + // given firstInteraction(); secondInteraction(); - verify(mock).otherMethod(); //verify 1st interaction + verify(mock).otherMethod(); // verify 1st interaction try { - //when + // when verify(mock).simpleMethod(); fail(); } catch (WantedButNotInvoked e) { - //then + // then assertThat(e) - .hasMessageContaining("However, there were exactly 2 interactions with this mock") - .hasMessageContaining("firstInteraction(") - .hasMessageContaining("secondInteraction("); + .hasMessageContaining( + "However, there were exactly 2 interactions with this mock") + .hasMessageContaining("firstInteraction(") + .hasMessageContaining("secondInteraction("); } } @@ -48,7 +49,9 @@ public void shouldNotShowAllInteractionsOnDifferentMock() throws Exception { verify(mock).simpleMethod(); fail(); } catch (WantedButNotInvoked e) { - assertThat(e.getMessage()).contains("firstInteraction(").doesNotContain("differentMockInteraction("); + assertThat(e.getMessage()) + .contains("firstInteraction(") + .doesNotContain("differentMockInteraction("); } } diff --git a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java index 47c409109e..42f644d2a9 100644 --- a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java +++ b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java @@ -20,88 +20,85 @@ public class PrintingVerboseTypesWithArgumentsTest extends TestBase { class Boo { - public void withLong(long x) { - } + public void withLong(long x) {} - public void withLongAndInt(long x, int y) { - } + public void withLongAndInt(long x, int y) {} } @Test public void should_not_report_argument_types_when_to_string_is_the_same() { - //given + // given Boo boo = mock(Boo.class); boo.withLong(100); try { - //when + // when verify(boo).withLong(eq(100)); fail(); } catch (ArgumentsAreDifferent e) { - //then + // then assertThat(e) - .hasMessageContaining("withLong((Integer) 100);") - .hasMessageContaining("withLong((Long) 100L);"); + .hasMessageContaining("withLong((Integer) 100);") + .hasMessageContaining("withLong((Long) 100L);"); } } @Test public void should_show_the_type_of_only_the_argument_that_doesnt_match() { - //given + // given Boo boo = mock(Boo.class); boo.withLongAndInt(100, 200); try { - //when + // when verify(boo).withLongAndInt(eq(100), eq(200)); fail(); } catch (ArgumentsAreDifferent e) { - //then + // then assertThat(e) - .hasMessageContaining("withLongAndInt((Integer) 100, 200)") - .hasMessageContaining("withLongAndInt((Long) 100L, 200)"); + .hasMessageContaining("withLongAndInt((Integer) 100, 200)") + .hasMessageContaining("withLongAndInt((Long) 100L, 200)"); } } @Test - public void should_show_the_type_of_the_mismatching_argument_when_output_descriptions_for_invocations_are_different() { - //given + public void + should_show_the_type_of_the_mismatching_argument_when_output_descriptions_for_invocations_are_different() { + // given Boo boo = mock(Boo.class); boo.withLongAndInt(100, 200); try { - //when + // when verify(boo).withLongAndInt(eq(100), any(Integer.class)); fail(); } catch (ArgumentsAreDifferent e) { - //then + // then Assertions.assertThat(e.getMessage()) - .contains("withLongAndInt(\n" + - " (Long) 100L,\n" + - " 200\n" + - ")") - .contains("withLongAndInt(\n" + - " (Integer) 100,\n" + - " \n" + - ")"); + .contains("withLongAndInt(\n" + " (Long) 100L,\n" + " 200\n" + ")") + .contains( + "withLongAndInt(\n" + + " (Integer) 100,\n" + + " \n" + + ")"); } } @Test public void should_not_show_types_when_argument_value_is_different() { - //given + // given Boo boo = mock(Boo.class); boo.withLongAndInt(100, 200); try { - //when + // when verify(boo).withLongAndInt(eq(100L), eq(230)); fail(); } catch (ArgumentsAreDifferent e) { - //then + // then assertThat(e) - .hasMessageContaining("withLongAndInt(100L, 200)") - .hasMessageContaining("withLongAndInt(100L, 230)"); + .hasMessageContaining("withLongAndInt(100L, 200)") + .hasMessageContaining("withLongAndInt(100L, 230)"); } } @@ -127,17 +124,18 @@ public String toString() { } @Test - public void should_not_show_types_when_types_are_the_same_even_if_to_string_gives_the_same_result() { - //given + public void + should_not_show_types_when_types_are_the_same_even_if_to_string_gives_the_same_result() { + // given IMethods mock = mock(IMethods.class); mock.simpleMethod(new Foo(10)); try { - //when + // when verify(mock).simpleMethod(new Foo(20)); fail(); } catch (ArgumentsAreDifferent e) { - //then + // then assertThat(e).hasMessageContaining("simpleMethod(foo)"); } } diff --git a/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java index c4744cfaf9..ea172ce0ac 100644 --- a/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java +++ b/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java @@ -69,7 +69,8 @@ public void shouldAllowFirstChunkBeforeLastInvocation() { try { verifyNoMoreInteractions(mockTwo); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -87,7 +88,8 @@ public void shouldVerifyDetectFirstChunkOfInvocationThatExistInManyChunks() { try { verifyNoMoreInteractions(mockTwo); fail(); - } catch(NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -104,7 +106,8 @@ public void shouldVerifyInteractionsFromAllChunksWhenAtLeastOnceMode() { try { inOrder.verify(mockThree).simpleMethod(3); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -113,10 +116,11 @@ public void shouldVerifyInteractionsFromFirstChunk() { try { verifyNoMoreInteractions(mockTwo); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } - @Test(expected=VerificationInOrderFailure.class) + @Test(expected = VerificationInOrderFailure.class) public void shouldFailVerificationOfNonFirstChunk() { inOrder.verify(mockTwo, times(1)).simpleMethod(2); } @@ -181,7 +185,7 @@ public void shouldVerifyMockTwoCalledAtLeastOnce() { inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(2); } - @Test(expected=WantedButNotInvoked.class) + @Test(expected = WantedButNotInvoked.class) public void shouldFailOnWrongMethodCalledOnMockTwo() { inOrder.verify(mockTwo, atLeastOnce()).differentMethod(); } @@ -194,7 +198,8 @@ public void shouldAllowTimesZeroButOnlyInOrder() { try { verify(mockOne, times(0)).simpleMethod(1); fail(); - } catch (NeverWantedButInvoked e) {} + } catch (NeverWantedButInvoked e) { + } } @Test @@ -203,10 +208,11 @@ public void shouldFailTimesZeroInOrder() { try { inOrder.verify(mockThree, times(0)).simpleMethod(3); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } - @Test(expected=VerificationInOrderFailure.class) + @Test(expected = VerificationInOrderFailure.class) public void shouldFailWhenMockTwoWantedZeroTimes() { inOrder.verify(mockTwo, times(0)).simpleMethod(2); } @@ -234,7 +240,8 @@ public void shouldFailOnLastTwoInvocationsInWrongOrder() { try { inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(2); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -243,7 +250,8 @@ public void shouldFailOnLastAndFirstInWrongOrder() { try { inOrder.verify(mockOne).simpleMethod(1); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -252,6 +260,7 @@ public void shouldFailOnWrongMethodAfterLastInvocation() { try { inOrder.verify(mockOne).simpleMethod(999); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } } diff --git a/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java b/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java index 68292b9066..39e5fdf558 100644 --- a/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java @@ -84,7 +84,8 @@ public void shouldFailVerificationForMockOne() { try { inOrder.verify(mockOne).differentMethod(); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -95,7 +96,8 @@ public void shouldFailVerificationForMockOneBecauseOfWrongOrder() { try { inOrder.verify(mockOne).simpleMethod(1); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -123,7 +125,8 @@ public void shouldFailVerificationForMockTwo() { try { inOrder.verify(mockTwo).simpleMethod(2); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -133,7 +136,8 @@ public void shouldThrowNoMoreInvocationsForMockTwo() { try { inOrder.verify(mockTwo, times(2)).simpleMethod(2); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -143,7 +147,8 @@ public void shouldThrowTooFewInvocationsForMockTwo() { try { inOrder.verify(mockTwo, times(4)).simpleMethod(2); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -153,7 +158,8 @@ public void shouldThrowTooManyInvocationsForMockTwo() { try { inOrder.verify(mockTwo, times(2)).simpleMethod(2); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -182,6 +188,7 @@ public void shouldAllowTwoTimesOnMockTwo() { try { verifyNoMoreInteractions(mockTwo); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } } diff --git a/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java b/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java index 75270ff537..9bad45ad37 100644 --- a/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java @@ -22,35 +22,39 @@ public class VerificationExcludingStubsTest extends TestBase { @Test public void shouldAllowToExcludeStubsForVerification() throws Exception { - //given + // given when(mock.simpleMethod()).thenReturn("foo"); - //when - String stubbed = mock.simpleMethod(); //irrelevant call because it is stubbing + // when + String stubbed = mock.simpleMethod(); // irrelevant call because it is stubbing mock.objectArgMethod(stubbed); - //then + // then verify(mock).objectArgMethod("foo"); - //verifyNoMoreInteractions fails: - try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) {} + // verifyNoMoreInteractions fails: + try { + verifyNoMoreInteractions(mock); + fail(); + } catch (NoInteractionsWanted e) { + } - //but it works when stubs are ignored: + // but it works when stubs are ignored: ignoreStubs(mock); verifyNoMoreInteractions(mock); } @Test public void shouldExcludeFromVerificationInOrder() throws Exception { - //given + // given when(mock.simpleMethod()).thenReturn("foo"); - //when + // when mock.objectArgMethod("1"); mock.objectArgMethod("2"); - mock.simpleMethod(); //calling the stub + mock.simpleMethod(); // calling the stub - //then + // then InOrder inOrder = inOrder(ignoreStubs(mock)); inOrder.verify(mock).objectArgMethod("1"); inOrder.verify(mock).objectArgMethod("2"); @@ -67,5 +71,4 @@ public void shouldIgnoringStubsDetectNulls() throws Exception { public void shouldIgnoringStubsDetectNonMocks() throws Exception { ignoreStubs(mock, new Object()); } - } diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java index dd11f92172..c03d63fd1a 100644 --- a/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java @@ -82,7 +82,8 @@ public void shouldFailOnNoMoreInteractions() { try { verifyNoMoreInteractions(mockOne, mockTwo, mockThree); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -94,7 +95,8 @@ public void shouldFailOnNoMoreInteractionsOnMockVerifiedInOrder() { try { verifyNoMoreInteractions(mockOne, mockTwo, mockThree); fail(); - } catch (NoInteractionsWanted e) {} + } catch (NoInteractionsWanted e) { + } } @Test @@ -115,10 +117,11 @@ public void shouldFailOnLastInvocationTooEarly() { try { inOrder.verify(mockOne, atLeastOnce()).simpleMethod(1); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } - @Test(expected=MockitoException.class) + @Test(expected = MockitoException.class) public void shouldScreamWhenUnfamiliarMockPassedToInOrderObject() { inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(1); } diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderTest.java index a997d1c5ac..030ac0d9a3 100644 --- a/src/test/java/org/mockitousage/verification/VerificationInOrderTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationInOrderTest.java @@ -47,7 +47,8 @@ public void shouldVerifySingleMockInOrderAndNotInOrder() { try { inOrder.verify(mockOne).simpleMethod(1); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -77,7 +78,8 @@ public void shouldVerifyInOrderWhenTwoChunksAreEqual() { try { inOrder.verify(mockOne, atLeastOnce()).simpleMethod(); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } @Test @@ -96,6 +98,7 @@ public void shouldVerifyInOrderUsingMatcher() { try { inOrder.verify(mockOne, times(3)).simpleMethod(anyInt()); fail(); - } catch (VerificationInOrderFailure e) {} + } catch (VerificationInOrderFailure e) { + } } } diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java index 0a92cd6e04..ce5f742bbc 100644 --- a/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java @@ -21,123 +21,121 @@ public class VerificationInOrderWithCallsTest extends TestBase { @Mock private IMethods mockOne; @Mock private IMethods mockTwo; - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); + @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test - public void shouldFailWhenMethodNotCalled(){ + public void shouldFailWhenMethodNotCalled() { // Given - mockOne.oneArg( 1 ); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + mockOne.oneArg(1); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "Verification in order failure" ); - exceptionRule.expectMessage( "Wanted but not invoked" ); - exceptionRule.expectMessage( "mockOne.oneArg(2)" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("Verification in order failure"); + exceptionRule.expectMessage("Wanted but not invoked"); + exceptionRule.expectMessage("mockOne.oneArg(2)"); // When - verifier.verify( mockOne, calls(1)).oneArg( 2 ); + verifier.verify(mockOne, calls(1)).oneArg(2); // Then - expected exception thrown } @Test - public void shouldFailWhenMethodCalledTooFewTimes(){ + public void shouldFailWhenMethodCalledTooFewTimes() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); + mockOne.oneArg(1); + mockOne.oneArg(2); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "Verification in order failure" ); - exceptionRule.expectMessage( "mockOne.oneArg(2)" ); - exceptionRule.expectMessage( "Wanted 2 times" ); - exceptionRule.expectMessage( "But was 1 time" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("Verification in order failure"); + exceptionRule.expectMessage("mockOne.oneArg(2)"); + exceptionRule.expectMessage("Wanted 2 times"); + exceptionRule.expectMessage("But was 1 time"); // When - verifier.verify( mockOne, calls(2)).oneArg( 2 ); + verifier.verify(mockOne, calls(2)).oneArg(2); // Then - expected exception thrown } @Test - public void shouldFailWhenSingleMethodCallsAreOutOfSequence(){ + public void shouldFailWhenSingleMethodCallsAreOutOfSequence() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); + mockOne.oneArg(1); + mockOne.oneArg(2); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 2 ); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(2); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "Verification in order failure" ); - exceptionRule.expectMessage( "Wanted but not invoked" ); - exceptionRule.expectMessage( "mockOne.oneArg(1)" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("Verification in order failure"); + exceptionRule.expectMessage("Wanted but not invoked"); + exceptionRule.expectMessage("mockOne.oneArg(1)"); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + verifier.verify(mockOne, calls(1)).oneArg(1); // Then - expected exception thrown } @Test - public void shouldFailWhenDifferentMethodCallsAreOutOfSequence(){ + public void shouldFailWhenDifferentMethodCallsAreOutOfSequence() { // Given - mockOne.oneArg( 1 ); + mockOne.oneArg(1); mockOne.voidMethod(); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).voidMethod(); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).voidMethod(); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "Verification in order failure" ); - exceptionRule.expectMessage( "Wanted but not invoked" ); - exceptionRule.expectMessage( "mockOne.oneArg(1)" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("Verification in order failure"); + exceptionRule.expectMessage("Wanted but not invoked"); + exceptionRule.expectMessage("mockOne.oneArg(1)"); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + verifier.verify(mockOne, calls(1)).oneArg(1); // Then - expected exception thrown } @Test - public void shouldFailWhenMethodCallsOnDifferentMocksAreOutOfSequence(){ + public void shouldFailWhenMethodCallsOnDifferentMocksAreOutOfSequence() { // Given mockOne.voidMethod(); mockTwo.voidMethod(); - InOrder verifier = inOrder( mockOne, mockTwo ); - verifier.verify( mockTwo, calls(1)).voidMethod(); + InOrder verifier = inOrder(mockOne, mockTwo); + verifier.verify(mockTwo, calls(1)).voidMethod(); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "Verification in order failure" ); - exceptionRule.expectMessage( "Wanted but not invoked" ); - exceptionRule.expectMessage( "mockOne.voidMethod()" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("Verification in order failure"); + exceptionRule.expectMessage("Wanted but not invoked"); + exceptionRule.expectMessage("mockOne.voidMethod()"); // When - verifier.verify( mockOne, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).voidMethod(); // Then - expected exception thrown } - @Test - public void shouldAllowSequentialCallsToCallsForSingleMethod(){ + public void shouldAllowSequentialCallsToCallsForSingleMethod() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(2)).oneArg( 2 ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(2)).oneArg(2); + verifier.verify(mockOne, calls(1)).oneArg(1); verifyNoMoreInteractions(mockOne); verifier.verifyNoMoreInteractions(); @@ -145,19 +143,19 @@ public void shouldAllowSequentialCallsToCallsForSingleMethod(){ } @Test - public void shouldAllowSequentialCallsToCallsForDifferentMethods(){ + public void shouldAllowSequentialCallsToCallsForDifferentMethods() { // Given - mockOne.oneArg( 1 ); + mockOne.oneArg(1); mockOne.voidMethod(); mockOne.voidMethod(); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(2)).voidMethod(); - verifier.verify( mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(2)).voidMethod(); + verifier.verify(mockOne, calls(1)).oneArg(1); verifyNoMoreInteractions(mockOne); verifier.verifyNoMoreInteractions(); @@ -165,19 +163,19 @@ public void shouldAllowSequentialCallsToCallsForDifferentMethods(){ } @Test - public void shouldAllowSequentialCallsToCallsForMethodsOnDifferentMocks(){ + public void shouldAllowSequentialCallsToCallsForMethodsOnDifferentMocks() { // Given mockOne.voidMethod(); mockTwo.voidMethod(); mockTwo.voidMethod(); mockOne.voidMethod(); - InOrder verifier = inOrder( mockOne, mockTwo ); + InOrder verifier = inOrder(mockOne, mockTwo); // When - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockTwo, calls(2)).voidMethod(); - verifier.verify( mockOne, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockTwo, calls(2)).voidMethod(); + verifier.verify(mockOne, calls(1)).voidMethod(); verifyNoMoreInteractions(mockOne); verifyNoMoreInteractions(mockTwo); verifier.verifyNoMoreInteractions(); @@ -185,61 +183,60 @@ public void shouldAllowSequentialCallsToCallsForMethodsOnDifferentMocks(){ // Then - no exception thrown } - @Test - public void shouldAllowFewerCallsForSingleMethod(){ + public void shouldAllowFewerCallsForSingleMethod() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); + mockOne.oneArg(1); + mockOne.oneArg(2); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).oneArg( 2 ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).oneArg( 2 ); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).oneArg(2); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).oneArg(2); // Then - no exception thrown } @Test - public void shouldNotVerifySkippedCallsWhenFewerCallsForSingleMethod(){ + public void shouldNotVerifySkippedCallsWhenFewerCallsForSingleMethod() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).oneArg( 2 ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).oneArg(2); + verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect( NoInteractionsWanted.class ); + exceptionRule.expect(NoInteractionsWanted.class); // When - verifyNoMoreInteractions( mockOne ); + verifyNoMoreInteractions(mockOne); // Then - expected exception thrown } @Test - public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForSingleMethod(){ + public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForSingleMethod() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).oneArg( 2 ); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).oneArg(2); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "No interactions wanted here" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("No interactions wanted here"); // When verifier.verifyNoMoreInteractions(); @@ -248,59 +245,59 @@ public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForSingleMethod(){ } @Test - public void shouldAllowFewerCallsForDifferentMethods(){ + public void shouldAllowFewerCallsForDifferentMethods() { // Given - mockOne.oneArg( 1 ); + mockOne.oneArg(1); mockOne.voidMethod(); mockOne.voidMethod(); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); mockOne.voidMethod(); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).voidMethod(); // Then - no exception thrown } @Test - public void shouldNotVerifySkippedCallsWhenFewerCallsForDifferentMethods(){ + public void shouldNotVerifySkippedCallsWhenFewerCallsForDifferentMethods() { // Given - mockOne.oneArg( 1 ); + mockOne.oneArg(1); mockOne.voidMethod(); mockOne.voidMethod(); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect( NoInteractionsWanted.class ); + exceptionRule.expect(NoInteractionsWanted.class); // When - verifyNoMoreInteractions( mockOne ); + verifyNoMoreInteractions(mockOne); // Then - no exception thrown } @Test - public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForDifferentMethods(){ + public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForDifferentMethods() { // Given - mockOne.oneArg( 1 ); + mockOne.oneArg(1); mockOne.voidMethod(); mockOne.voidMethod(); - InOrder verifier = inOrder( mockOne ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(1)).voidMethod(); + InOrder verifier = inOrder(mockOne); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, calls(1)).voidMethod(); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "No interactions wanted here" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("No interactions wanted here"); // When verifier.verifyNoMoreInteractions(); @@ -309,7 +306,7 @@ public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForDifferentMethod } @Test - public void shouldAllowFewerCallsForMethodsOnDifferentMocks(){ + public void shouldAllowFewerCallsForMethodsOnDifferentMocks() { // Given mockOne.voidMethod(); mockTwo.voidMethod(); @@ -317,51 +314,51 @@ public void shouldAllowFewerCallsForMethodsOnDifferentMocks(){ mockOne.voidMethod(); mockTwo.voidMethod(); - InOrder verifier = inOrder( mockOne, mockTwo ); + InOrder verifier = inOrder(mockOne, mockTwo); // When - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockTwo, calls(1)).voidMethod(); - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockTwo, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockTwo, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockTwo, calls(1)).voidMethod(); // Then - no exception thrown } @Test - public void shouldNotVerifySkippedCallsWhenFewerCallsForMethodsOnDifferentMocks(){ + public void shouldNotVerifySkippedCallsWhenFewerCallsForMethodsOnDifferentMocks() { // Given mockOne.voidMethod(); mockTwo.voidMethod(); mockTwo.voidMethod(); mockOne.voidMethod(); - InOrder verifier = inOrder( mockOne, mockTwo ); - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockTwo, calls(1)).voidMethod(); - verifier.verify( mockOne, calls(1)).voidMethod(); + InOrder verifier = inOrder(mockOne, mockTwo); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockTwo, calls(1)).voidMethod(); + verifier.verify(mockOne, calls(1)).voidMethod(); exceptionRule.expect(NoInteractionsWanted.class); // When - verifyNoMoreInteractions( mockTwo ); + verifyNoMoreInteractions(mockTwo); // Then - expected exception thrown } @Test - public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForMethodsOnDifferentMocks(){ + public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForMethodsOnDifferentMocks() { // Given mockOne.voidMethod(); mockTwo.voidMethod(); mockTwo.voidMethod(); - InOrder verifier = inOrder( mockOne, mockTwo ); - verifier.verify( mockOne, calls(1)).voidMethod(); - verifier.verify( mockTwo, calls(1)).voidMethod(); + InOrder verifier = inOrder(mockOne, mockTwo); + verifier.verify(mockOne, calls(1)).voidMethod(); + verifier.verify(mockTwo, calls(1)).voidMethod(); - exceptionRule.expect( VerificationInOrderFailure.class ); - exceptionRule.expectMessage( "No interactions wanted here" ); + exceptionRule.expect(VerificationInOrderFailure.class); + exceptionRule.expectMessage("No interactions wanted here"); // When verifier.verifyNoMoreInteractions(); @@ -370,127 +367,127 @@ public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForMethodsOnDiffer } @Test - public void shouldVerifyWithCallsAfterUseOfTimes(){ + public void shouldVerifyWithCallsAfterUseOfTimes() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, times(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(2)).oneArg( 2 ); - verifier.verify( mockOne, calls(1)).oneArg( 1 ); + verifier.verify(mockOne, times(1)).oneArg(1); + verifier.verify(mockOne, calls(2)).oneArg(2); + verifier.verify(mockOne, calls(1)).oneArg(1); // Then - no exception thrown } @Test - public void shouldVerifyWithCallsAfterUseOfAtLeast(){ + public void shouldVerifyWithCallsAfterUseOfAtLeast() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, atLeast(1)).oneArg( 1 ); - verifier.verify( mockOne, calls(2)).oneArg( 2 ); + verifier.verify(mockOne, atLeast(1)).oneArg(1); + verifier.verify(mockOne, calls(2)).oneArg(2); // Then - no exception thrown } @Test - public void shouldVerifyWithTimesAfterUseOfCalls(){ + public void shouldVerifyWithTimesAfterUseOfCalls() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, times(2)).oneArg( 2 ); - verifier.verify( mockOne, times(1)).oneArg( 1 ); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, times(2)).oneArg(2); + verifier.verify(mockOne, times(1)).oneArg(1); // Then - no exception thrown } @Test - public void shouldVerifyWithAtLeastAfterUseOfCalls(){ + public void shouldVerifyWithAtLeastAfterUseOfCalls() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 2 ); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); + mockOne.oneArg(2); + mockOne.oneArg(2); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, atLeast(1)).oneArg( 2 ); - verifier.verify( mockOne, atLeast(1)).oneArg( 1 ); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, atLeast(1)).oneArg(2); + verifier.verify(mockOne, atLeast(1)).oneArg(1); // Then - no exception thrown } @Test - public void shouldVerifyWithTimesAfterCallsInSameChunk(){ + public void shouldVerifyWithTimesAfterCallsInSameChunk() { // Given - mockOne.oneArg( 1 ); - mockOne.oneArg( 1 ); - mockOne.oneArg( 1 ); + mockOne.oneArg(1); + mockOne.oneArg(1); + mockOne.oneArg(1); - InOrder verifier = inOrder( mockOne ); + InOrder verifier = inOrder(mockOne); // When - verifier.verify( mockOne, calls(1)).oneArg( 1 ); - verifier.verify( mockOne, times(2)).oneArg( 1 ); + verifier.verify(mockOne, calls(1)).oneArg(1); + verifier.verify(mockOne, times(2)).oneArg(1); verifier.verifyNoMoreInteractions(); // Then - no exception thrown } @Test - public void shouldFailToCreateCallsWithZeroArgument(){ + public void shouldFailToCreateCallsWithZeroArgument() { // Given - InOrder verifier = inOrder( mockOne ); - exceptionRule.expect( MockitoException.class ); - exceptionRule.expectMessage( "Negative and zero values are not allowed here" ); + InOrder verifier = inOrder(mockOne); + exceptionRule.expect(MockitoException.class); + exceptionRule.expectMessage("Negative and zero values are not allowed here"); // When - verifier.verify( mockOne, calls(0)).voidMethod(); + verifier.verify(mockOne, calls(0)).voidMethod(); // Then - expected exception thrown } @Test - public void shouldFailToCreateCallsWithNegativeArgument(){ + public void shouldFailToCreateCallsWithNegativeArgument() { // Given - InOrder verifier = inOrder( mockOne ); - exceptionRule.expect( MockitoException.class ); - exceptionRule.expectMessage( "Negative and zero values are not allowed here" ); + InOrder verifier = inOrder(mockOne); + exceptionRule.expect(MockitoException.class); + exceptionRule.expectMessage("Negative and zero values are not allowed here"); // When - verifier.verify( mockOne, calls(-1)).voidMethod(); + verifier.verify(mockOne, calls(-1)).voidMethod(); // Then - expected exception thrown } @Test - public void shouldFailToCreateCallsForNonInOrderVerification(){ + public void shouldFailToCreateCallsForNonInOrderVerification() { // Given mockOne.voidMethod(); - exceptionRule.expect( MockitoException.class ); - exceptionRule.expectMessage( "calls is only intended to work with InOrder" ); + exceptionRule.expect(MockitoException.class); + exceptionRule.expectMessage("calls is only intended to work with InOrder"); // When - verify( mockOne, calls(1)).voidMethod(); + verify(mockOne, calls(1)).voidMethod(); // Then - expected exception thrown } diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java index 1d29839b1e..121399d1e1 100644 --- a/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java @@ -32,23 +32,28 @@ public class VerificationInOrderWithTimeoutTest { private AsyncTesting async; - @Before public void setUp() { + @Before + public void setUp() { async = new AsyncTesting(); } - @After public void tearDown() { + @After + public void tearDown() { async.cleanUp(); } @Test public void should_not_allow_in_order_with_after() { // expect - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - inOrder(mock1).verify(mock1, after(100)).oneArg('a'); - } - }).isInstanceOf(MockitoException.class).hasMessageContaining("not implemented to work with InOrder"); - //TODO specific exception + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + inOrder(mock1).verify(mock1, after(100)).oneArg('a'); + } + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("not implemented to work with InOrder"); + // TODO specific exception } @Test @@ -73,13 +78,16 @@ public void should_verify_in_order_with_timeout_and_fail() { // then final InOrder inOrder = inOrder(mock1, mock2); inOrder.verify(mock2, timeout(300)).oneArg('b'); - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - inOrder.verify(mock1, timeout(300)).oneArg('a'); - } - }).isInstanceOf(VerificationInOrderFailure.class) - .hasMessageContaining("Wanted but not invoked:\nmock1.oneArg('a');") - .hasMessageContaining("Wanted anywhere AFTER following interaction:\nmock2.oneArg('b');"); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + inOrder.verify(mock1, timeout(300)).oneArg('a'); + } + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("Wanted but not invoked:\nmock1.oneArg('a');") + .hasMessageContaining( + "Wanted anywhere AFTER following interaction:\nmock2.oneArg('b');"); } @Test @@ -108,24 +116,30 @@ public void should_verify_in_order_with_times_x_and_fail() { final InOrder inOrder = inOrder(mock1, mock2); inOrder.verify(mock2, timeout(500).times(2)).oneArg('b'); - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - inOrder.verify(mock1, timeout(100).times(2)).oneArg('a'); - } - }).isInstanceOf(VerificationInOrderFailure.class) - .hasMessageContaining("Wanted but not invoked:\nmock1.oneArg('a');") - .hasMessageContaining("Wanted anywhere AFTER following interaction:\nmock2.oneArg('b');"); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + inOrder.verify(mock1, timeout(100).times(2)).oneArg('a'); + } + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("Wanted but not invoked:\nmock1.oneArg('a');") + .hasMessageContaining( + "Wanted anywhere AFTER following interaction:\nmock2.oneArg('b');"); } @Test public void should_not_allow_in_order_with_only() { - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() throws Throwable { - inOrder(mock1).verify(mock1, timeout(200).only()).oneArg('a'); - } - }).isInstanceOf(MockitoException.class).hasMessageContaining("not implemented to work with InOrder"); - //TODO specific exception + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() throws Throwable { + inOrder(mock1).verify(mock1, timeout(200).only()).oneArg('a'); + } + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("not implemented to work with InOrder"); + // TODO specific exception } @Test @@ -153,13 +167,16 @@ public void should_verify_in_order_with_at_least_once_and_fail() { // then final InOrder inOrder = inOrder(mock1, mock2); inOrder.verify(mock2, timeout(300).atLeastOnce()).oneArg('b'); - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - inOrder.verify(mock1, timeout(500).atLeastOnce()).oneArg('a'); - } - }).isInstanceOf(VerificationInOrderFailure.class) - .hasMessageContaining("Wanted but not invoked:\nmock1.oneArg('a');") - .hasMessageContaining("Wanted anywhere AFTER following interaction:\nmock2.oneArg('b');"); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + inOrder.verify(mock1, timeout(500).atLeastOnce()).oneArg('a'); + } + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("Wanted but not invoked:\nmock1.oneArg('a');") + .hasMessageContaining( + "Wanted anywhere AFTER following interaction:\nmock2.oneArg('b');"); } @Test @@ -187,12 +204,14 @@ public void should_verify_in_order_with_at_least_x_and_fail() { // then final InOrder inOrder = inOrder(mock1, mock2); inOrder.verify(mock2, timeout(300).atLeast(2)).oneArg('b'); - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - inOrder.verify(mock1, timeout(500).atLeast(2)).oneArg('a'); - } - }).isInstanceOf(AssertionError.class) - .hasMessageContaining("Verification in order failure"); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + inOrder.verify(mock1, timeout(500).atLeast(2)).oneArg('a'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("Verification in order failure"); } private Runnable callMock(final IMethods mock, final char c) { diff --git a/src/test/java/org/mockitousage/verification/VerificationStartedListenerTest.java b/src/test/java/org/mockitousage/verification/VerificationStartedListenerTest.java index 6f93458989..5d585f4291 100644 --- a/src/test/java/org/mockitousage/verification/VerificationStartedListenerTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationStartedListenerTest.java @@ -30,98 +30,124 @@ public class VerificationStartedListenerTest extends TestBase { @Test public void verified_mock_can_be_replaced() throws Exception { - //given + // given final List mock1 = mock(List.class); - mock1.clear(); //register clear() on mock1 - - //when - List mock2 = mock(List.class, Mockito.withSettings().verificationStartedListeners(new VerificationStartedListener() { - public void onVerificationStarted(VerificationStartedEvent event) { - //this is a hack to simulate desired behavior - event.setMock(mock1); - } - })); - - //then verified mock is not mock2 that was passed to 'verify' but the replacement: mock1 + mock1.clear(); // register clear() on mock1 + + // when + List mock2 = + mock( + List.class, + Mockito.withSettings() + .verificationStartedListeners( + new VerificationStartedListener() { + public void onVerificationStarted( + VerificationStartedEvent event) { + // this is a hack to simulate desired behavior + event.setMock(mock1); + } + })); + + // then verified mock is not mock2 that was passed to 'verify' but the replacement: mock1 List verifiedMock = verify(mock2); assertEquals(mock1, verifiedMock); - //and verification is successful because mock1.clear() was called + // and verification is successful because mock1.clear() was called verifiedMock.clear(); - //this test is admittedly contrived. it's goal is to provide coverage for the key functionality of the listener - //see the discussion at https://github.com/mockito/mockito/issues/1191 + // this test is admittedly contrived. it's goal is to provide coverage for the key + // functionality of the listener + // see the discussion at https://github.com/mockito/mockito/issues/1191 } @Test public void verification_started_event_contains_correct_mock() throws Exception { - //given + // given final List container = new ArrayList(); - List mock = mock(List.class, Mockito.withSettings().verificationStartedListeners(new VerificationStartedListener() { - public void onVerificationStarted(VerificationStartedEvent event) { - //this is a hack to simulate desired behavior - container.add(event.getMock()); - } - })); - - //when + List mock = + mock( + List.class, + Mockito.withSettings() + .verificationStartedListeners( + new VerificationStartedListener() { + public void onVerificationStarted( + VerificationStartedEvent event) { + // this is a hack to simulate desired behavior + container.add(event.getMock()); + } + })); + + // when verify(mock, never()).clear(); - //then + // then Assertions.assertThat(container).containsExactly(mock); } @Test public void listeners_are_executed_in_sequence() throws Exception { - //given + // given final List container = new ArrayList(); final List mock1 = mock(List.class); - List mock2 = mock(List.class, Mockito.withSettings().verificationStartedListeners(new VerificationStartedListener() { - public void onVerificationStarted(VerificationStartedEvent event) { - //this is a hack to simulate desired behavior - container.add(event.getMock()); - event.setMock(mock1); - } - }, new VerificationStartedListener() { - @Override - public void onVerificationStarted(VerificationStartedEvent event) { - container.add(event.getMock()); - } - })); - - //when + List mock2 = + mock( + List.class, + Mockito.withSettings() + .verificationStartedListeners( + new VerificationStartedListener() { + public void onVerificationStarted( + VerificationStartedEvent event) { + // this is a hack to simulate desired behavior + container.add(event.getMock()); + event.setMock(mock1); + } + }, + new VerificationStartedListener() { + @Override + public void onVerificationStarted( + VerificationStartedEvent event) { + container.add(event.getMock()); + } + })); + + // when verify(mock2, never()).clear(); - //ensure that: + // ensure that: // 1. listeners were notified in sequence // 2. the state set by 1st listeners affects 2nd listener Assertions.assertThat(container).containsExactly(mock2, mock1); - //there is no particular reason we decided on that behavior - //we want to have a consistent and documented behavior of the verification started listener + // there is no particular reason we decided on that behavior + // we want to have a consistent and documented behavior of the verification started listener } @Test public void shows_clean_exception_when_null_array_passed() throws Exception { try { - //when + // when Mockito.withSettings().verificationStartedListeners(null); fail(); } catch (MockitoException e) { - assertEquals("verificationStartedListeners() does not accept null vararg array. See the Javadoc.", e.getMessage()); + assertEquals( + "verificationStartedListeners() does not accept null vararg array. See the Javadoc.", + e.getMessage()); } } @Test public void shows_clean_exception_when_null_listener_passed() throws Exception { try { - //when - Mockito.withSettings().verificationStartedListeners(mock(VerificationStartedListener.class), null); + // when + Mockito.withSettings() + .verificationStartedListeners(mock(VerificationStartedListener.class), null); fail(); } catch (MockitoException e) { - assertEquals("verificationStartedListeners() does not accept null listeners. See the Javadoc.", e.getMessage()); + assertEquals( + "verificationStartedListeners() does not accept null listeners. See the Javadoc.", + e.getMessage()); } } } diff --git a/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java b/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java index 4b7493c147..85d37dd924 100644 --- a/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java @@ -67,7 +67,9 @@ public void shouldVerifyUsingMixedMatchers() { mock.threeArgumentMethod(11, "", "01234"); try { - verify(mock).threeArgumentMethod(and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); + verify(mock) + .threeArgumentMethod( + and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); fail(); } catch (ArgumentsAreDifferent e) { } @@ -75,7 +77,9 @@ public void shouldVerifyUsingMixedMatchers() { mock.threeArgumentMethod(8, new Object(), "01234"); try { - verify(mock).threeArgumentMethod(and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); + verify(mock) + .threeArgumentMethod( + and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); fail(); } catch (ArgumentsAreDifferent e) { } @@ -83,13 +87,17 @@ public void shouldVerifyUsingMixedMatchers() { mock.threeArgumentMethod(8, "", "no match"); try { - verify(mock).threeArgumentMethod(and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); + verify(mock) + .threeArgumentMethod( + and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); fail(); } catch (ArgumentsAreDifferent e) { } mock.threeArgumentMethod(8, "", "123"); - verify(mock).threeArgumentMethod(and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); + verify(mock) + .threeArgumentMethod( + and(geq(7), leq(10)), isA(String.class), Matchers.contains("123")); } } diff --git a/src/test/java/org/mockitousage/verification/VerificationWithAfterAndCaptorTest.java b/src/test/java/org/mockitousage/verification/VerificationWithAfterAndCaptorTest.java index 1dfdffb465..d173812e57 100644 --- a/src/test/java/org/mockitousage/verification/VerificationWithAfterAndCaptorTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationWithAfterAndCaptorTest.java @@ -62,7 +62,7 @@ public void shouldReturnListOfArgumentsWithSameSizeAsGivenInTimesVerification() // when exerciseMockNTimes(n); - //Then + // Then verify(mock, after(200).times(n)).oneArg((char) captor.capture()); assertEquals(n, captor.getAllValues().size()); assertEquals('0', (char) captor.getAllValues().get(0)); @@ -79,7 +79,7 @@ public void shouldReturnListOfArgumentsWithSameSizeAsGivenInAtLeastVerification( // when exerciseMockNTimes(n); - //Then + // Then verify(mock, after(200).atLeast(n)).oneArg((char) captor.capture()); assertEquals(n, captor.getAllValues().size()); assertEquals('0', (char) captor.getAllValues().get(0)); diff --git a/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java b/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java index bb7f105cc8..4fb65530b1 100644 --- a/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java @@ -33,16 +33,18 @@ public class VerificationWithAfterTest { @Mock private IMethods mock; - private Runnable callMock = new Runnable() { - public void run() { - mock.oneArg('1'); - } - }; + private Runnable callMock = + new Runnable() { + public void run() { + mock.oneArg('1'); + } + }; private AsyncTesting async = new AsyncTesting(); private Stopwatch watch = createNotStarted(); - @After public void tearDown() { + @After + public void tearDown() { async.cleanUp(); } @@ -63,12 +65,14 @@ public void should_verify_with_after_and_fail() { async.runAfter(40, callMock); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(600)).oneArg('1'); - } - }).isInstanceOf(TooManyActualInvocations.class); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(600)).oneArg('1'); + } + }) + .isInstanceOf(TooManyActualInvocations.class); } @Test @@ -90,12 +94,14 @@ public void should_verify_with_time_x_and_fail() { async.runAfter(80, callMock); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(300).times(2)).oneArg('1'); - } - }).isInstanceOf(TooManyActualInvocations.class); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(300).times(2)).oneArg('1'); + } + }) + .isInstanceOf(TooManyActualInvocations.class); } @Test @@ -116,12 +122,15 @@ public void should_verify_with_at_least_and_fail() { async.runAfter(600, callMock); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(300).atLeast(3)).oneArg('1'); - } - }).isInstanceOf(AssertionError.class).hasMessageContaining("Wanted *at least* 3 times"); //TODO specific exception + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(300).atLeast(3)).oneArg('1'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("Wanted *at least* 3 times"); // TODO specific exception } @Test @@ -143,12 +152,15 @@ public void should_verify_with_at_most_and_fail() { async.runAfter(600, callMock); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(300).atMost(1)).oneArg('1'); - } - }).isInstanceOf(AssertionError.class).hasMessageContaining("Wanted at most 1 time but was 2"); //TODO specific exception + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(300).atMost(1)).oneArg('1'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("Wanted at most 1 time but was 2"); // TODO specific exception } @Test @@ -166,12 +178,15 @@ public void should_verify_with_never_and_fail() { async.runAfter(10, callMock); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(300).never()).oneArg('1'); - } - }).isInstanceOf(MoreThanAllowedActualInvocations.class).hasMessageContaining("Wanted at most 0 times but was 1"); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(300).never()).oneArg('1'); + } + }) + .isInstanceOf(MoreThanAllowedActualInvocations.class) + .hasMessageContaining("Wanted at most 0 times but was 1"); } @Test @@ -191,12 +206,15 @@ public void should_verify_with_only_and_fail() { async.runAfter(50, callMock); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(300).only()).oneArg('1'); - } - }).isInstanceOf(AssertionError.class).hasMessageContaining("No interactions wanted here"); //TODO specific exception + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(300).only()).oneArg('1'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("No interactions wanted here"); // TODO specific exception } @Test @@ -208,11 +226,13 @@ public void should_fail_early_when_at_most_is_used() { async.runAfter(100, callMock); // then - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - verify(mock, after(10000).atMost(1)).oneArg('1'); - } - }).isInstanceOf(MoreThanAllowedActualInvocations.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + verify(mock, after(10000).atMost(1)).oneArg('1'); + } + }) + .isInstanceOf(MoreThanAllowedActualInvocations.class); // using generous number to avoid timing issues watch.assertElapsedTimeIsLessThan(2000, MILLISECONDS); @@ -226,18 +246,20 @@ public void should_fail_early_when_never_is_used() { async.runAfter(50, callMock); // then - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - verify(mock, after(10000).never()).oneArg('1'); - } - }).isInstanceOf(MoreThanAllowedActualInvocations.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + verify(mock, after(10000).never()).oneArg('1'); + } + }) + .isInstanceOf(MoreThanAllowedActualInvocations.class); // using generous number to avoid timing issues watch.assertElapsedTimeIsLessThan(2000, MILLISECONDS); } @Test - @Ignore //TODO nice to have + @Ignore // TODO nice to have public void should_fail_early_when_only_is_used() { watch.start(); @@ -246,18 +268,20 @@ public void should_fail_early_when_only_is_used() { async.runAfter(100, callMock); // then - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - verify(mock, after(10000).only()).oneArg('1'); - } - }).isInstanceOf(NoInteractionsWanted.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + verify(mock, after(10000).only()).oneArg('1'); + } + }) + .isInstanceOf(NoInteractionsWanted.class); // using generous number to avoid timing issues watch.assertElapsedTimeIsLessThan(2000, MILLISECONDS); } @Test - @Ignore //TODO nice to have + @Ignore // TODO nice to have public void should_fail_early_when_time_x_is_used() { watch.start(); @@ -266,11 +290,13 @@ public void should_fail_early_when_time_x_is_used() { async.runAfter(100, callMock); // then - assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - verify(mock, after(10000).times(1)).oneArg('1'); - } - }).isInstanceOf(NoInteractionsWanted.class); + assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + verify(mock, after(10000).times(1)).oneArg('1'); + } + }) + .isInstanceOf(NoInteractionsWanted.class); // using generous number to avoid timing issues watch.assertElapsedTimeIsLessThan(2000, MILLISECONDS); diff --git a/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java b/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java index 0c50578f6c..ee876e49f8 100644 --- a/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java @@ -54,7 +54,7 @@ public void should_verify_with_timeout() { // then verify(mock, timeout(200).only()).oneArg('c'); - verify(mock).oneArg('c'); //sanity check + verify(mock).oneArg('c'); // sanity check } @Test @@ -63,17 +63,20 @@ public void should_verify_with_timeout_and_fail() { async.runAfter(200, callMock('c')); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, timeout(50).only()).oneArg('c'); - } - }).isInstanceOf(AssertionError.class).hasMessageContaining("Wanted but not invoked"); - //TODO let's have a specific exception vs. generic assertion error + message + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, timeout(50).only()).oneArg('c'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("Wanted but not invoked"); + // TODO let's have a specific exception vs. generic assertion error + message } @Test - @Ignore //TODO nice to have + @Ignore // TODO nice to have public void should_verify_with_timeout_and_fail_early() { // when callMock('c'); @@ -82,12 +85,15 @@ public void should_verify_with_timeout_and_fail_early() { watch.start(); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, timeout(2000)).oneArg('c'); - } - }).isInstanceOf(AssertionError.class).hasMessageContaining("Wanted but not invoked"); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, timeout(2000)).oneArg('c'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("Wanted but not invoked"); watch.assertElapsedTimeIsLessThan(1000, TimeUnit.MILLISECONDS); } @@ -110,12 +116,14 @@ public void should_verify_with_times_x_and_fail() { async.runAfter(200, callMock('c')); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, timeout(100).times(2)).oneArg('c'); - } - }).isInstanceOf(TooFewActualInvocations.class); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, timeout(100).times(2)).oneArg('c'); + } + }) + .isInstanceOf(TooFewActualInvocations.class); } @Test @@ -145,11 +153,13 @@ public void should_verify_with_at_least_and_fail() { async.runAfter(50, callMock('c')); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - public void call() { - verify(mock, timeout(100).atLeast(3)).oneArg('c'); - } - }).isInstanceOf(TooFewActualInvocations.class); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + public void call() { + verify(mock, timeout(100).atLeast(3)).oneArg('c'); + } + }) + .isInstanceOf(TooFewActualInvocations.class); } @Test @@ -170,16 +180,18 @@ public void should_verify_with_only_and_fail() { async.runAfter(50, callMock('c')); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, after(200).only()).oneArg('c'); - } - }).isInstanceOf(AssertionError.class); + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, after(200).only()).oneArg('c'); + } + }) + .isInstanceOf(AssertionError.class); } @Test - @Ignore //TODO nice to have + @Ignore // TODO nice to have public void should_verify_with_only_and_fail_early() { // when callMock('c'); @@ -188,12 +200,15 @@ public void should_verify_with_only_and_fail_early() { watch.start(); // then - Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock, timeout(2000).only()).oneArg('c'); - } - }).isInstanceOf(AssertionError.class).hasMessageContaining("Wanted but not invoked"); //TODO specific exception + Assertions.assertThatThrownBy( + new ThrowableAssert.ThrowingCallable() { + @Override + public void call() { + verify(mock, timeout(2000).only()).oneArg('c'); + } + }) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("Wanted but not invoked"); // TODO specific exception watch.assertElapsedTimeIsLessThan(1000, TimeUnit.MILLISECONDS); } diff --git a/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java b/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java index 6ef951b416..e9b4a296e9 100644 --- a/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java +++ b/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java @@ -11,7 +11,6 @@ import org.mockito.Mockito; import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent; - public class VerifyPrintsAllInvocationsOnErrorTest { @Test @@ -22,14 +21,12 @@ public void shouldPrintAllInvocationsOnError() { try { Mockito.verify(mockBuilder).with("key1", "wrongValue"); fail(); - } - catch (ArgumentsAreDifferent e) { + } catch (ArgumentsAreDifferent e) { assertThat(e).hasMessageContaining("exampleBuilder.with(\"key1\", \"val1\")"); assertThat(e).hasMessageContaining("exampleBuilder.with(\"key2\", \"val2\""); } } - private static class ExampleBuilder { public ExampleBuilder with(String key, String val) { return this; diff --git a/src/test/java/org/mockitoutil/ClassLoaders.java b/src/test/java/org/mockitoutil/ClassLoaders.java index 045f83df09..2b3f51051d 100644 --- a/src/test/java/org/mockitoutil/ClassLoaders.java +++ b/src/test/java/org/mockitoutil/ClassLoaders.java @@ -43,8 +43,7 @@ public abstract class ClassLoaders { protected ClassLoader parent = currentClassLoader(); - protected ClassLoaders() { - } + protected ClassLoaders() {} public static IsolatedURLClassLoaderBuilder isolatedClassLoader() { return new IsolatedURLClassLoaderBuilder(); @@ -105,28 +104,33 @@ public ClassLoaderExecutor(ClassLoader classLoader) { } public void execute(final Runnable task) throws Exception { - ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread thread = Executors.defaultThreadFactory().newThread(r); - thread.setContextClassLoader(classLoader); - return thread; - } - }); + ExecutorService executorService = + Executors.newSingleThreadExecutor( + new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread thread = Executors.defaultThreadFactory().newThread(r); + thread.setContextClassLoader(classLoader); + return thread; + } + }); try { - Future taskFuture = executorService.submit(new Runnable() { - @Override - public void run() { - try { - reloadTaskInClassLoader(task).run(); - } catch (Throwable throwable) { - throw new IllegalStateException(format("Given task could not be loaded properly in the given classloader '%s', error '%s", - task, - throwable.getMessage()), - throwable); - } - } - }); + Future taskFuture = + executorService.submit( + new Runnable() { + @Override + public void run() { + try { + reloadTaskInClassLoader(task).run(); + } catch (Throwable throwable) { + throw new IllegalStateException( + format( + "Given task could not be loaded properly in the given classloader '%s', error '%s", + task, throwable.getMessage()), + throwable); + } + } + }); taskFuture.get(); executorService.shutdownNow(); } catch (InterruptedException e) { @@ -144,17 +148,19 @@ private T unwrapAndThrows(ExecutionException ex) throws T Runnable reloadTaskInClassLoader(Runnable task) { try { @SuppressWarnings("unchecked") - Class taskClassReloaded = (Class) classLoader.loadClass(task.getClass().getName()); + Class taskClassReloaded = + (Class) classLoader.loadClass(task.getClass().getName()); Objenesis objenesis = new ObjenesisStd(); - ObjectInstantiator thingyInstantiator = objenesis.getInstantiatorOf(taskClassReloaded); + ObjectInstantiator thingyInstantiator = + objenesis.getInstantiatorOf(taskClassReloaded); Runnable reloaded = thingyInstantiator.newInstance(); // lenient shallow copy of class compatible fields for (Field field : task.getClass().getDeclaredFields()) { Field declaredField = taskClassReloaded.getDeclaredField(field.getName()); int modifiers = declaredField.getModifiers(); - if(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { + if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { // Skip static final fields (e.g. jacoco fields) // otherwise IllegalAccessException (can be bypassed with Unsafe though) // We may also miss coverage data. @@ -215,8 +221,7 @@ public ClassLoader build() { jdkClassLoader(), codeSourceUrls.toArray(new URL[codeSourceUrls.size()]), privateCopyPrefixes, - excludedPrefixes - ); + excludedPrefixes); } } @@ -224,10 +229,11 @@ static class LocalIsolatedURLClassLoader extends URLClassLoader { private final ArrayList privateCopyPrefixes; private final ArrayList excludedPrefixes; - LocalIsolatedURLClassLoader(ClassLoader classLoader, - URL[] urls, - ArrayList privateCopyPrefixes, - ArrayList excludedPrefixes) { + LocalIsolatedURLClassLoader( + ClassLoader classLoader, + URL[] urls, + ArrayList privateCopyPrefixes, + ArrayList excludedPrefixes) { super(urls, classLoader); this.privateCopyPrefixes = privateCopyPrefixes; this.excludedPrefixes = excludedPrefixes; @@ -236,17 +242,20 @@ static class LocalIsolatedURLClassLoader extends URLClassLoader { @Override public Class findClass(String name) throws ClassNotFoundException { if (!classShouldBePrivate(name) || classShouldBeExcluded(name)) { - throw new ClassNotFoundException(format("Can only load classes with prefixes : %s, but not : %s", - privateCopyPrefixes, - excludedPrefixes)); + throw new ClassNotFoundException( + format( + "Can only load classes with prefixes : %s, but not : %s", + privateCopyPrefixes, excludedPrefixes)); } try { return super.findClass(name); } catch (ClassNotFoundException cnfe) { - throw new ClassNotFoundException(format("%s%n%s%n", - cnfe.getMessage(), - " Did you forgot to add the code source url 'withCodeSourceUrlOf' / 'withCurrentCodeSourceUrls' ?"), - cnfe); + throw new ClassNotFoundException( + format( + "%s%n%s%n", + cnfe.getMessage(), + " Did you forgot to add the code source url 'withCodeSourceUrlOf' / 'withCurrentCodeSourceUrls' ?"), + cnfe); } } @@ -295,17 +304,15 @@ public ClassLoader build() { return new LocalExcludingURLClassLoader( jdkClassLoader(), codeSourceUrls.toArray(new URL[codeSourceUrls.size()]), - excludedPrefixes - ); + excludedPrefixes); } } static class LocalExcludingURLClassLoader extends URLClassLoader { private final ArrayList excludedPrefixes; - LocalExcludingURLClassLoader(ClassLoader classLoader, - URL[] urls, - ArrayList excludedPrefixes) { + LocalExcludingURLClassLoader( + ClassLoader classLoader, URL[] urls, ArrayList excludedPrefixes) { super(urls, classLoader); this.excludedPrefixes = excludedPrefixes; } @@ -313,7 +320,8 @@ static class LocalExcludingURLClassLoader extends URLClassLoader { @Override public Class findClass(String name) throws ClassNotFoundException { if (classShouldBeExcluded(name)) - throw new ClassNotFoundException("classes with prefix : " + excludedPrefixes + " are excluded"); + throw new ClassNotFoundException( + "classes with prefix : " + excludedPrefixes + " are excluded"); return super.findClass(name); } @@ -409,12 +417,12 @@ public MemURLConnection(URL url, InMemoryClassLoader inMemoryClassLoader) { } @Override - public void connect() throws IOException { - } + public void connect() throws IOException {} @Override public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(inMemoryClassLoader.inMemoryClassObjects.get(qualifiedName)); + return new ByteArrayInputStream( + inMemoryClassLoader.inMemoryClassObjects.get(qualifiedName)); } } } @@ -481,7 +489,10 @@ public Set listOwnedClasses() throws IOException, URISyntaxException { // Just ignore it. continue; } else { - throw new IllegalArgumentException(format("Given ClassLoader '%s' don't have reachable by File or vi ClassLoaders.inMemory", classLoader)); + throw new IllegalArgumentException( + format( + "Given ClassLoader '%s' don't have reachable by File or vi ClassLoaders.inMemory", + classLoader)); } } return classes; @@ -499,8 +510,8 @@ private void addFromInMemoryBasedClassLoader(Set classes, URI uri) { } } - - private Set findClassQualifiedNames(File root, File file, Set packageFilters) { + private Set findClassQualifiedNames( + File root, File file, Set packageFilters) { if (file.isDirectory()) { File[] files = file.listFiles(); Set classes = new HashSet(); @@ -527,10 +538,11 @@ private boolean excludes(String qualifiedName, Set packageFilters) { } private String classNameFor(File root, File file) { - String temp = file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1). - replace(File.separatorChar, '.'); + String temp = + file.getAbsolutePath() + .substring(root.getAbsolutePath().length() + 1) + .replace(File.separatorChar, '.'); return temp.subSequence(0, temp.indexOf(".class")).toString(); } - } } diff --git a/src/test/java/org/mockitoutil/ClassLoadersTest.java b/src/test/java/org/mockitoutil/ClassLoadersTest.java index 51e973be66..baecd02dfb 100644 --- a/src/test/java/org/mockitoutil/ClassLoadersTest.java +++ b/src/test/java/org/mockitoutil/ClassLoadersTest.java @@ -19,7 +19,8 @@ public class ClassLoadersTest { - public static final String CLASS_NAME_DEPENDING_ON_INTERFACE = "org.mockitoutil.ClassLoadersTest$ClassUsingInterface1"; + public static final String CLASS_NAME_DEPENDING_ON_INTERFACE = + "org.mockitoutil.ClassLoadersTest$ClassUsingInterface1"; public static final String INTERFACE_NAME = "org.mockitoutil.ClassLoadersTest$Interface1"; @Test(expected = ClassNotFoundException.class) @@ -34,11 +35,11 @@ public void isolated_class_loader_cannot_load_classes_when_no_given_prefix() thr } @Test - public void isolated_class_loader_cannot_load_classes_if_no_code_source_path() throws Exception { + public void isolated_class_loader_cannot_load_classes_if_no_code_source_path() + throws Exception { // given - ClassLoader cl = isolatedClassLoader() - .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) - .build(); + ClassLoader cl = + isolatedClassLoader().withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE).build(); // when try { @@ -51,12 +52,15 @@ public void isolated_class_loader_cannot_load_classes_if_no_code_source_path() t } @Test - public void isolated_class_loader_cannot_load_classes_if_dependent_classes_do_not_match_the_prefixes() throws Exception { + public void + isolated_class_loader_cannot_load_classes_if_dependent_classes_do_not_match_the_prefixes() + throws Exception { // given - ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) - .build(); + ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) + .build(); // when try { @@ -69,13 +73,16 @@ public void isolated_class_loader_cannot_load_classes_if_dependent_classes_do_no } @Test - public void isolated_class_loader_can_load_classes_when_dependent_classes_are_matching_the_prefixes() throws Exception { + public void + isolated_class_loader_can_load_classes_when_dependent_classes_are_matching_the_prefixes() + throws Exception { // given - ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) - .withPrivateCopyOf(INTERFACE_NAME) - .build(); + ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) + .withPrivateCopyOf(INTERFACE_NAME) + .build(); // when Class aClass = cl.loadClass(CLASS_NAME_DEPENDING_ON_INTERFACE); @@ -87,12 +94,14 @@ public void isolated_class_loader_can_load_classes_when_dependent_classes_are_ma } @Test - public void isolated_class_loader_can_load_classes_isolated_classes_in_isolation() throws Exception { + public void isolated_class_loader_can_load_classes_isolated_classes_in_isolation() + throws Exception { // given - ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) - .build(); + ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) + .build(); // when Class aClass = cl.loadClass(AClass.class.getName()); @@ -106,11 +115,12 @@ public void isolated_class_loader_can_load_classes_isolated_classes_in_isolation @Test public void isolated_class_loader_cannot_load_classes_if_prefix_excluded() throws Exception { // given - ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) - .without(AClass.class.getName()) - .build(); + ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) + .without(AClass.class.getName()) + .build(); // when try { @@ -118,28 +128,29 @@ public void isolated_class_loader_cannot_load_classes_if_prefix_excluded() throw fail(); } catch (ClassNotFoundException e) { // then - assertThat(e).hasMessageContaining("org.mockitoutil") - .hasMessageContaining(AClass.class.getName()); + assertThat(e) + .hasMessageContaining("org.mockitoutil") + .hasMessageContaining(AClass.class.getName()); } } @Test public void isolated_class_loader_has_no_parent() throws Exception { - ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) - .withPrivateCopyOf(INTERFACE_NAME) - .build(); + ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE) + .withPrivateCopyOf(INTERFACE_NAME) + .build(); assertThat(cl.getParent()).isNull(); } @Test(expected = ClassNotFoundException.class) - public void excluding_class_loader_cannot_load_classes_when_no_correct_source_url_set() throws Exception { + public void excluding_class_loader_cannot_load_classes_when_no_correct_source_url_set() + throws Exception { // given - ClassLoader cl = excludingClassLoader() - .withCodeSourceUrlOf(this.getClass()) - .build(); + ClassLoader cl = excludingClassLoader().withCodeSourceUrlOf(this.getClass()).build(); // when cl.loadClass("org.mockito.Mockito"); @@ -148,11 +159,10 @@ public void excluding_class_loader_cannot_load_classes_when_no_correct_source_ur } @Test - public void excluding_class_loader_can_load_classes_when_correct_source_url_set() throws Exception { + public void excluding_class_loader_can_load_classes_when_correct_source_url_set() + throws Exception { // given - ClassLoader cl = excludingClassLoader() - .withCodeSourceUrlOf(Mockito.class) - .build(); + ClassLoader cl = excludingClassLoader().withCodeSourceUrlOf(Mockito.class).build(); // when cl.loadClass("org.mockito.Mockito"); @@ -161,12 +171,14 @@ public void excluding_class_loader_can_load_classes_when_correct_source_url_set( } @Test - public void excluding_class_loader_cannot_load_class_when_excluded_prefix_match_class_to_load() throws Exception { + public void excluding_class_loader_cannot_load_class_when_excluded_prefix_match_class_to_load() + throws Exception { // given - ClassLoader cl = excludingClassLoader() - .withCodeSourceUrlOf(Mockito.class) - .without("org.mockito.BDDMockito") - .build(); + ClassLoader cl = + excludingClassLoader() + .withCodeSourceUrlOf(Mockito.class) + .without("org.mockito.BDDMockito") + .build(); cl.loadClass("org.mockito.Mockito"); @@ -184,10 +196,11 @@ public void excluding_class_loader_cannot_load_class_when_excluded_prefix_match_ @Test public void can_not_load_a_class_not_previously_registered_in_builder() throws Exception { // given - ClassLoader cl = ClassLoaders - .inMemoryClassLoader() - .withClassDefinition("yop.Dude", SimpleClassGenerator.makeMarkerInterface("yop.Dude")) - .build(); + ClassLoader cl = + ClassLoaders.inMemoryClassLoader() + .withClassDefinition( + "yop.Dude", SimpleClassGenerator.makeMarkerInterface("yop.Dude")) + .build(); // when try { @@ -202,10 +215,11 @@ public void can_not_load_a_class_not_previously_registered_in_builder() throws E @Test public void can_load_a_class_in_memory_from_bytes() throws Exception { // given - ClassLoader cl = ClassLoaders - .inMemoryClassLoader() - .withClassDefinition("yop.Dude", SimpleClassGenerator.makeMarkerInterface("yop.Dude")) - .build(); + ClassLoader cl = + ClassLoaders.inMemoryClassLoader() + .withClassDefinition( + "yop.Dude", SimpleClassGenerator.makeMarkerInterface("yop.Dude")) + .build(); // when Class aClass = cl.loadClass("yop.Dude"); @@ -219,10 +233,7 @@ public void can_load_a_class_in_memory_from_bytes() throws Exception { @Test public void cannot_load_a_class_file_not_in_parent() throws Exception { // given - ClassLoader cl = ClassLoaders - .inMemoryClassLoader() - .withParent(jdkClassLoader()) - .build(); + ClassLoader cl = ClassLoaders.inMemoryClassLoader().withParent(jdkClassLoader()).build(); cl.loadClass("java.lang.String"); @@ -238,16 +249,20 @@ public void cannot_load_a_class_file_not_in_parent() throws Exception { @Test public void can_list_all_classes_reachable_in_a_classloader() throws Exception { - ClassLoader classLoader = ClassLoaders.inMemoryClassLoader() - .withParent(jdkClassLoader()) - .withClassDefinition("a.A", SimpleClassGenerator.makeMarkerInterface("a.A")) - .withClassDefinition("a.b.B", SimpleClassGenerator.makeMarkerInterface("a.b.B")) - .withClassDefinition("c.C", SimpleClassGenerator.makeMarkerInterface("c.C")) -// .withCodeSourceUrlOf(ClassLoaders.class) - .build(); - - assertThat(ClassLoaders.in(classLoader).listOwnedClasses()).containsOnly("a.A", "a.b.B", "c.C"); - assertThat(ClassLoaders.in(classLoader).omit("b", "c").listOwnedClasses()).containsOnly("a.A"); + ClassLoader classLoader = + ClassLoaders.inMemoryClassLoader() + .withParent(jdkClassLoader()) + .withClassDefinition("a.A", SimpleClassGenerator.makeMarkerInterface("a.A")) + .withClassDefinition( + "a.b.B", SimpleClassGenerator.makeMarkerInterface("a.b.B")) + .withClassDefinition("c.C", SimpleClassGenerator.makeMarkerInterface("c.C")) + // .withCodeSourceUrlOf(ClassLoaders.class) + .build(); + + assertThat(ClassLoaders.in(classLoader).listOwnedClasses()) + .containsOnly("a.A", "a.b.B", "c.C"); + assertThat(ClassLoaders.in(classLoader).omit("b", "c").listOwnedClasses()) + .containsOnly("a.A"); } @Test @@ -266,80 +281,92 @@ public void return_current_classloader() throws Exception { @Test public void can_run_in_given_classloader() throws Exception { // given - final ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withCodeSourceUrlOf(Assertions.class) - .withPrivateCopyOf("org.assertj.core") - .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) - .without(AClass.class.getName()) - .build(); + final ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withCodeSourceUrlOf(Assertions.class) + .withPrivateCopyOf("org.assertj.core") + .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) + .without(AClass.class.getName()) + .build(); final AtomicBoolean executed = new AtomicBoolean(false); // when - ClassLoaders.using(cl).execute(new Runnable() { - @Override - public void run() { - assertThat(this.getClass().getClassLoader()).describedAs("runnable is reloaded in given classloader").isEqualTo(cl); - assertThat(Thread.currentThread().getContextClassLoader()).describedAs("Thread context classloader is using given classloader").isEqualTo(cl); - - try { - assertThat(Thread.currentThread() - .getContextClassLoader() - .loadClass("java.lang.String")) - .describedAs("can load JDK type") - .isNotNull(); - assertThat(Thread.currentThread() - .getContextClassLoader() - .loadClass("org.mockitoutil.ClassLoadersTest$ClassUsingInterface1")) - .describedAs("can load classloader types") - .isNotNull(); - } catch (ClassNotFoundException cnfe) { - Assertions.fail("should not have raised a CNFE", cnfe); - } - executed.set(true); - } - }); + ClassLoaders.using(cl) + .execute( + new Runnable() { + @Override + public void run() { + assertThat(this.getClass().getClassLoader()) + .describedAs("runnable is reloaded in given classloader") + .isEqualTo(cl); + assertThat(Thread.currentThread().getContextClassLoader()) + .describedAs( + "Thread context classloader is using given classloader") + .isEqualTo(cl); + + try { + assertThat( + Thread.currentThread() + .getContextClassLoader() + .loadClass("java.lang.String")) + .describedAs("can load JDK type") + .isNotNull(); + assertThat( + Thread.currentThread() + .getContextClassLoader() + .loadClass( + "org.mockitoutil.ClassLoadersTest$ClassUsingInterface1")) + .describedAs("can load classloader types") + .isNotNull(); + } catch (ClassNotFoundException cnfe) { + Assertions.fail("should not have raised a CNFE", cnfe); + } + executed.set(true); + } + }); // then assertThat(executed.get()).isEqualTo(true); } - @Test - public void cannot_load_runnable_in_given_classloader_if_some_type_cant_be_loaded() throws Exception { + public void cannot_load_runnable_in_given_classloader_if_some_type_cant_be_loaded() + throws Exception { // given - final ClassLoader cl = isolatedClassLoader() - .withCurrentCodeSourceUrls() - .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) - .without(AClass.class.getName()) - .build(); + final ClassLoader cl = + isolatedClassLoader() + .withCurrentCodeSourceUrls() + .withPrivateCopyOf(ClassLoadersTest.class.getPackage().getName()) + .without(AClass.class.getName()) + .build(); // when try { - ClassLoaders.using(cl).execute(new Runnable() { - @Override - public void run() { - AClass cant_be_found = new AClass(); - } - }); + ClassLoaders.using(cl) + .execute( + new Runnable() { + @Override + public void run() { + AClass cant_be_found = new AClass(); + } + }); Assertions.fail("should have raised a ClassNotFoundException"); } catch (IllegalStateException ise) { // then - assertThat(ise).hasCauseInstanceOf(NoClassDefFoundError.class) - .hasMessageContaining("AClass"); + assertThat(ise) + .hasCauseInstanceOf(NoClassDefFoundError.class) + .hasMessageContaining("AClass"); } } @SuppressWarnings("unused") - static class AClass { - } + static class AClass {} @SuppressWarnings("unused") - static class ClassUsingInterface1 implements Interface1 { - } + static class ClassUsingInterface1 implements Interface1 {} @SuppressWarnings("unused") - interface Interface1 { - } + interface Interface1 {} } diff --git a/src/test/java/org/mockitoutil/ConcurrentTesting.java b/src/test/java/org/mockitoutil/ConcurrentTesting.java index 1722aeb0fa..f5717fe372 100644 --- a/src/test/java/org/mockitoutil/ConcurrentTesting.java +++ b/src/test/java/org/mockitoutil/ConcurrentTesting.java @@ -25,7 +25,7 @@ public static void inThread(Runnable r) throws InterruptedException { * Starts all supplied runnables and then waits for all of them to complete. * Runnables are executed concurrently. */ - public static void concurrently(Runnable ... runnables) throws InterruptedException { + public static void concurrently(Runnable... runnables) throws InterruptedException { List threads = new LinkedList(); for (Runnable r : runnables) { Thread t = new Thread(r); diff --git a/src/test/java/org/mockitoutil/Conditions.java b/src/test/java/org/mockitoutil/Conditions.java index a9658cbc30..96491faed6 100644 --- a/src/test/java/org/mockitoutil/Conditions.java +++ b/src/test/java/org/mockitoutil/Conditions.java @@ -23,10 +23,11 @@ public boolean matches(Throwable traceElements) { StackTraceElement[] trace = traceElements.getStackTrace(); Assertions.assertThat(trace.length) - .describedAs("Number of classes does not match.\nExpected: %s\nGot: %s", - Arrays.toString(classes), - Arrays.toString(traceElements.getStackTrace())) - .isEqualTo(classes.length); + .describedAs( + "Number of classes does not match.\nExpected: %s\nGot: %s", + Arrays.toString(classes), + Arrays.toString(traceElements.getStackTrace())) + .isEqualTo(classes.length); for (int i = 0; i < trace.length; i++) { Assertions.assertThat(trace[i].getClassName()).isEqualTo(classes[i]); @@ -43,10 +44,10 @@ public static Condition onlyThoseClasses(final String... cl @Override public boolean matches(StackTraceElement[] traceElements) { Assertions.assertThat(traceElements.length) - .describedAs("Number of classes does not match.\nExpected: %s\nGot: %s", - Arrays.toString(classes), - Arrays.toString(traceElements)) - .isEqualTo(classes.length); + .describedAs( + "Number of classes does not match.\nExpected: %s\nGot: %s", + Arrays.toString(classes), Arrays.toString(traceElements)) + .isEqualTo(classes.length); for (int i = 0; i < traceElements.length; i++) { Assertions.assertThat(traceElements[i].getClassName()).isEqualTo(classes[i]); @@ -61,7 +62,8 @@ public static Condition firstMethodInStackTrace(final String method) return methodInStackTraceAt(0, method); } - public static Condition methodInStackTraceAt(final int stackTraceIndex, final String method) { + public static Condition methodInStackTraceAt( + final int stackTraceIndex, final String method) { return new Condition() { private String actualMethodAtIndex; @@ -74,7 +76,9 @@ public boolean matches(Throwable throwable) { @Override public Description description() { - return new TextDescription("Method at index: %d\nexpected to be: %s\nbut is: %s", stackTraceIndex, method, actualMethodAtIndex); + return new TextDescription( + "Method at index: %d\nexpected to be: %s\nbut is: %s", + stackTraceIndex, method, actualMethodAtIndex); } }; } @@ -111,12 +115,12 @@ public static Condition methodsInStackTrace(final String... methods) public boolean matches(Throwable value) { StackTraceElement[] trace = value.getStackTrace(); for (int i = 0; i < methods.length; i++) { - Assertions.assertThat(trace[i].getMethodName()).describedAs("Expected methods[%d] to be in the stack trace.", i).isEqualTo(methods[i]); + Assertions.assertThat(trace[i].getMethodName()) + .describedAs("Expected methods[%d] to be in the stack trace.", i) + .isEqualTo(methods[i]); } return true; } }; } - - } diff --git a/src/test/java/org/mockitoutil/JUnitResultAssert.java b/src/test/java/org/mockitoutil/JUnitResultAssert.java index e920ae1dd6..54ad6fa773 100644 --- a/src/test/java/org/mockitoutil/JUnitResultAssert.java +++ b/src/test/java/org/mockitoutil/JUnitResultAssert.java @@ -39,8 +39,13 @@ public JUnitResultAssert fails(int expectedFailureCount, Class expectedException fails(expectedFailureCount); for (Failure f : result.getFailures()) { if (!expectedException.isInstance(f.getException())) { - throw new AssertionError("Incorrect failure type, expected: " + expectedException + ", actual: " + f.getException().getClass().getSimpleName() + "\n" + - formatFailures(result.getFailures())); + throw new AssertionError( + "Incorrect failure type, expected: " + + expectedException + + ", actual: " + + f.getException().getClass().getSimpleName() + + "\n" + + formatFailures(result.getFailures())); } } return this; @@ -51,8 +56,13 @@ public JUnitResultAssert fails(int expectedFailureCount, Class expectedException */ public JUnitResultAssert fails(int expectedFailureCount) { if (result.getFailures().size() != expectedFailureCount) { - throw new AssertionError("Wrong number of failures, expected: " + expectedFailureCount + ", actual: " + result.getFailures().size() + "\n" + - formatFailures(result.getFailures())); + throw new AssertionError( + "Wrong number of failures, expected: " + + expectedFailureCount + + ", actual: " + + result.getFailures().size() + + "\n" + + formatFailures(result.getFailures())); } return this; } @@ -61,15 +71,20 @@ public JUnitResultAssert fails(int expectedFailureCount) { * @param expectedExceptions - failures must match the supplied sequence in order, * if supplied input is empty, this method is a no-op */ - public JUnitResultAssert failsExactly(Class ... expectedExceptions) { + public JUnitResultAssert failsExactly(Class... expectedExceptions) { fails(expectedExceptions.length); int i = 0; for (Failure f : result.getFailures()) { if (!expectedExceptions[i].isInstance(f.getException())) { - throw new AssertionError("Actual failure #" + (i+1) - + " should be of type: " + expectedExceptions[i].getSimpleName() - + " but is of type: " + f.getException().getClass().getSimpleName() - + "\n" + formatFailures(result.getFailures())); + throw new AssertionError( + "Actual failure #" + + (i + 1) + + " should be of type: " + + expectedExceptions[i].getSimpleName() + + " but is of type: " + + f.getException().getClass().getSimpleName() + + "\n" + + formatFailures(result.getFailures())); } i++; } @@ -92,27 +107,41 @@ public JUnitResultAssert fails(Class expectedException, String exceptionMessage) */ public JUnitResultAssert fails(String methodName, Class expectedException) { for (Failure f : result.getFailures()) { - if (methodName.equals(f.getDescription().getMethodName()) && expectedException.isInstance(f.getException())) { + if (methodName.equals(f.getDescription().getMethodName()) + && expectedException.isInstance(f.getException())) { return this; } } - throw new AssertionError("Method '" + methodName + "' did not fail with: " + expectedException.getSimpleName() - + "\n" + formatFailures(result.getFailures())); + throw new AssertionError( + "Method '" + + methodName + + "' did not fail with: " + + expectedException.getSimpleName() + + "\n" + + formatFailures(result.getFailures())); } /** * Expects given amount of failures, with given exception triggered by given test method */ - public JUnitResultAssert fails(int expectedFailureCount, String methodName, Class expectedException) { - return fails(expectedFailureCount, expectedException) - .fails(methodName, expectedException); + public JUnitResultAssert fails( + int expectedFailureCount, String methodName, Class expectedException) { + return fails(expectedFailureCount, expectedException).fails(methodName, expectedException); } public JUnitResultAssert succeeds(int successCount) { int i = result.getRunCount() - result.getFailureCount(); if (i != successCount) { - throw new AssertionError("Expected " + successCount + " passes but " + i + "/" + result.getRunCount() + " passed." + - "\n" + formatFailures(result.getFailures())); + throw new AssertionError( + "Expected " + + successCount + + " passes but " + + i + + "/" + + result.getRunCount() + + " passed." + + "\n" + + formatFailures(result.getFailures())); } return this; } diff --git a/src/test/java/org/mockitoutil/SafeJUnitRule.java b/src/test/java/org/mockitoutil/SafeJUnitRule.java index db256d5870..701c3eb443 100644 --- a/src/test/java/org/mockitoutil/SafeJUnitRule.java +++ b/src/test/java/org/mockitoutil/SafeJUnitRule.java @@ -18,7 +18,10 @@ public class SafeJUnitRule implements MethodRule { private final MethodRule testedRule; private FailureAssert failureAssert = null; - private Runnable successAssert = new Runnable() { public void run() { } }; + private Runnable successAssert = + new Runnable() { + public void run() {} + }; /** * Wraps rule under test with exception handling so that it is easy to assert on exceptions fired from the tested rule. @@ -27,7 +30,8 @@ public SafeJUnitRule(MethodRule testedRule) { this.testedRule = testedRule; } - public Statement apply(final Statement base, final FrameworkMethod method, final Object target) { + public Statement apply( + final Statement base, final FrameworkMethod method, final Object target) { return new Statement() { public void evaluate() throws Throwable { try { @@ -41,8 +45,9 @@ public void evaluate() throws Throwable { return; } if (failureAssert != null) { - //looks like the user expects a throwable but it was not thrown! - throw new ExpectedThrowableNotReported("Expected the tested rule to throw an exception but it did not."); + // looks like the user expects a throwable but it was not thrown! + throw new ExpectedThrowableNotReported( + "Expected the tested rule to throw an exception but it did not."); } } }; @@ -51,26 +56,30 @@ public void evaluate() throws Throwable { /** * Expects that _after_ the test, the rule will fire specific exception with specific exception message */ - public void expectFailure(final Class expected, final String expectedMessage) { - this.expectFailure(new FailureAssert() { - public void doAssert(Throwable t) { - assertThrowable(t, expected).hasMessage(expectedMessage); - } - }); + public void expectFailure( + final Class expected, final String expectedMessage) { + this.expectFailure( + new FailureAssert() { + public void doAssert(Throwable t) { + assertThrowable(t, expected).hasMessage(expectedMessage); + } + }); } /** * Expects that _after_ the test, the rule will fire specific exception with specific exception message */ public void expectFailure(final Class expected) { - this.expectFailure(new FailureAssert() { - public void doAssert(Throwable t) { - assertThrowable(t, expected); - } - }); + this.expectFailure( + new FailureAssert() { + public void doAssert(Throwable t) { + assertThrowable(t, expected); + } + }); } - private static AbstractThrowableAssert assertThrowable(Throwable throwable, Class expected) { + private static AbstractThrowableAssert assertThrowable( + Throwable throwable, Class expected) { return Assertions.assertThat(throwable).isInstanceOf(expected); } diff --git a/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java b/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java index acbf27af9e..3ac6397c2b 100644 --- a/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java +++ b/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java @@ -18,108 +18,143 @@ public class SafeJUnitRuleTest { MethodRuleStub delegate = new MethodRuleStub(); SafeJUnitRule rule = new SafeJUnitRule(delegate); - @Test public void happy_path_no_exception() throws Throwable { - //when - rule.apply(new Statement() { - public void evaluate() throws Throwable { - //all good - } - }, mock(FrameworkMethod.class), this).evaluate(); - - //then + @Test + public void happy_path_no_exception() throws Throwable { + // when + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + // all good + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); + + // then assertTrue(delegate.statementEvaluated); } @Test(expected = IllegalArgumentException.class) public void regular_failing_test() throws Throwable { - //when - rule.apply(new Statement() { - public void evaluate() throws Throwable { - throw new IllegalArgumentException(); - } - }, mock(FrameworkMethod.class), this).evaluate(); + // when + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + throw new IllegalArgumentException(); + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); } - @Test public void rule_threw_exception() throws Throwable { - //expect + @Test + public void rule_threw_exception() throws Throwable { + // expect rule.expectFailure(AssertionError.class, "x"); - //when - rule.apply(new Statement() { - public void evaluate() throws Throwable { - throw new AssertionError("x"); - } - }, mock(FrameworkMethod.class), this).evaluate(); + // when + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + throw new AssertionError("x"); + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); } - @Test public void expected_exception_but_no_exception() throws Throwable { - //expect + @Test + public void expected_exception_but_no_exception() throws Throwable { + // expect rule.expectFailure(AssertionError.class, "x"); - //when + // when try { - rule.apply(new Statement() { - public void evaluate() throws Throwable { - //all good - } - }, mock(FrameworkMethod.class), this).evaluate(); + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + // all good + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); fail(); - //then + // then } catch (SafeJUnitRule.ExpectedThrowableNotReported t) { - //yup, expected + // yup, expected } } - @Test public void expected_exception_message_did_not_match() throws Throwable { - //expect + @Test + public void expected_exception_message_did_not_match() throws Throwable { + // expect rule.expectFailure(AssertionError.class, "FOO"); - //when + // when try { - rule.apply(new Statement() { - public void evaluate() throws Throwable { - throw new AssertionError("BAR"); - } - }, mock(FrameworkMethod.class), this).evaluate(); + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + throw new AssertionError("BAR"); + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); fail(); } catch (AssertionError throwable) { Assertions.assertThat(throwable).hasMessageContaining("Expecting message"); } } - @Test public void expected_exception_type_did_not_match() throws Throwable { - //expect + @Test + public void expected_exception_type_did_not_match() throws Throwable { + // expect rule.expectFailure(AssertionError.class, "x"); - //when + // when try { - rule.apply(new Statement() { - public void evaluate() throws Throwable { - throw new RuntimeException("x"); - } - }, mock(FrameworkMethod.class), this).evaluate(); + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + throw new RuntimeException("x"); + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); fail(); } catch (AssertionError throwable) { Assertions.assertThat(throwable).hasMessageContaining("but was:"); } } - @Test public void expected_exception_assert_did_not_match() throws Throwable { - //expect - rule.expectFailure(new SafeJUnitRule.FailureAssert() { - public void doAssert(Throwable t) { - throw new AssertionError("x"); - } - }); - - //when + @Test + public void expected_exception_assert_did_not_match() throws Throwable { + // expect + rule.expectFailure( + new SafeJUnitRule.FailureAssert() { + public void doAssert(Throwable t) { + throw new AssertionError("x"); + } + }); + + // when try { - rule.apply(new Statement() { - public void evaluate() throws Throwable { - throw new RuntimeException(); - } - }, mock(FrameworkMethod.class), this).evaluate(); + rule.apply( + new Statement() { + public void evaluate() throws Throwable { + throw new RuntimeException(); + } + }, + mock(FrameworkMethod.class), + this) + .evaluate(); fail(); } catch (AssertionError throwable) { assertEquals(throwable.getMessage(), "x"); @@ -128,6 +163,7 @@ public void evaluate() throws Throwable { private static class MethodRuleStub implements MethodRule { private boolean statementEvaluated; + public Statement apply(final Statement base, FrameworkMethod method, Object target) { return new Statement() { public void evaluate() throws Throwable { diff --git a/src/test/java/org/mockitoutil/SimpleClassGenerator.java b/src/test/java/org/mockitoutil/SimpleClassGenerator.java index 8920122910..26ce9e837c 100644 --- a/src/test/java/org/mockitoutil/SimpleClassGenerator.java +++ b/src/test/java/org/mockitoutil/SimpleClassGenerator.java @@ -14,10 +14,15 @@ public static byte[] makeMarkerInterface(String qualifiedName) { String relativePath = qualifiedName.replace('.', '/'); ClassWriter cw = new ClassWriter(0); - cw.visit(V1_6, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, relativePath, null, "java/lang/Object", null); + cw.visit( + V1_6, + ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE, + relativePath, + null, + "java/lang/Object", + null); cw.visitEnd(); return cw.toByteArray(); } - } diff --git a/src/test/java/org/mockitoutil/SimplePerRealmReloadingClassLoader.java b/src/test/java/org/mockitoutil/SimplePerRealmReloadingClassLoader.java index 1f49afb1ba..5855d21fe5 100644 --- a/src/test/java/org/mockitoutil/SimplePerRealmReloadingClassLoader.java +++ b/src/test/java/org/mockitoutil/SimplePerRealmReloadingClassLoader.java @@ -18,7 +18,7 @@ */ public class SimplePerRealmReloadingClassLoader extends URLClassLoader { - private final Map> classHashMap = new HashMap>(); + private final Map> classHashMap = new HashMap>(); private ReloadClassPredicate reloadClassPredicate; public SimplePerRealmReloadingClassLoader(ReloadClassPredicate reloadClassPredicate) { @@ -26,16 +26,17 @@ public SimplePerRealmReloadingClassLoader(ReloadClassPredicate reloadClassPredic this.reloadClassPredicate = reloadClassPredicate; } - public SimplePerRealmReloadingClassLoader(ClassLoader parentClassLoader, ReloadClassPredicate reloadClassPredicate) { + public SimplePerRealmReloadingClassLoader( + ClassLoader parentClassLoader, ReloadClassPredicate reloadClassPredicate) { super(getPossibleClassPathsUrls(), parentClassLoader); this.reloadClassPredicate = reloadClassPredicate; } private static URL[] getPossibleClassPathsUrls() { - return new URL[]{ - obtainClassPath(), - obtainClassPath("org.mockito.Mockito"), - obtainClassPath("net.bytebuddy.ByteBuddy") + return new URL[] { + obtainClassPath(), + obtainClassPath("org.mockito.Mockito"), + obtainClassPath("net.bytebuddy.ByteBuddy") }; } @@ -46,7 +47,11 @@ private static URL obtainClassPath() { private static URL obtainClassPath(String className) { String path = className.replace('.', '/') + ".class"; - String url = SimplePerRealmReloadingClassLoader.class.getClassLoader().getResource(path).toExternalForm(); + String url = + SimplePerRealmReloadingClassLoader.class + .getClassLoader() + .getResource(path) + .toExternalForm(); try { return new URL(url.substring(0, url.length() - path.length())); @@ -55,14 +60,12 @@ private static URL obtainClassPath(String className) { } } - - @Override public Class loadClass(String qualifiedClassName) throws ClassNotFoundException { - if(reloadClassPredicate.acceptReloadOf(qualifiedClassName)) { + if (reloadClassPredicate.acceptReloadOf(qualifiedClassName)) { // return customLoadClass(qualifiedClassName); -// Class loadedClass = findLoadedClass(qualifiedClassName); - if(!classHashMap.containsKey(qualifiedClassName)) { + // Class loadedClass = findLoadedClass(qualifiedClassName); + if (!classHashMap.containsKey(qualifiedClassName)) { Class foundClass = findClass(qualifiedClassName); saveFoundClass(qualifiedClassName, foundClass); return foundClass; @@ -77,17 +80,16 @@ private void saveFoundClass(String qualifiedClassName, Class foundClass) { classHashMap.put(qualifiedClassName, foundClass); } - private Class useParentClassLoaderFor(String qualifiedName) throws ClassNotFoundException { return super.loadClass(qualifiedName); } - public Object doInRealm(String callableCalledInClassLoaderRealm) throws Exception { ClassLoader current = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this); - Object instance = this.loadClass(callableCalledInClassLoaderRealm).getConstructor().newInstance(); + Object instance = + this.loadClass(callableCalledInClassLoaderRealm).getConstructor().newInstance(); if (instance instanceof Callable) { Callable callableInRealm = (Callable) instance; return callableInRealm.call(); @@ -95,15 +97,22 @@ public Object doInRealm(String callableCalledInClassLoaderRealm) throws Exceptio } finally { Thread.currentThread().setContextClassLoader(current); } - throw new IllegalArgumentException("qualified name '" + callableCalledInClassLoaderRealm + "' should represent a class implementing Callable"); + throw new IllegalArgumentException( + "qualified name '" + + callableCalledInClassLoaderRealm + + "' should represent a class implementing Callable"); } - - public Object doInRealm(String callableCalledInClassLoaderRealm, Class[] argTypes, Object[] args) throws Exception { + public Object doInRealm( + String callableCalledInClassLoaderRealm, Class[] argTypes, Object[] args) + throws Exception { ClassLoader current = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this); - Object instance = this.loadClass(callableCalledInClassLoaderRealm).getConstructor(argTypes).newInstance(args); + Object instance = + this.loadClass(callableCalledInClassLoaderRealm) + .getConstructor(argTypes) + .newInstance(args); if (instance instanceof Callable) { Callable callableInRealm = (Callable) instance; return callableInRealm.call(); @@ -112,10 +121,12 @@ public Object doInRealm(String callableCalledInClassLoaderRealm, Class[] argT Thread.currentThread().setContextClassLoader(current); } - throw new IllegalArgumentException("qualified name '" + callableCalledInClassLoaderRealm + "' should represent a class implementing Callable"); + throw new IllegalArgumentException( + "qualified name '" + + callableCalledInClassLoaderRealm + + "' should represent a class implementing Callable"); } - public interface ReloadClassPredicate { boolean acceptReloadOf(String qualifiedName); } diff --git a/src/test/java/org/mockitoutil/SimpleSerializationUtil.java b/src/test/java/org/mockitoutil/SimpleSerializationUtil.java index 152b54d042..65fe8421a1 100644 --- a/src/test/java/org/mockitoutil/SimpleSerializationUtil.java +++ b/src/test/java/org/mockitoutil/SimpleSerializationUtil.java @@ -10,20 +10,21 @@ public abstract class SimpleSerializationUtil { - //TODO use widely + // TODO use widely @SuppressWarnings("unchecked") public static T serializeAndBack(T obj) throws Exception { ByteArrayOutputStream os = serializeMock(obj); return (T) deserializeMock(os, Object.class); } - public static T deserializeMock(ByteArrayOutputStream serialized, Class type) throws IOException, - ClassNotFoundException { + public static T deserializeMock(ByteArrayOutputStream serialized, Class type) + throws IOException, ClassNotFoundException { InputStream unserialize = new ByteArrayInputStream(serialized.toByteArray()); return deserializeMock(unserialize, type); } - public static T deserializeMock(InputStream unserialize, Class type) throws IOException, ClassNotFoundException { + public static T deserializeMock(InputStream unserialize, Class type) + throws IOException, ClassNotFoundException { Object readObject = new ObjectInputStream(unserialize).readObject(); assertNotNull(readObject); return type.cast(readObject); diff --git a/src/test/java/org/mockitoutil/Stopwatch.java b/src/test/java/org/mockitoutil/Stopwatch.java index 7c9e5c80a3..5c0ea2d1bf 100644 --- a/src/test/java/org/mockitoutil/Stopwatch.java +++ b/src/test/java/org/mockitoutil/Stopwatch.java @@ -25,8 +25,7 @@ public class Stopwatch { /** * To create an instance use {@link #createNotStarted()} */ - private Stopwatch() { - } + private Stopwatch() {} /** * Return a new and not started {@link Stopwatch}. @@ -47,7 +46,9 @@ public void assertElapsedTimeIsMoreThan(long expected, TimeUnit unit) { long expectedNanos = unit.toNanos(expected); if (elapsedNanos <= expectedNanos) - fail("Expected that more than %dms elapsed! But was: %dms", expectedNanos, elapsedNanos); + fail( + "Expected that more than %dms elapsed! But was: %dms", + expectedNanos, elapsedNanos); } public void assertElapsedTimeIsLessThan(long expected, TimeUnit unit) { @@ -55,17 +56,22 @@ public void assertElapsedTimeIsLessThan(long expected, TimeUnit unit) { long expectedNanos = unit.toNanos(expected); if (elapsedNanos >= expectedNanos) - fail("Expected that less than %dms elapsed! But was: %dms", expectedNanos, elapsedNanos); + fail( + "Expected that less than %dms elapsed! But was: %dms", + expectedNanos, elapsedNanos); } private long elapsedNanos() { - if (startNanos == null) - throw new IllegalStateException("This stop watch is not started!"); + if (startNanos == null) throw new IllegalStateException("This stop watch is not started!"); return nanoTime() - startNanos; } private static void fail(String message, long expectedNanos, long elapsedNanos) { - throw new MockitoAssertionError(format(message, NANOSECONDS.toMillis(expectedNanos), NANOSECONDS.toMillis(elapsedNanos))); + throw new MockitoAssertionError( + format( + message, + NANOSECONDS.toMillis(expectedNanos), + NANOSECONDS.toMillis(elapsedNanos))); } /** diff --git a/src/test/java/org/mockitoutil/TestBase.java b/src/test/java/org/mockitoutil/TestBase.java index fdd1231c54..e35ea5b5b0 100644 --- a/src/test/java/org/mockitoutil/TestBase.java +++ b/src/test/java/org/mockitoutil/TestBase.java @@ -48,10 +48,11 @@ public void cleanUpConfigInAnyCase() { ConfigurationAccess.getConfig().overrideCleansStackTrace(false); ConfigurationAccess.getConfig().overrideDefaultAnswer(null); StateMaster state = new StateMaster(); - //catch any invalid state left over after test case run - //this way we can catch early if some Mockito operations leave weird state afterwards + // catch any invalid state left over after test case run + // this way we can catch early if some Mockito operations leave weird state afterwards state.validate(); - //reset the state, especially, reset any ongoing stubbing for correct error messages of tests that assert unhappy paths + // reset the state, especially, reset any ongoing stubbing for correct error messages of + // tests that assert unhappy paths state.reset(); } @@ -72,14 +73,19 @@ public static Invocation getLastInvocation() { return new MockitoCore().getLastInvocation(); } - protected static Invocation invocationOf(Class type, String methodName, Object ... args) throws NoSuchMethodException { + protected static Invocation invocationOf(Class type, String methodName, Object... args) + throws NoSuchMethodException { Class[] types = new Class[args.length]; for (int i = 0; i < args.length; i++) { types[i] = args[i].getClass(); } - return new InterceptedInvocation(new MockStrongReference(mock(type), false), - new SerializableMethod(type.getMethod(methodName, types)), args, InterceptedInvocation.NO_OP, - new LocationImpl(), 1); + return new InterceptedInvocation( + new MockStrongReference(mock(type), false), + new SerializableMethod(type.getMethod(methodName, types)), + args, + InterceptedInvocation.NO_OP, + new LocationImpl(), + 1); } protected static Invocation invocationAt(String location) { @@ -95,7 +101,8 @@ protected String getStackTrace(Throwable e) { e.printStackTrace(new PrintStream(out)); try { out.close(); - } catch (IOException ex) {} + } catch (IOException ex) { + } return out.toString(); } diff --git a/src/test/java/org/mockitoutil/TestBaseTest.java b/src/test/java/org/mockitoutil/TestBaseTest.java index 81e5477db9..aa98f33e75 100644 --- a/src/test/java/org/mockitoutil/TestBaseTest.java +++ b/src/test/java/org/mockitoutil/TestBaseTest.java @@ -10,13 +10,19 @@ public class TestBaseTest extends TestBase { - @Test public void filters_line_no_from_stack_trace() { + @Test + public void filters_line_no_from_stack_trace() { assertEquals("", filterLineNo("")); assertEquals("asdf", filterLineNo("asdf")); assertEquals("asdf (FooBar.java:0) blah", filterLineNo("asdf (FooBar.java:23) blah")); - assertEquals("asdf\n(FooBar.java:0)\nblah", filterLineNo("asdf\n(FooBar.java:123123)\nblah")); - assertEquals("asdf\n(FooBar.java:0)\n(Xxx.java:0)blah", filterLineNo("asdf\n(FooBar.java:2)\n(Xxx.java:1)blah")); + assertEquals( + "asdf\n(FooBar.java:0)\nblah", filterLineNo("asdf\n(FooBar.java:123123)\nblah")); + assertEquals( + "asdf\n(FooBar.java:0)\n(Xxx.java:0)blah", + filterLineNo("asdf\n(FooBar.java:2)\n(Xxx.java:1)blah")); - assertEquals("asdf\n(FooBar.java:0)\nXxx.java:20)blah", filterLineNo("asdf\n(FooBar.java:2)\nXxx.java:20)blah")); + assertEquals( + "asdf\n(FooBar.java:0)\nXxx.java:20)blah", + filterLineNo("asdf\n(FooBar.java:2)\nXxx.java:20)blah")); } } diff --git a/src/test/java/org/mockitoutil/ThrowableAssert.java b/src/test/java/org/mockitoutil/ThrowableAssert.java index c58ca8e3d9..54c4b27631 100644 --- a/src/test/java/org/mockitoutil/ThrowableAssert.java +++ b/src/test/java/org/mockitoutil/ThrowableAssert.java @@ -24,10 +24,12 @@ private ThrowableAssert(Runnable runnable) { } public ThrowableAssert throwsException(Class exceptionType) { - if(!exceptionType.isInstance(reportedException)) { - throw new AssertionError("Exception should be of type: " - + exceptionType.getSimpleName() + " but it was: " - + reportedException.getClass().getSimpleName()); + if (!exceptionType.isInstance(reportedException)) { + throw new AssertionError( + "Exception should be of type: " + + exceptionType.getSimpleName() + + " but it was: " + + reportedException.getClass().getSimpleName()); } return this; } diff --git a/src/test/java/org/mockitoutil/VmArgAssumptions.java b/src/test/java/org/mockitoutil/VmArgAssumptions.java index 1eba1bdeab..4ab606e65f 100644 --- a/src/test/java/org/mockitoutil/VmArgAssumptions.java +++ b/src/test/java/org/mockitoutil/VmArgAssumptions.java @@ -28,5 +28,4 @@ private static boolean assertEnabled(String vmArg) { } return false; } - } diff --git a/src/test/java/org/mockitoutil/async/AsyncTesting.java b/src/test/java/org/mockitoutil/async/AsyncTesting.java index a193eb689c..855d3fbd11 100644 --- a/src/test/java/org/mockitoutil/async/AsyncTesting.java +++ b/src/test/java/org/mockitoutil/async/AsyncTesting.java @@ -15,8 +15,8 @@ */ public class AsyncTesting { - //Sanity limit of threas. Increase it if justified. - private final static int MAX_THREADS = 4; + // Sanity limit of threas. Increase it if justified. + private static final int MAX_THREADS = 4; private final LinkedList problems = new LinkedList(); private final LinkedList threads = new LinkedList(); @@ -32,22 +32,28 @@ public class AsyncTesting { */ public void runAfter(final int delayMillis, final Runnable runnable) { if (threads.size() == MAX_THREADS) { - throw new RuntimeException("Please don't schedule any more threads. Figure out how to test the code with minimum amount of threads"); + throw new RuntimeException( + "Please don't schedule any more threads. Figure out how to test the code with minimum amount of threads"); } - Thread t = new Thread() { - public void run() { - try { - Thread.sleep(delayMillis); - runnable.run(); - } catch (Exception e) { - boolean cleanStop = e instanceof InterruptedException && stopping; - if (!cleanStop) { - problems.add(e); + Thread t = + new Thread() { + public void run() { + try { + Thread.sleep(delayMillis); + runnable.run(); + } catch (Exception e) { + boolean cleanStop = e instanceof InterruptedException && stopping; + if (!cleanStop) { + problems.add(e); + } + } } - } - } - }; - System.out.println("[AsyncTesting] Starting thread that will execute the runnable after " + delayMillis + " millis. Threads so far: " + threads.size()); + }; + System.out.println( + "[AsyncTesting] Starting thread that will execute the runnable after " + + delayMillis + + " millis. Threads so far: " + + threads.size()); threads.add(t); t.start(); } @@ -58,8 +64,11 @@ public void run() { */ public void cleanUp() { stopping = true; - System.out.println("[AsyncTesting] Interrupting and waiting for " + threads.size() + " threads to complete..."); - while(!threads.isEmpty()) { + System.out.println( + "[AsyncTesting] Interrupting and waiting for " + + threads.size() + + " threads to complete..."); + while (!threads.isEmpty()) { Thread t = threads.removeFirst(); try { t.interrupt(); @@ -69,7 +78,9 @@ public void cleanUp() { } } if (!problems.isEmpty()) { - throw new RuntimeException("Caught " + problems.size() + " exception(s). First one is included as cause", problems.getFirst()); + throw new RuntimeException( + "Caught " + problems.size() + " exception(s). First one is included as cause", + problems.getFirst()); } } } diff --git a/src/test/java/org/mockitoutil/async/AsyncTestingTest.java b/src/test/java/org/mockitoutil/async/AsyncTestingTest.java index 5db8147abb..e6d7cdf564 100644 --- a/src/test/java/org/mockitoutil/async/AsyncTestingTest.java +++ b/src/test/java/org/mockitoutil/async/AsyncTestingTest.java @@ -27,27 +27,29 @@ public void after() { @Test public void sanity_test() { - //given + // given watch.start(); final AtomicInteger value = new AtomicInteger(0); - //when - async.runAfter(200, new Runnable() { - public void run() { - value.incrementAndGet(); - } - }); + // when + async.runAfter( + 200, + new Runnable() { + public void run() { + value.incrementAndGet(); + } + }); - //then the runnable is truly async and has not ran yet: + // then the runnable is truly async and has not ran yet: assertEquals(0, value.get()); - //after some wait... + // after some wait... watch.waitFor(300); - //we actually waited for some time + // we actually waited for some time watch.assertElapsedTimeIsMoreThan(200, MILLISECONDS); - //and the async has actually ran: + // and the async has actually ran: assertEquals(1, value.get()); } }