From d9535098c10920c369d103a1871832e97ab5b42a Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Wed, 26 Feb 2020 23:12:36 +0100 Subject: [PATCH 001/963] Revert "Fixed undetected unused stubbing when matching previous stubbed call" (#1878) [ci maven-central-release] --- .../mockito/internal/exceptions/Reporter.java | 7 +- .../internal/reporting/Pluralizer.java | 4 -- .../stubbing/InvocationContainerImpl.java | 21 ------ .../stubbing/StubbedInvocationMatcher.java | 4 -- .../org/mockito/invocation/Invocation.java | 3 +- .../internal/reporting/PluralizerTest.java | 7 -- .../junitrule/StrictJUnitRuleTest.java | 2 +- .../UnusedStubsExceptionMessageTest.java | 2 +- .../stubbing/StrictStubbingTest.java | 69 ------------------- 9 files changed, 6 insertions(+), 113 deletions(-) diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java index ab94fd1551..f661b81e5c 100644 --- a/src/main/java/org/mockito/internal/exceptions/Reporter.java +++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java @@ -5,7 +5,6 @@ package org.mockito.internal.exceptions; import static org.mockito.internal.reporting.Pluralizer.pluralize; -import static org.mockito.internal.reporting.Pluralizer.stubbings; import static org.mockito.internal.reporting.Pluralizer.were_exactly_x_interactions; import static org.mockito.internal.util.StringUtil.join; @@ -883,9 +882,9 @@ public static MockitoException notAnException() { public static UnnecessaryStubbingException formatUnncessaryStubbingException(Class testClass, Collection unnecessaryStubbings) { StringBuilder stubbings = new StringBuilder(); - int count = 0; + int count = 1; for (Invocation u : unnecessaryStubbings) { - stubbings.append("\n ").append(++count).append(". ").append(u.getLocation()); + stubbings.append("\n ").append(count++).append(". ").append(u.getLocation()); } String heading = (testClass != null)? "Unnecessary stubbings detected in test class: " + testClass.getSimpleName() : @@ -894,7 +893,7 @@ public static UnnecessaryStubbingException formatUnncessaryStubbingException(Cla return new UnnecessaryStubbingException(join( heading, "Clean & maintainable test code requires zero unnecessary code.", - "There are " + count + " unnecessary " + stubbings(count) + " (click to navigate to relevant line of code):" + stubbings, + "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." )); } diff --git a/src/main/java/org/mockito/internal/reporting/Pluralizer.java b/src/main/java/org/mockito/internal/reporting/Pluralizer.java index 5a9d7425b0..1e8d0e3f4b 100644 --- a/src/main/java/org/mockito/internal/reporting/Pluralizer.java +++ b/src/main/java/org/mockito/internal/reporting/Pluralizer.java @@ -17,8 +17,4 @@ public static String were_exactly_x_interactions(int x) { return "were exactly " + x + " interactions"; } } - - public static String stubbings(int number) { - return number == 1 ? "stubbing" : "stubbings"; - } } diff --git a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java index 19922a7fa8..07c5a5e41c 100644 --- a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java +++ b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java @@ -52,31 +52,10 @@ public void resetInvocationForPotentialStubbing(MatchableInvocation invocationMa } public void addAnswer(Answer answer, Strictness stubbingStrictness) { - unmarkLastUsedStubIfNecessary(); - registeredInvocations.removeLast(); addAnswer(answer, false, stubbingStrictness); } - /** - * A stubbed call is marked as used when the method call is stubbed again, because the second - * stub looks like an actual usage of the first stubbed call. When the second stub is set up, - * the previous one is marked as unused again. - */ - private void unmarkLastUsedStubIfNecessary() { - synchronized (stubbed) { - Invocation invocation = invocationForStubbing.getInvocation(); - - for (StubbedInvocationMatcher s : stubbed) { - if (s.matches(invocation)) { - s.markStubUsed(null); - invocation.markStubbed(null); - return; - } - } - } - } - public void addConsecutiveAnswer(Answer answer) { addAnswer(answer, true, null); } diff --git a/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java b/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java index 0b1e4f4ba9..e88c85b2d1 100644 --- a/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java +++ b/src/main/java/org/mockito/internal/stubbing/StubbedInvocationMatcher.java @@ -43,10 +43,6 @@ public void addAnswer(Answer answer) { answers.add(answer); } - /** - * Marks the stub as used by the passed invocation. Passing null marks the stub as unused. - * @param usedAt The invocation which uses this stub - */ public void markStubUsed(DescribedInvocation usedAt) { this.usedAt = usedAt; } diff --git a/src/main/java/org/mockito/invocation/Invocation.java b/src/main/java/org/mockito/invocation/Invocation.java index ed25fd4c69..04d14907f8 100644 --- a/src/main/java/org/mockito/invocation/Invocation.java +++ b/src/main/java/org/mockito/invocation/Invocation.java @@ -81,8 +81,7 @@ public interface Invocation extends InvocationOnMock, DescribedInvocation { StubInfo stubInfo(); /** - * Marks this invocation as stubbed. Passing null resets the invocation state back to not - * stubbed. + * Marks this invocation as stubbed. * * @param stubInfo the information about stubbing. */ diff --git a/src/test/java/org/mockito/internal/reporting/PluralizerTest.java b/src/test/java/org/mockito/internal/reporting/PluralizerTest.java index 3e9a2fc28f..c1be4382c1 100644 --- a/src/test/java/org/mockito/internal/reporting/PluralizerTest.java +++ b/src/test/java/org/mockito/internal/reporting/PluralizerTest.java @@ -25,11 +25,4 @@ public void pluralizes_interactions() { assertEquals("was exactly 1 interaction", Pluralizer.were_exactly_x_interactions(1)); assertEquals("were exactly 100 interactions", Pluralizer.were_exactly_x_interactions(100)); } - - @Test - public void pluralizes_stubbings() { - assertEquals("stubbings", Pluralizer.stubbings(0)); - assertEquals("stubbing", Pluralizer.stubbings(1)); - assertEquals("stubbings", Pluralizer.stubbings(100)); - } } diff --git a/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java index 6dbe3d83c2..98b17915b6 100644 --- a/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java @@ -140,7 +140,7 @@ public void doAssert(Throwable t) { assertEquals(filterLineNo("\n" + "Unnecessary stubbings detected.\n" + "Clean & maintainable test code requires zero unnecessary code.\n" + - "There are 2 unnecessary stubbings (click to navigate to relevant line of 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())); diff --git a/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java b/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java index 394d013a04..09e1e70923 100644 --- a/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java +++ b/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java @@ -50,7 +50,7 @@ public void lists_all_unused_stubs_cleanly() { assertEquals("\n" + "Unnecessary stubbings detected in test class: HasUnnecessaryStubs\n" + "Clean & maintainable test code requires zero unnecessary code.\n" + - "There are 2 unnecessary stubbings (click to navigate to relevant line of 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.", diff --git a/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java b/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java index 37195cb29a..96e6a9f346 100644 --- a/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java +++ b/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java @@ -4,16 +4,11 @@ */ package org.mockitousage.stubbing; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockitoutil.ThrowableAssert.assertThat; -import org.assertj.core.api.Assertions; -import org.assertj.core.api.ThrowableAssert; import org.junit.After; import org.junit.Test; import org.mockito.Mock; @@ -104,68 +99,4 @@ public void run() { } }).throwsException(UnnecessaryStubbingException.class); } - - private static void assertUnusedStubbingsWhen(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, int unusedStubbingsCount) { - Assertions.assertThatThrownBy(shouldRaiseThrowable) - .isInstanceOf(UnnecessaryStubbingException.class) - .hasMessageContaining(unusedStubbingsCount + " unnecessary stubbing"); - } - - @Test public void repeated_unnecessary_stubbing() { - given(mock.simpleMethod("1")).willReturn("one"); - given(mock.simpleMethod("2")).willReturn("three"); - given(mock.simpleMethod("1")).willReturn("two"); //repeat 1x - given(mock.simpleMethod("1")).willReturn("four"); //repeat 2x - - mock.simpleMethod("1"); - mock.simpleMethod("2"); - - assertUnusedStubbingsWhen(() -> mockito.finishMocking(), 2); - } - - @Test public void repeated_unnecessary_stubbing_willReturn() { - willReturn("one").given(mock).simpleMethod("1"); - willReturn("three").given(mock).simpleMethod("2"); - willReturn("two").given(mock).simpleMethod("1"); - willReturn("four").given(mock).simpleMethod("1"); - - mock.simpleMethod("1"); - mock.simpleMethod("2"); - - assertUnusedStubbingsWhen(() -> mockito.finishMocking(), 2); - } - - @Test public void unnecessary_stubbing_with_any_matchers() { - given(mock.simpleMethod((String) any())).willReturn("one"); - given(mock.simpleMethod(anyString())).willReturn("three"); - - mock.simpleMethod("1"); - - assertUnusedStubbingsWhen(() -> mockito.finishMocking(), 1); - } - - @Test public void unnecessary_stubbing_with_mixed_matchers() { - given(mock.simpleMethod(anyString())).willReturn("one"); - given(mock.simpleMethod("foo")).willReturn("three"); - - mock.simpleMethod("1"); - - assertUnusedStubbingsWhen(() -> mockito.finishMocking(), 1); - } - - @Test public void unnecessary_stubbing_with_stubs_only() { - given(mock.simpleMethod(anyString())).willReturn("one"); - given(mock.simpleMethod("foo")).willReturn("three"); - - assertUnusedStubbingsWhen(() -> mockito.finishMocking(), 2); - } - - @Test public void unnecessary_stubbing_with_mixed_matchers_willReturn() { - willReturn("one").given(mock).simpleMethod(anyString()); - willReturn("three").given(mock).simpleMethod("foo"); - - mock.simpleMethod("1"); - - assertUnusedStubbingsWhen(() -> mockito.finishMocking(), 1); - } } From 434556a4bd4bb288bf7d12fd4d21ce3a244ce4ba Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Wed, 26 Feb 2020 22:18:27 +0000 Subject: [PATCH 002/963] 3.3.1 release (previous 3.3.0) + release notes updated by CI build 4387 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index a9d866e818..f499120377 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.1 + - 2020-02-26 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.0...v3.3.1) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.1-green.svg)](https://bintray.com/mockito/maven/mockito/3.3.1) + - Revert "Fixed undetected unused stubbing when matching previous stubbed call" [(#1878)](https://github.com/mockito/mockito/pull/1878) + #### 3.3.0 - 2020-02-21 - [1 commit](https://github.com/mockito/mockito/compare/v3.2.11...v3.3.0) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.3.0) - No pull requests referenced in commit messages. diff --git a/version.properties b/version.properties index c056235733..e095ec76a1 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.1 +version=3.3.2 #Previous version used to generate release notes delta -previousVersion=3.3.0 +previousVersion=3.3.1 From 06b131f7aca0ec1d7f20f1b4ed767936ad440362 Mon Sep 17 00:00:00 2001 From: Jean-Michel Leclercq Date: Fri, 28 Feb 2020 23:20:05 +0100 Subject: [PATCH 003/963] Fix UnnecessaryStubbingException javadoc (#1881) --- .../exceptions/misusing/UnnecessaryStubbingException.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java b/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java index 2d4605b4f6..6078437038 100644 --- a/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java +++ b/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java @@ -33,10 +33,11 @@ * when(translator.translate("one")).thenReturn("jeden"); // <- stubbing realized during code execution * when(translator.translate("two")).thenReturn("dwa"); // <- stubbing never realized * ... + * * * Notice that one of the stubbed methods were never realized in the code under test, during test execution. * The stray stubbing might be an oversight of the developer, the artifact of copy-paste - * or the effect not understanding the test/code. + * or the effect of not understanding the test/code. * Either way, the developer ends up with unnecessary test code. * In order to keep the codebase clean & maintainable it is necessary to remove unnecessary code. * Otherwise tests are harder to read and reason about. From f61e187bc0aae4a220d3d41ef2eaa66c296e7b01 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Fri, 28 Feb 2020 22:26:36 +0000 Subject: [PATCH 004/963] 3.3.2 release (previous 3.3.1) + release notes updated by CI build 4390 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index f499120377..0c2664ebe0 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.2 + - 2020-02-28 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.1...v3.3.2) by [Jean-Michel Leclercq](https://github.com/LeJeanbono) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.2-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.2) + - Fix UnnecessaryStubbingException javadoc [(#1881)](https://github.com/mockito/mockito/pull/1881) + #### 3.3.1 - 2020-02-26 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.0...v3.3.1) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.1-green.svg)](https://bintray.com/mockito/maven/mockito/3.3.1) - Revert "Fixed undetected unused stubbing when matching previous stubbed call" [(#1878)](https://github.com/mockito/mockito/pull/1878) diff --git a/version.properties b/version.properties index e095ec76a1..3b443f1577 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.2 +version=3.3.3 #Previous version used to generate release notes delta -previousVersion=3.3.1 +previousVersion=3.3.2 From 0f38efd83ce8e104237a26f2b3a2974dfd849656 Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Fri, 13 Mar 2020 13:53:43 +0000 Subject: [PATCH 005/963] Publish to Maven Central Hopefully to address #1886 [ci maven-central-release] From 560adf377677a4a2c658a0b24e2f9c2e0b373c20 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Fri, 13 Mar 2020 13:59:53 +0000 Subject: [PATCH 006/963] 3.3.3 release (previous 3.3.2) + release notes updated by CI build 4393 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 0c2664ebe0..af451cb258 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.3 + - 2020-03-13 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.2...v3.3.3) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.3-green.svg)](https://bintray.com/mockito/maven/mockito/3.3.3) + - No pull requests referenced in commit messages. + #### 3.3.2 - 2020-02-28 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.1...v3.3.2) by [Jean-Michel Leclercq](https://github.com/LeJeanbono) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.2-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.2) - Fix UnnecessaryStubbingException javadoc [(#1881)](https://github.com/mockito/mockito/pull/1881) diff --git a/version.properties b/version.properties index 3b443f1577..6dbe7a157e 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.3 +version=3.3.4 #Previous version used to generate release notes delta -previousVersion=3.3.2 +previousVersion=3.3.3 From 5b63b6fa0d5649a6552ebd75a7113206ad863e03 Mon Sep 17 00:00:00 2001 From: dean-burdaky Date: Sat, 21 Mar 2020 14:37:29 +0000 Subject: [PATCH 007/963] Fixes #1875 : Fix mocks throwing same instance with throwable class (#1890) Fixes mocks throwing the same instance consecutively of a given throwable class after specifying the mock behaviour with doThrow(Class) or thenThrow(Class). --- .../internal/stubbing/BaseStubbing.java | 6 +- .../internal/stubbing/StubberImpl.java | 15 +-- .../answers/AbstractThrowsException.java | 56 ++++++++ .../stubbing/answers/ThrowsException.java | 41 +----- .../answers/ThrowsExceptionForClassType.java | 25 ++++ .../answers/AbstractThrowsExceptionTest.java | 125 ++++++++++++++++++ .../ThrowsExceptionForClassTypeTest.java | 28 ++++ .../stubbing/answers/ThrowsExceptionTest.java | 20 ++- .../stubbing/StubbingWithThrowablesTest.java | 25 ++++ .../UninstantiableThrowableTest.java | 31 ----- 10 files changed, 286 insertions(+), 86 deletions(-) create mode 100644 src/main/java/org/mockito/internal/stubbing/answers/AbstractThrowsException.java create mode 100644 src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassType.java create mode 100644 src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java create mode 100644 src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java delete mode 100644 subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java diff --git a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java index 73dab853d5..b3bd074428 100644 --- a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java +++ b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java @@ -7,11 +7,10 @@ import static org.mockito.internal.exceptions.Reporter.notAnException; import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; -import org.mockito.creation.instance.Instantiator; -import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.stubbing.answers.CallsRealMethods; import org.mockito.internal.stubbing.answers.Returns; import org.mockito.internal.stubbing.answers.ThrowsException; +import org.mockito.internal.stubbing.answers.ThrowsExceptionForClassType; import org.mockito.stubbing.Answer; import org.mockito.stubbing.OngoingStubbing; @@ -75,8 +74,7 @@ public OngoingStubbing thenThrow(Class throwableType) { mockingProgress().reset(); throw notAnException(); } - Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(null); - return thenThrow(instantiator.newInstance(throwableType)); + return thenAnswer(new ThrowsExceptionForClassType(throwableType)); } @Override diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java index d707cf8b3a..3f37af64b3 100644 --- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java +++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java @@ -14,10 +14,10 @@ import java.util.LinkedList; import java.util.List; -import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.stubbing.answers.CallsRealMethods; import org.mockito.internal.stubbing.answers.Returns; import org.mockito.internal.stubbing.answers.ThrowsException; +import org.mockito.internal.stubbing.answers.ThrowsExceptionForClassType; import org.mockito.internal.util.MockUtil; import org.mockito.quality.Strictness; import org.mockito.stubbing.Answer; @@ -89,18 +89,7 @@ public Stubber doThrow(Class toBeThrown) { mockingProgress().reset(); throw notAnException(); } - Throwable e = null; - try { - e = Plugins.getInstantiatorProvider().getInstantiator(null).newInstance(toBeThrown); - } finally { - if (e == null) { - //this means that an exception or error was thrown when trying to create new instance - //we don't want 'catch' statement here because we want the exception to be thrown to the user - //however, we do want to clean up state (e.g. "stubbing started"). - mockingProgress().reset(); - } - } - return doThrow(e); + return doAnswer(new ThrowsExceptionForClassType(toBeThrown)); } @Override diff --git a/src/main/java/org/mockito/internal/stubbing/answers/AbstractThrowsException.java b/src/main/java/org/mockito/internal/stubbing/answers/AbstractThrowsException.java new file mode 100644 index 0000000000..47bf6d669b --- /dev/null +++ b/src/main/java/org/mockito/internal/stubbing/answers/AbstractThrowsException.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.stubbing.answers; + +import static org.mockito.internal.exceptions.Reporter.cannotStubWithNullThrowable; +import static org.mockito.internal.exceptions.Reporter.checkedExceptionInvalid; + +import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter; +import org.mockito.internal.util.MockUtil; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.mockito.stubbing.ValidableAnswer; + +public abstract class AbstractThrowsException implements Answer, ValidableAnswer { + + private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter(); + + protected abstract Throwable getThrowable(); + + 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!"); + } + if (MockUtil.isMock(throwable)) { + throw throwable; + } + Throwable t = throwable.fillInStackTrace(); + + if (t == null) { + //Custom exceptions sometimes return null, see #866 + throw throwable; + } + filter.filter(t); + throw t; + } + + @Override + public void validateFor(InvocationOnMock invocation) { + Throwable throwable = getThrowable(); + if (throwable == null) { + throw cannotStubWithNullThrowable(); + } + + if (throwable instanceof RuntimeException || throwable instanceof Error) { + return; + } + + if (!new InvocationInfo(invocation).isValidException(throwable)) { + throw checkedExceptionInvalid(throwable); + } + } +} 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 bc1b987f37..1250a88882 100644 --- a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java +++ b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java @@ -4,25 +4,19 @@ */ package org.mockito.internal.stubbing.answers; -import static org.mockito.internal.exceptions.Reporter.cannotStubWithNullThrowable; -import static org.mockito.internal.exceptions.Reporter.checkedExceptionInvalid; import java.io.Serializable; -import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter; -import org.mockito.internal.util.MockUtil; import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.mockito.stubbing.ValidableAnswer; /** * An answer that always throws the same throwable. */ -public class ThrowsException implements Answer, ValidableAnswer, Serializable { +public class ThrowsException extends AbstractThrowsException implements Serializable { private static final long serialVersionUID = 1128820328555183980L; private final Throwable throwable; - private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter(); /** * Creates a new answer always throwing the given throwable. If it is null, @@ -33,36 +27,9 @@ public ThrowsException(Throwable throwable) { this.throwable = throwable; } - public Object answer(InvocationOnMock invocation) throws Throwable { - if (throwable == null) { - throw new IllegalStateException("throwable is null: " + - "you shall not call #answer if #validateFor fails!"); - } - if (MockUtil.isMock(throwable)) { - throw throwable; - } - Throwable t = throwable.fillInStackTrace(); - - if (t == null) { - //Custom exceptions sometimes return null, see #866 - throw throwable; - } - filter.filter(t); - throw t; - } - @Override - public void validateFor(InvocationOnMock invocation) { - if (throwable == null) { - throw cannotStubWithNullThrowable(); - } - - if (throwable instanceof RuntimeException || throwable instanceof Error) { - return; - } - - if (!new InvocationInfo(invocation).isValidException(throwable)) { - throw checkedExceptionInvalid(throwable); - } + protected Throwable getThrowable() { + return throwable; } + } diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassType.java b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassType.java new file mode 100644 index 0000000000..2c3d923956 --- /dev/null +++ b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassType.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.stubbing.answers; + +import java.io.Serializable; + +import org.mockito.creation.instance.Instantiator; +import org.mockito.internal.configuration.plugins.Plugins; + +public class ThrowsExceptionForClassType extends AbstractThrowsException implements Serializable { + + private final Class throwableClass; + + public ThrowsExceptionForClassType(Class throwableClass) { + this.throwableClass = throwableClass; + } + + @Override + protected Throwable getThrowable() { + Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(null); + return instantiator.newInstance(throwableClass); + } +} diff --git a/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java b/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java new file mode 100644 index 0000000000..8fa4d86f58 --- /dev/null +++ b/src/test/java/org/mockito/internal/stubbing/answers/AbstractThrowsExceptionTest.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.stubbing.answers; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.internal.exceptions.Reporter.cannotStubWithNullThrowable; +import static org.mockito.internal.exceptions.Reporter.checkedExceptionInvalid; + +import java.io.IOException; +import java.nio.charset.CharacterCodingException; + +import org.assertj.core.api.Assertions; +import org.junit.Test; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.invocation.InvocationBuilder; +import org.mockito.invocation.Invocation; + +public class AbstractThrowsExceptionTest { + + @Test + public void should_raise_wanted_throwable() { + Throwable expected = new Exception(); + AbstractThrowsException ate = instantiateFixture(expected); + + Throwable throwable = Assertions.catchThrowable(() -> ate.answer(createMethodInvocation())); + assertNotNull("Should have raised an exception.", throwable); + assertSame(expected, throwable); + } + + @Test + public void should_throw_mock_exception_without_stacktrace() { + AbstractThrowsException ate = instantiateFixture(mock(Exception.class)); + + Throwable throwable = Assertions.catchThrowable(() -> ate.answer(createMethodInvocation())); + assertNotNull("Should have raised an exception.", throwable); + assertThat(throwable.getStackTrace()).describedAs("no stack trace, it's mock").isNull(); + } + + @Test + public void should_fill_in_exception_stacktrace() { + AbstractThrowsException ate = instantiateFixture(new Exception()); + + 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].getMethodName()).isEqualTo("answer"); + } + + @Test + public void should_invalidate_null_throwable() { + AbstractThrowsException ate = instantiateFixture(null); + + Throwable throwable = Assertions.catchThrowableOfType(() -> ate.validateFor(createMethodInvocation()), + MockitoException.class); + assertNotNull("Should have raised a MockitoException.", throwable); + assertEquals(cannotStubWithNullThrowable().getMessage(), throwable.getMessage()); + } + + @Test + public void should_throw_illegal_state_exception_if_null_answer() { + AbstractThrowsException ate = instantiateFixture(null); + + 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()); + } + + @Test + public void should_pass_proper_checked_exception() { + instantiateFixture(new CharacterCodingException()).validateFor(createMethodInvocation()); + } + + @Test + 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); + assertNotNull("Should have raised a MockitoException.", throwable); + assertEquals(checkedExceptionInvalid(comparison).getMessage(), throwable.getMessage()); + } + + @Test + public void should_pass_RuntimeException() { + instantiateFixture(new RuntimeException()).validateFor(createMethodInvocation()); + } + + @Test + public void should_pass_Error() { + instantiateFixture(new Error()).validateFor(createMethodInvocation()); + } + + /** Creates a fixture for AbstractThrowsException that returns the given Throwable. */ + private static AbstractThrowsException instantiateFixture(Throwable throwable) { + return new AbstractThrowsException() { + @Override + protected Throwable getThrowable() { + return throwable; + } + }; + } + + /** Creates Invocation of a "canThrowException" method call. */ + private static Invocation createMethodInvocation() { + return new InvocationBuilder() + .method("canThrowException") + .toInvocation(); + } + + @Test + public void fixture_should_return_expected_throwable() { + Throwable expected = new RuntimeException(); + AbstractThrowsException ate = instantiateFixture(expected); + + assertSame(expected, ate.getThrowable()); + } +} diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java new file mode 100644 index 0000000000..9aa67d098a --- /dev/null +++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionForClassTypeTest.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.stubbing.answers; + +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +import org.junit.Test; + +public class ThrowsExceptionForClassTypeTest { + @Test + public void should_return_throwable_of_expected_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); + + Throwable first = throwsExceptionForClassType.getThrowable(); + Throwable second = throwsExceptionForClassType.getThrowable(); + assertNotSame(first, second); + } +} 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 6940244997..2da1e04596 100644 --- a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java +++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java @@ -6,6 +6,7 @@ import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import java.io.IOException; @@ -54,7 +55,7 @@ public void should_fill_in_exception_stacktrace() throws Exception { } catch (Throwable throwable) { // then throwable.printStackTrace(); - assertThat(throwableToRaise.getStackTrace()[0].getClassName()).isEqualTo(ThrowsException.class.getName()); + assertThat(throwableToRaise.getStackTrace()[0].getClassName()).isEqualTo(AbstractThrowsException.class.getName()); assertThat(throwableToRaise.getStackTrace()[0].getMethodName()).isEqualTo("answer"); } } @@ -94,6 +95,23 @@ public void should_pass_RuntimeExceptions() throws Throwable { new ThrowsException(new RuntimeException()).validateFor(createMethodInvocation()); } + @Test + public void should_return_expected_throwable() { + Throwable expected = new Exception(); + ThrowsException throwsException = new ThrowsException(expected); + + assertSame(expected, throwsException.getThrowable()); + } + + @Test + public void should_return_same_throwable() { + ThrowsException throwsException = new ThrowsException(new Exception()); + + Throwable first = throwsException.getThrowable(); + Throwable second = throwsException.getThrowable(); + assertSame(first, second); + } + /** Creates Invocation of a "canThrowException" method call. */ private static Invocation createMethodInvocation() { return new InvocationBuilder() diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java index 3798ca735f..3b93f3c7db 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java @@ -6,6 +6,7 @@ import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -92,6 +93,30 @@ public void call() { }).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); + + assertNotSame(first, second); + } + + @Test + 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); + + assertNotSame(first, second); + } + @Test public void shouldStubWithThrowable() throws Exception { IllegalArgumentException expected = new IllegalArgumentException("thrown by mock"); diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java deleted file mode 100644 index 2ef3128016..0000000000 --- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2018 Mockito contributors - * This program is made available under the terms of the MIT License. - */ -package org.mockitousage; - -import org.assertj.core.api.Assertions; -import org.junit.jupiter.api.RepeatedTest; -import org.junit.jupiter.api.RepetitionInfo; -import org.mockito.Mockito; - -import java.util.List; - -//issue 1514 -class UninstantiableThrowableTest { - - @RepeatedTest(2) - void should_behave_consistently(RepetitionInfo i) { - List mock = Mockito.mock(List.class); - if (i.getCurrentRepetition() == 1) { - Assertions.assertThatThrownBy( - () -> Mockito.doThrow(UninstantiableException.class).when(mock).clear()) - .isInstanceOf(InstantiationError.class); - } - - // The following operation results in "UnfinishedStubbing" - Mockito.doThrow(RuntimeException.class).when(mock).clear(); - } - - abstract static class UninstantiableException extends RuntimeException { } -} From fd6dfea618126e0555a12038e7071eae3ba3234d Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sat, 21 Mar 2020 14:42:54 +0000 Subject: [PATCH 008/963] 3.3.4 release (previous 3.3.3) + release notes updated by CI build 4397 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index af451cb258..7b6b82b9e6 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.4 + - 2020-03-21 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.3...v3.3.4) by [dean-burdaky](https://github.com/dean-burdaky) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.4-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.4) + - Fix mocks throwing same instance with throwable class [(#1890)](https://github.com/mockito/mockito/pull/1890) + - thenThrow(Class) no longer creates new instances [(#1875)](https://github.com/mockito/mockito/issues/1875) + #### 3.3.3 - 2020-03-13 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.2...v3.3.3) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.3-green.svg)](https://bintray.com/mockito/maven/mockito/3.3.3) - No pull requests referenced in commit messages. diff --git a/version.properties b/version.properties index 6dbe7a157e..390952a77b 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.4 +version=3.3.5 #Previous version used to generate release notes delta -previousVersion=3.3.3 +previousVersion=3.3.4 From e8685ab7d7ffea9249f33ff1619ca4bf2436803d Mon Sep 17 00:00:00 2001 From: Shyam Sundar J Date: Mon, 23 Mar 2020 23:20:13 +0530 Subject: [PATCH 009/963] Fixes #1888: fix typo in documentation (#1893) --- src/main/java/org/mockito/Mockito.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index af1ceb22e9..01f0024ff6 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -1100,7 +1100,7 @@ * * Mockito introduces serialization across classloader. * - * Like with any other form of serialization, all types in the mock hierarchy have to serializable, inclusing answers. + * Like with any other form of serialization, all types in the mock hierarchy have to serializable, including answers. * As this serialization mode require considerably more work, this is an opt-in setting. * *


From 872358c810a7e750cccac6a6614b3191269732db Mon Sep 17 00:00:00 2001
From: shipkit-org 
Date: Mon, 23 Mar 2020 17:55:58 +0000
Subject: [PATCH 010/963] 3.3.5 release (previous 3.3.4) + release notes
 updated by CI build 4402

[ci skip-release]
---
 doc/release-notes/official.md | 5 +++++
 version.properties            | 4 ++--
 2 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md
index 7b6b82b9e6..c2525c2e99 100644
--- a/doc/release-notes/official.md
+++ b/doc/release-notes/official.md
@@ -1,5 +1,10 @@
 *Release notes were automatically generated by [Shipkit](http://shipkit.org/)*
 
+#### 3.3.5
+ - 2020-03-23 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.4...v3.3.5) by [Shyam Sundar J](https://github.com/severussundar) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.5-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.5)
+ - Fixes #id : 1888 [(#1893)](https://github.com/mockito/mockito/pull/1893)
+ - Documentation typo [(#1888)](https://github.com/mockito/mockito/issues/1888)
+
 #### 3.3.4
  - 2020-03-21 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.3...v3.3.4) by [dean-burdaky](https://github.com/dean-burdaky) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.4-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.4)
  - Fix mocks throwing same instance with throwable class [(#1890)](https://github.com/mockito/mockito/pull/1890)
diff --git a/version.properties b/version.properties
index 390952a77b..eea79ec34c 100644
--- a/version.properties
+++ b/version.properties
@@ -1,5 +1,5 @@
 #Currently building Mockito version
-version=3.3.5
+version=3.3.6
 
 #Previous version used to generate release notes delta
-previousVersion=3.3.4
+previousVersion=3.3.5

From ab4bd0c533977497697ac4ab629f301c66596ffc Mon Sep 17 00:00:00 2001
From: Alex Wilson <460299+mrwilson@users.noreply.github.com>
Date: Tue, 24 Mar 2020 14:00:35 +0000
Subject: [PATCH 011/963] Fixes #1891: Instruct Gradle to build JARs
 deterministically (#1892)

This makes the build reproducible, if there are no other sources of non-determinism with the JAR's content such as the manifest.

It strips the "Bnd-LastModified" header from OSGi content in JARs. it copies the jar and removes the offending header from the Manifest file. Due to a known issue in Gradle with the (now-deprecated) OSGi plugin, this is one of the only ways to remove this header.

Additionally, we verify the reproducibility in CI build via a new Gradle task. This new task, `checkReproducibility`, runs two builds, collects the sha256 checksums of the output archives, and compares them.

Co-authored-by: Tim van der Lippe 
---
 .gitignore                                    |  3 +
 .travis.yml                                   |  2 +-
 build.gradle                                  |  7 ++
 gradle/mockito-core/osgi.gradle               | 92 +++++++++++++++++++
 gradle/mockito-core/reproducible-build.gradle | 69 ++++++++++++++
 5 files changed, 172 insertions(+), 1 deletion(-)
 create mode 100644 gradle/mockito-core/reproducible-build.gradle

diff --git a/.gitignore b/.gitignore
index 9d0c115582..09ab494393 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,3 +21,6 @@ out
 classes
 .gradletasknamecache
 *.log
+
+# Used to check reproducibility of Mockito jars
+checksums/
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
index 26c444f3ef..43f616aa7b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -50,7 +50,7 @@ script:
   # We are using && below on purpose
   # ciPerformRelease must run only when the entire build has completed
   # This guarantees that no release steps are executed when the build or tests fail
-  - ./gradlew spotlessCheck && ./gradlew build idea -s && ./gradlew ciPerformRelease
+  - ./gradlew spotlessCheck && ./gradlew build idea -s && ./gradlew checkReproducibility && ./gradlew ciPerformRelease
 
 after_success:
   #Generates coverage report:
diff --git a/build.gradle b/build.gradle
index a44878c0a9..7e11a05e1f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -42,6 +42,7 @@ apply from: 'gradle/root/coverage.gradle'
 apply from: 'gradle/mockito-core/inline-mock.gradle'
 apply from: 'gradle/mockito-core/osgi.gradle'
 apply from: 'gradle/mockito-core/javadoc.gradle'
+apply from: 'gradle/mockito-core/reproducible-build.gradle'
 apply from: 'gradle/mockito-core/testing.gradle'
 
 apply from: 'gradle/dependencies.gradle'
@@ -64,6 +65,12 @@ allprojects { proj ->
         options.addStringOption('charSet', 'UTF-8')
         options.setSource('8')
     }
+
+    tasks.withType(AbstractArchiveTask) {
+        preserveFileTimestamps = false
+        reproducibleFileOrder = true
+    }
+
     apply plugin: 'checkstyle'
     checkstyle {
        configFile = rootProject.file('config/checkstyle/checkstyle.xml')
diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle
index 1e942f6569..9ed59f8363 100644
--- a/gradle/mockito-core/osgi.gradle
+++ b/gradle/mockito-core/osgi.gradle
@@ -1,3 +1,12 @@
+import java.nio.file.attribute.FileTime
+import java.util.jar.Attributes
+import java.util.jar.JarEntry
+import java.util.jar.JarFile
+import java.util.jar.JarOutputStream
+import java.util.jar.Manifest
+
+import static java.util.Calendar.FEBRUARY
+
 apply plugin: 'osgi'
 
 afterEvaluate {
@@ -31,5 +40,88 @@ afterEvaluate {
 
             attributes 'Automatic-Module-Name': 'org.mockito'
         }
+
+        jar.doLast {
+            JarFile originalJar = new JarFile(jar.archivePath)
+
+            new RemoveOsgiLastModifiedHeader(originalJar)
+                .transform()
+                .renameTo jar.archivePath
+        }
+
     }
 }
+
+
+/*
+ * The OSGi plugin in Gradle 5.3 has a known issue (https://github.com/gradle/gradle/issues/6187) where it embeds
+ * a Manifest entry "Bnd-LastModified" (set to the last modified time of the build directory) even if you ask it not to
+ * using `-noextraheaders` or `-removeheaders`.
+ *
+ * It cannot be pinned or removed, and is a source of non-determinism in the build.
+ *
+ * This class addresses the problem by rewriting the JAR and removing that entry from the Manifest. A side-effect of this
+ * is having to set `lastModifiedTime` for each entry to a fixed value, else this would also introduce non-determinism.
+ *
+ * The fixed value is the same as the default value for Gradle's fixed timestamps, and the rationale behind it is detailed
+ * in https://github.com/gradle/gradle/blob/58538513a3bff3b7015718976fe1304e23f40694/subprojects/core/src/main/java/org/gradle/api/internal/file/archive/ZipCopyAction.java#L42-L57
+ */
+
+class RemoveOsgiLastModifiedHeader {
+    private final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, FEBRUARY, 1, 0, 0, 0).timeInMillis
+
+    private final JarFile artifact
+
+    RemoveOsgiLastModifiedHeader(JarFile artifact) {
+        this.artifact = artifact
+    }
+
+    File transform() {
+        File temp = File.createTempFile("temp",".jar")
+
+        temp.withOutputStream { os ->
+            JarOutputStream stream = new JarOutputStream(os)
+
+            this.artifact
+                .entries()
+                .sort { it.name }
+                .each { JarEntry entry ->
+
+                    stream.putNextEntry(newJarEntry(entry))
+
+                    if (entry.name == "META-INF/MANIFEST.MF") {
+                        newManifest(entry).write(stream)
+                    } else {
+                        stream << this.artifact.getInputStream(entry)
+                    }
+
+                    stream.closeEntry()
+                }
+
+            stream.finish()
+        }
+
+        temp
+    }
+
+    Manifest newManifest(JarEntry entry) {
+        Manifest manifest = new Manifest()
+
+        manifest.read(this.artifact.getInputStream(entry))
+
+        manifest
+            .getMainAttributes()
+            .remove(new Attributes.Name("Bnd-LastModified"))
+
+        manifest
+    }
+
+    JarEntry newJarEntry(JarEntry original) {
+        JarEntry newEntry = new JarEntry(original.name)
+
+        newEntry.setLastModifiedTime(FileTime.fromMillis(CONSTANT_TIME_FOR_ZIP_ENTRIES))
+
+        newEntry
+    }
+
+}
diff --git a/gradle/mockito-core/reproducible-build.gradle b/gradle/mockito-core/reproducible-build.gradle
new file mode 100644
index 0000000000..bb513706ab
--- /dev/null
+++ b/gradle/mockito-core/reproducible-build.gradle
@@ -0,0 +1,69 @@
+import java.security.DigestInputStream
+import java.security.MessageDigest
+
+/*
+ * The `checkReproducibility` task compares two sets of checksums, generated
+ * in two independent builds, from non-javadoc output archives.
+ *
+ * This task ensures that a change has not regressed the reproducibility of
+ * the Mockito project and its subprojects.
+ */
+
+task checkReproducibility {
+    doLast {
+        def first = new File("checksums", "checksums-1.txt").text.split('\n')
+        def second = new File("checksums", "checksums-2.txt").text.split('\n')
+
+        assert first.sort() == second.sort()
+    }
+}
+
+task getChecksums1(type: GradleBuild) {
+    tasks = ['clean', 'assemble']
+    startParameter.projectProperties = ['build-id': "1"]
+}
+
+task getChecksums2(type: GradleBuild) {
+    tasks = ['clean', 'assemble']
+    startParameter.projectProperties = ['build-id': "2"]
+}
+
+getChecksums2.dependsOn(getChecksums1)
+checkReproducibility.dependsOn(getChecksums2)
+
+if (project.hasProperty('build-id')) {
+
+    String id = project.getProperty('build-id')
+
+    mkdir "checksums"
+
+    File checksums = new File("checksums", "checksums-${id}.txt")
+    checksums.delete()
+
+    afterEvaluate {
+
+        ([project] + subprojects).each { p ->
+
+            p.tasks.withType(AbstractArchiveTask) { task ->
+
+                if (!task.name.contains('javadoc')) {
+                    task.doLast {
+                        File output = task.archiveFile.get().getAsFile()
+
+                        checksums << "${output.name},${calculateHash(output)}\n"
+                    }
+                }
+            }
+        }
+
+    }
+}
+
+static def calculateHash(File file) {
+    file.withInputStream {
+        new DigestInputStream(it, MessageDigest.getInstance("SHA-256")).withStream {
+            it.eachByte {}
+            it.messageDigest.digest().encodeHex() as String
+        }
+    }
+}

From 4e1ae5155f5e67f5afb1934f95bc8af9283da76b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marcin=20Miko=C5=82ajczyk?=
 <62449358+mikolajczykmarcin@users.noreply.github.com>
Date: Tue, 24 Mar 2020 21:37:31 +0100
Subject: [PATCH 012/963] Fixes #1894: Use relative path in CheckStyle config
 to fix Windows build (#1895)

---
 config/checkstyle/checkstyle.xml                          | 2 +-
 src/test/java/org/mockitousage/matchers/MatchersTest.java | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml
index 2a5094bcda..b000ccb311 100644
--- a/config/checkstyle/checkstyle.xml
+++ b/config/checkstyle/checkstyle.xml
@@ -28,7 +28,7 @@
         
     
     
-        
+        
         
     
 
diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java
index 8c4b45afed..ca3e94de2f 100644
--- a/src/test/java/org/mockitousage/matchers/MatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java
@@ -608,7 +608,7 @@ public void same_matcher_and_nulls() {
     public void nullable_matcher() throws Exception {
         // imagine a Stream.of(...).map(c -> mock.oneArg(c))...
         mock.oneArg((Character) null);
-        mock.oneArg(Character.valueOf('€'));
+        mock.oneArg(Character.valueOf('\u20AC'));
 
         verify(mock, times(2)).oneArg(nullable(Character.class));
     }

From 62879b9531b1dc15af4255fa3906957affa92943 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marcin=20Miko=C5=82ajczyk?=
 <62449358+mikolajczykmarcin@users.noreply.github.com>
Date: Wed, 25 Mar 2020 19:07:25 +0100
Subject: [PATCH 013/963] Fixes #1885: Add java.time.{Duration,Period} to
 ReturnsEmptyValues (#1896)

---
 .../defaultanswers/ReturnsEmptyValues.java    |  7 ++
 .../mockito/internal/util/JavaEightUtil.java  | 96 ++++++++++++++++++-
 .../ReturnsEmptyValuesTest.java               | 16 ++++
 3 files changed, 114 insertions(+), 5 deletions(-)

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 8e92a0d93e..7e2ed1b829 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
@@ -42,6 +42,9 @@
  * Returns an {@code java.util.stream.Stream#empty() empty Stream} for Stream. Similarly for primitive stream variants.
  * 
  * 
  • + * Returns an {@code java.time.Duration.ZERO zero Duration} for empty Duration and {@code java.time.Period.ZERO zero Period} for empty Period. + *
  • + *
  • * Returns null for everything else *
  • * @@ -125,6 +128,10 @@ Object returnValueFor(Class type) { return JavaEightUtil.emptyIntStream(); } else if ("java.util.stream.LongStream".equals(type.getName())) { return JavaEightUtil.emptyLongStream(); + } else if ("java.time.Duration".equals(type.getName())) { + return JavaEightUtil.emptyDuration(); + } else if ("java.time.Period".equals(type.getName())) { + return JavaEightUtil.emptyPeriod(); } //Let's not care about the rest of collections. diff --git a/src/main/java/org/mockito/internal/util/JavaEightUtil.java b/src/main/java/org/mockito/internal/util/JavaEightUtil.java index ce85487a8b..5b2ffc3fb7 100644 --- a/src/main/java/org/mockito/internal/util/JavaEightUtil.java +++ b/src/main/java/org/mockito/internal/util/JavaEightUtil.java @@ -4,9 +4,10 @@ */ package org.mockito.internal.util; +import java.lang.reflect.Field; import java.lang.reflect.Method; -import org.mockito.internal.creation.instance.InstantiationException; +import org.mockito.creation.instance.InstantiationException; /** * Helper class to work with features that were introduced in Java versions after 1.5. @@ -19,6 +20,8 @@ public final class JavaEightUtil { private static Object emptyOptionalDouble; private static Object emptyOptionalInt; private static Object emptyOptionalLong; + private static Object emptyDuration; + private static Object emptyPeriod; private JavaEightUtil() { // utility class @@ -121,6 +124,35 @@ public static Object emptyLongStream() { return invokeNullaryFactoryMethod("java.util.stream.LongStream", "empty"); } + + /** + * Creates an empty Duration using reflection to stay backwards-compatible with older JDKs. + * + * @return an empty (ZERO) Duration. + */ + public static Object emptyDuration() { + // no need for double-checked locking + if (emptyDuration != null) { + return emptyDuration; + } + + return emptyDuration = getStaticFieldValue("java.time.Duration", "ZERO"); + } + + /** + * Creates an empty Period using reflection to stay backwards-compatible with older JDKs. + * + * @return an empty (ZERO) Period. + */ + public static Object emptyPeriod() { + // no need for double-checked locking + if (emptyPeriod != null) { + return emptyPeriod; + } + + return emptyPeriod = getStaticFieldValue("java.time.Period", "ZERO"); + } + /** * Invokes a nullary static factory method using reflection to stay backwards-compatible with older JDKs. * @@ -130,15 +162,69 @@ public static Object emptyLongStream() { */ private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) { try { - final Class type = Class.forName(fqcn); - final Method method = type.getMethod(methodName); - + final Method method = getMethod(fqcn, methodName); return method.invoke(null); // any exception is really unexpected since the type name has // 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. + * + * @param fqcn The fully qualified class name of the type to be produced. + * @param fieldName The name of th classes' field which value is going to be returned. + * @return the restored value. + */ + private static Object getStaticFieldValue(final String fqcn, final String fieldName) { + try { + final Class type = getClass(fqcn); + final Field field = type.getDeclaredField(fieldName); + return field.get(null); + // any exception is really unexpected since the type name has + // already been verified + } catch (Exception e) { + throw new InstantiationException( + String.format("Could not get %s#%s(): %s", fqcn, fieldName, e), e); + } + } + + /** + * Returns the {@code Class} object associated with the class or interface with the given string name. + * + * @param fqcn The fully qualified class name of the type to be produced. + * @return the Class object for the class with the specified name. + */ + private static Class getClass(String fqcn) { + try { + return Class.forName(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); + } + } + + /** + * Returns a Method object that reflects the specified public member method of the class or interface represented by the fully qualified class name. + * + * @param fqcn The fully qualified class name of the type to be produced. + * @param methodName The name of the method. + * @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) { + 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); } } } 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 ab68102c55..13ca291823 100644 --- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java +++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java @@ -158,6 +158,22 @@ private void verify_empty_Stream_is_returned(String streamFqcn) throws Exception assertEquals("count of empty " + streamFqcn, 0L, count); } + @Test + public void should_return_empty_duration() throws Exception { + //given + final String fqcn = "java.time.Duration"; + final Class durationClass = getClassOrSkipTest(fqcn); + + // when + final Object duration = values.returnValueFor(durationClass); + final int nano = (Integer) durationClass.getMethod("getNano").invoke(duration); + final long seconds = (Long) durationClass.getMethod("getSeconds").invoke(duration); + + // then + assertEquals("nano of empty " + fqcn, 0, nano); + assertEquals("seconds of empty " + fqcn, 0L, seconds); + } + /** * Tries to load the given class. If the class is not found, the complete test is skipped. */ From b2de4cce9d26470145135dde2cd51ac60f999fce Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Wed, 25 Mar 2020 18:14:22 +0000 Subject: [PATCH 014/963] 3.3.6 release (previous 3.3.5) + release notes updated by CI build 4416 [ci skip-release] --- doc/release-notes/official.md | 9 +++++++++ version.properties | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index c2525c2e99..37e1a7d038 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,14 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.6 + - 2020-03-25 - [3 commits](https://github.com/mockito/mockito/compare/v3.3.5...v3.3.6) by [Marcin Mikołajczyk](https://github.com/mikolajczykmarcin) (2), [Alex Wilson](https://github.com/mrwilson) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.6-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.6) + - Feature/returns empty java8 time [(#1896)](https://github.com/mockito/mockito/pull/1896) + - Fixes #1894 checkstyle error on windows [(#1895)](https://github.com/mockito/mockito/pull/1895) + - Checkstyle error on windows [(#1894)](https://github.com/mockito/mockito/issues/1894) + - Make JARs build reproducibly [(#1892)](https://github.com/mockito/mockito/pull/1892) + - Build is not reproducible [(#1891)](https://github.com/mockito/mockito/issues/1891) + - Add java.time types to ReturnsEmptyValues [(#1885)](https://github.com/mockito/mockito/issues/1885) + #### 3.3.5 - 2020-03-23 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.4...v3.3.5) by [Shyam Sundar J](https://github.com/severussundar) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.5-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.5) - Fixes #id : 1888 [(#1893)](https://github.com/mockito/mockito/pull/1893) diff --git a/version.properties b/version.properties index eea79ec34c..ada4325b0d 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.6 +version=3.3.7 #Previous version used to generate release notes delta -previousVersion=3.3.5 +previousVersion=3.3.6 From 26bd827a732c41d5115c63bbb0324fb3910192cc Mon Sep 17 00:00:00 2001 From: Eitan Adler Date: Sun, 12 Apr 2020 13:34:40 -0700 Subject: [PATCH 015/963] [documentation] Change deprecated warnings from 3.x -> 4.x (#1906) Mockito 3.x was released as an upgrade to Java 8, but without any API removals. All APIs scheduled for removal should be documented to be removed in Mockito 4. --- .../java/org/mockito/ArgumentMatchers.java | 19 ++++++++++--------- src/main/java/org/mockito/BDDMockito.java | 2 +- src/main/java/org/mockito/Matchers.java | 2 +- .../configuration/AnnotationEngine.java | 2 +- .../configuration/IMockitoConfiguration.java | 2 +- .../ReturnsMoreEmptyValues.java | 2 +- .../mockito/runners/MockitoJUnitRunner.java | 4 ++-- 7 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java index 9d79a72546..d63ddf0cbb 100644 --- a/src/main/java/org/mockito/ArgumentMatchers.java +++ b/src/main/java/org/mockito/ArgumentMatchers.java @@ -159,7 +159,8 @@ public static T any() { * @see #any(Class) * @see #notNull() * @see #notNull(Class) - * @deprecated This will be removed in Mockito 3.0 (which will be java 8 only) + * @deprecated This will be removed in Mockito 4.0 This method is only used for generic + * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated public static T anyObject() { @@ -519,7 +520,7 @@ public static List anyList() { * @see #anyList() * @see #isNull() * @see #isNull(Class) - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -580,7 +581,7 @@ public static Set anySet() { * @see #anySet() * @see #isNull() * @see #isNull(Class) - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -642,7 +643,7 @@ public static Map anyMap() { * @see #anyMap() * @see #isNull() * @see #isNull(Class) - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -703,7 +704,7 @@ public static Collection anyCollection() { * @see #anyCollection() * @see #isNull() * @see #isNull(Class) - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -766,7 +767,7 @@ public static Iterable anyIterable() { * @see #isNull() * @see #isNull(Class) * @since 2.1.0 - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -991,7 +992,7 @@ public static T isNull() { * @see #isNull() * @see #isNotNull() * @see #isNotNull(Class) - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -1035,7 +1036,7 @@ public static T notNull() { * @see #isNotNull() * @see #isNull() * @see #isNull(Class) - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated @@ -1077,7 +1078,7 @@ public static T isNotNull() { * * @param clazz Type to avoid casting * @return null. - * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic + * @deprecated With Java 8 this method will be removed in Mockito 4.0. This method is only used for generic * friendliness to avoid casting, this is not anymore needed in Java 8. */ @Deprecated diff --git a/src/main/java/org/mockito/BDDMockito.java b/src/main/java/org/mockito/BDDMockito.java index b2dbf6e751..b3ff0e7e5d 100644 --- a/src/main/java/org/mockito/BDDMockito.java +++ b/src/main/java/org/mockito/BDDMockito.java @@ -354,7 +354,7 @@ public interface BDDStubber { /** * See original {@link Stubber#doNothing()}. * - * This method will be removed in version 3.0.0 + * This method will be removed in version 4.0.0 * * @since 1.8.0 * @deprecated as of 2.1.0 please use {@link #willDoNothing()} instead diff --git a/src/main/java/org/mockito/Matchers.java b/src/main/java/org/mockito/Matchers.java index f6d07bc047..807cca1993 100644 --- a/src/main/java/org/mockito/Matchers.java +++ b/src/main/java/org/mockito/Matchers.java @@ -6,7 +6,7 @@ /** * @deprecated Use {@link ArgumentMatchers}. This class is now deprecated in order to avoid a name clash with Hamcrest - * org.hamcrest.Matchers class. This class will likely be removed in version 3.0. + * org.hamcrest.Matchers class. This class will likely be removed in version 4.0. */ @Deprecated public class Matchers extends ArgumentMatchers { diff --git a/src/main/java/org/mockito/configuration/AnnotationEngine.java b/src/main/java/org/mockito/configuration/AnnotationEngine.java index 40ff3526ff..ad08ae345e 100644 --- a/src/main/java/org/mockito/configuration/AnnotationEngine.java +++ b/src/main/java/org/mockito/configuration/AnnotationEngine.java @@ -21,7 +21,7 @@ * 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 3. + * this interface will probably be removed in mockito 4. */ @Deprecated public interface AnnotationEngine extends org.mockito.plugins.AnnotationEngine { diff --git a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java index 2c2da565fb..f9690dec3d 100644 --- a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java +++ b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java @@ -57,7 +57,7 @@ public interface IMockitoConfiguration { * See javadoc for {@link IMockitoConfiguration} * * @deprecated Please use the extension mechanism {@link org.mockito.plugins.AnnotationEngine} instead, - * this method will probably be removed in mockito 3. + * this method will probably be removed in mockito 4. */ @Deprecated AnnotationEngine getAnnotationEngine(); 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 6188f75931..2de1c70245 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java @@ -12,7 +12,7 @@ import org.mockito.stubbing.Answer; /** - * It's likely this implementation will be used by default by every Mockito 3.0.0 mock. + * It's likely this implementation will be used by default by every Mockito 4.0.0 mock. *

    * Currently used only by {@link Mockito#RETURNS_SMART_NULLS} *

    diff --git a/src/main/java/org/mockito/runners/MockitoJUnitRunner.java b/src/main/java/org/mockito/runners/MockitoJUnitRunner.java index 38522ce168..1c473c6863 100644 --- a/src/main/java/org/mockito/runners/MockitoJUnitRunner.java +++ b/src/main/java/org/mockito/runners/MockitoJUnitRunner.java @@ -23,7 +23,7 @@ public class MockitoJUnitRunner extends org.mockito.junit.MockitoJUnitRunner { /** * Silent runner moved to a new place see {@link org.mockito.junit.MockitoJUnitRunner.Silent} * - * @deprecated Moved to {@link org.mockito.junit.MockitoJUnitRunner.Silent}, this class will be removed with Mockito 3 + * @deprecated Moved to {@link org.mockito.junit.MockitoJUnitRunner.Silent}, this class will be removed with Mockito 4 */ @Deprecated public static class Silent extends MockitoJUnitRunner { @@ -35,7 +35,7 @@ public Silent(Class klass) throws InvocationTargetException { /** * Silent runner moved to a new place see {@link org.mockito.junit.MockitoJUnitRunner.Strict} * - * @deprecated Moved to {@link org.mockito.junit.MockitoJUnitRunner.Strict}, this class will be removed with Mockito 3 + * @deprecated Moved to {@link org.mockito.junit.MockitoJUnitRunner.Strict}, this class will be removed with Mockito 4 */ @Deprecated public static class Strict extends MockitoJUnitRunner { From bd3c45a7e9004f75021e3dc002d199fd17ada6e0 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sun, 12 Apr 2020 20:40:37 +0000 Subject: [PATCH 016/963] 3.3.7 release (previous 3.3.6) + release notes updated by CI build 4422 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 37e1a7d038..5919dab8c8 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.7 + - 2020-04-12 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.6...v3.3.7) by [Eitan Adler](https://github.com/grimreaper) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.7-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.7) + - [documentation] change deprecated warnings from 3.x -> 4.x [(#1906)](https://github.com/mockito/mockito/pull/1906) + #### 3.3.6 - 2020-03-25 - [3 commits](https://github.com/mockito/mockito/compare/v3.3.5...v3.3.6) by [Marcin Mikołajczyk](https://github.com/mikolajczykmarcin) (2), [Alex Wilson](https://github.com/mrwilson) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.6-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.6) - Feature/returns empty java8 time [(#1896)](https://github.com/mockito/mockito/pull/1896) diff --git a/version.properties b/version.properties index ada4325b0d..c5a22aaf02 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.7 +version=3.3.8 #Previous version used to generate release notes delta -previousVersion=3.3.6 +previousVersion=3.3.7 From 6336378048effe01abb1cd560c8286d44f9a353f Mon Sep 17 00:00:00 2001 From: Eitan Adler Date: Mon, 13 Apr 2020 06:12:12 -0700 Subject: [PATCH 017/963] [tests] Use ArgumentMatchers instead of Matchers (#1907) `org.mockito.Matchers` are considered deprecated but our own tests still used them. --- .../ParameterizedConstructorInstantiatorTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 1ffa6cfbf3..f3f3a48527 100644 --- a/src/test/java/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/ParameterizedConstructorInstantiatorTest.java @@ -20,7 +20,7 @@ import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver; @@ -69,7 +69,7 @@ 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(Matchers.[]>anyVararg())).willReturn(new Object[]{ observer, map }); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())).willReturn(new Object[]{ observer, map }); new ParameterizedConstructorInstantiator(this, field("withMultipleConstructor"), resolver).instantiate(); @@ -82,7 +82,7 @@ public void should_instantiate_type_if_resolver_provide_matching_types() throws 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(Matchers.[]>anyVararg())).willReturn(new Object[]{ observer, wrongArg }); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>any())).willReturn(new Object[]{ observer, wrongArg }); try { new ParameterizedConstructorInstantiator(this, field("withMultipleConstructor"), resolver).instantiate(); @@ -94,7 +94,7 @@ 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(Matchers.[]>anyVararg())).willReturn(new Object[]{ null }); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())).willReturn(new Object[]{ null }); try { new ParameterizedConstructorInstantiator(this, field("withThrowingConstructor"), resolver).instantiate(); @@ -107,7 +107,7 @@ 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(Matchers.[]>anyVararg())).willReturn(new Object[]{ "", vararg}); + given(resolver.resolveTypeInstances(ArgumentMatchers.[]>anyVararg())).willReturn(new Object[]{ "", vararg}); new ParameterizedConstructorInstantiator(this, field("withVarargConstructor"), resolver).instantiate(); From 572505131adf20aecc1a8b6ae1f7ea7bfc08c73f Mon Sep 17 00:00:00 2001 From: NanjanChung Date: Wed, 15 Apr 2020 18:18:11 +0800 Subject: [PATCH 018/963] Fixes #1910: update description of ArgumentMatcher javadoc (#1911) For any(), the doc says that "any() is an alias of: anyObject() and any(java.lang.Class)." But in the note, it says that "Since mockito 2.1.0 any(Class) is not anymore an alias of this method." This is confusing, so the alias in the doc should exclude any(java.lang.Class) to simply be "any() is an alias of: anyObject()" Also update the same issue of anyObject(). --- src/main/java/org/mockito/ArgumentMatchers.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java index d63ddf0cbb..d449b65011 100644 --- a/src/main/java/org/mockito/ArgumentMatchers.java +++ b/src/main/java/org/mockito/ArgumentMatchers.java @@ -121,7 +121,7 @@ public class ArgumentMatchers { *

    * See examples in javadoc for {@link ArgumentMatchers} class * - * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)} + * This is an alias of: {@link #anyObject()} *

    * *

    @@ -150,7 +150,7 @@ public static T any() { * Matches anything, including null. * *

    - * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}. + * This is an alias of: {@link #any()}. * See examples in javadoc for {@link ArgumentMatchers} class. *

    * From bbd19ea9108132778da1010513d1544f0c57e327 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Wed, 15 Apr 2020 10:29:40 +0000 Subject: [PATCH 019/963] 3.3.8 release (previous 3.3.7) + release notes updated by CI build 4429 [ci skip-release] --- doc/release-notes/official.md | 6 ++++++ version.properties | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 5919dab8c8..74407f4c62 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,11 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.8 + - 2020-04-15 - [2 commits](https://github.com/mockito/mockito/compare/v3.3.7...v3.3.8) by [Eitan Adler](https://github.com/grimreaper) (1), [NanjanChung](https://github.com/NanjanChung) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.8-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.8) + - Fixes #1910: update description of ArgumentMatcher javadoc [(#1911)](https://github.com/mockito/mockito/pull/1911) + - Documentation of ArgumentMatchers any() is confusing [(#1910)](https://github.com/mockito/mockito/issues/1910) + - [tests] use ArgumentMatchers over Matchers [(#1907)](https://github.com/mockito/mockito/pull/1907) + #### 3.3.7 - 2020-04-12 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.6...v3.3.7) by [Eitan Adler](https://github.com/grimreaper) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.7-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.7) - [documentation] change deprecated warnings from 3.x -> 4.x [(#1906)](https://github.com/mockito/mockito/pull/1906) diff --git a/version.properties b/version.properties index c5a22aaf02..6631db5569 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.8 +version=3.3.9 #Previous version used to generate release notes delta -previousVersion=3.3.7 +previousVersion=3.3.8 From c6f23366002abcfb4e0b7ab58891c75d0e23260a Mon Sep 17 00:00:00 2001 From: dean-burdaky Date: Mon, 20 Apr 2020 16:44:30 +0100 Subject: [PATCH 020/963] Fixes #1905 : Fix Pattern matcher not matching to subregion (#1914) Issue #1905 talked about a particular pattern using Java's Pattern that causes Mockito to not properly match the argument (provided with an invocation) to the expected answer. It was later discovered that the Pattern matcher matches to the entire region, not some subregion, by using Java's Matcher.match(). This commit fixes that by using Matcher.find(). --- src/main/java/org/mockito/internal/matchers/Matches.java | 2 +- src/test/java/org/mockitousage/matchers/MatchersTest.java | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/internal/matchers/Matches.java b/src/main/java/org/mockito/internal/matchers/Matches.java index 63b77ff43a..2649b32539 100644 --- a/src/main/java/org/mockito/internal/matchers/Matches.java +++ b/src/main/java/org/mockito/internal/matchers/Matches.java @@ -22,7 +22,7 @@ public Matches(Pattern pattern) { } public boolean matches(Object actual) { - return (actual instanceof String) && pattern.matcher((String) actual).matches(); + return (actual instanceof String) && pattern.matcher((String) actual).find(); } public String toString() { diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java index ca3e94de2f..25f49da5d5 100644 --- a/src/test/java/org/mockitousage/matchers/MatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java @@ -511,6 +511,14 @@ public void matches_Pattern_matcher() { assertEquals(null, mock.oneArg("blah")); } + @Test + public void matches_Pattern_matcher_in_subregion() { + when(mock.oneArg(matches(Pattern.compile("[a-z]")))).thenReturn("1"); + + assertEquals("1", mock.oneArg("3a45")); + assertEquals(null, mock.oneArg("3445")); + } + @Test public void contains_matcher() { when(mock.oneArg(contains("ell"))).thenReturn("1"); From f0e79e751fc4824d8e51473612063c11b0e56df8 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Mon, 20 Apr 2020 15:50:27 +0000 Subject: [PATCH 021/963] 3.3.9 release (previous 3.3.8) + release notes updated by CI build 4432 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 74407f4c62..083516ef0b 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.9 + - 2020-04-20 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.8...v3.3.9) by [dean-burdaky](https://github.com/dean-burdaky) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.9-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.9) + - Fix Pattern matcher not matching to subregion [(#1914)](https://github.com/mockito/mockito/pull/1914) + - ArgumentMatchers.matches not working [(#1905)](https://github.com/mockito/mockito/issues/1905) + #### 3.3.8 - 2020-04-15 - [2 commits](https://github.com/mockito/mockito/compare/v3.3.7...v3.3.8) by [Eitan Adler](https://github.com/grimreaper) (1), [NanjanChung](https://github.com/NanjanChung) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.8-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.8) - Fixes #1910: update description of ArgumentMatcher javadoc [(#1911)](https://github.com/mockito/mockito/pull/1911) diff --git a/version.properties b/version.properties index 6631db5569..694afb3a96 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.9 +version=3.3.10 #Previous version used to generate release notes delta -previousVersion=3.3.8 +previousVersion=3.3.9 From a8f0a7cd33eb29ec1cdf27d3d916e6db987dac65 Mon Sep 17 00:00:00 2001 From: netbeansuser2019 <57791842+netbeansuser2019@users.noreply.github.com> Date: Thu, 30 Apr 2020 14:31:03 +0200 Subject: [PATCH 022/963] Update ByteBuddy to 1.10.10 (#1920) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index e052dad88e..6f57f1f41c 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -4,7 +4,7 @@ ext { def versions = [:] -versions.bytebuddy = '1.10.5' +versions.bytebuddy = '1.10.10' versions.junitJupiter = '5.4.2' versions.errorprone = '2.3.2' From 121dafad02d64044184c983715bd69f3d208581c Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 30 Apr 2020 12:37:23 +0000 Subject: [PATCH 023/963] 3.3.10 release (previous 3.3.9) + release notes updated by CI build 4435 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 083516ef0b..643afe0880 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.10 + - 2020-04-30 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.9...v3.3.10) by [netbeansuser2019](https://github.com/netbeansuser2019) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.10-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.10) + - Update dependencies.gradle [(#1920)](https://github.com/mockito/mockito/pull/1920) + #### 3.3.9 - 2020-04-20 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.8...v3.3.9) by [dean-burdaky](https://github.com/dean-burdaky) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.9-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.9) - Fix Pattern matcher not matching to subregion [(#1914)](https://github.com/mockito/mockito/pull/1914) diff --git a/version.properties b/version.properties index 694afb3a96..72017d3c4b 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.10 +version=3.3.11 #Previous version used to generate release notes delta -previousVersion=3.3.9 +previousVersion=3.3.10 From 47604395f37ab626b498f24c34af6198167d453a Mon Sep 17 00:00:00 2001 From: Andrei Silviu Dragnea Date: Fri, 8 May 2020 03:43:04 +0300 Subject: [PATCH 024/963] Fix JUnit 5 strict stubs check on test failure If the test fails, MockitoExtension should not check for strict stubs at the end of the test. --- .../junit/jupiter/MockitoExtension.java | 17 +++++---- .../java/org/mockitousage/StrictnessTest.java | 36 +++++++++++++++---- 2 files changed, 37 insertions(+), 16 deletions(-) diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java index 6219506634..32609c38b4 100644 --- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java +++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java @@ -5,6 +5,13 @@ package org.mockito.junit.jupiter; +import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create; +import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation; + +import java.lang.reflect.Parameter; +import java.util.List; +import java.util.Optional; + import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; @@ -21,13 +28,6 @@ import org.mockito.junit.MockitoJUnitRunner; import org.mockito.quality.Strictness; -import java.lang.reflect.Parameter; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create; -import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation; - /** * Extension that initializes mocks and handles strict stubbings. This extension is the JUnit Jupiter equivalent * of our JUnit4 {@link MockitoJUnitRunner}. @@ -178,7 +178,7 @@ private Optional retrieveAnnotationFromTestClasses(final Extens @Override public void afterEach(ExtensionContext context) { context.getStore(MOCKITO).remove(SESSION, MockitoSession.class) - .finishMocking(); + .finishMocking(context.getExecutionException().orElse(null)); } @Override @@ -186,7 +186,6 @@ public boolean supportsParameter(ParameterContext parameterContext, ExtensionCon return parameterContext.isAnnotated(Mock.class); } - @SuppressWarnings("ConstantConditions") @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { final Parameter parameter = parameterContext.getParameter(); diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java index 560b2f1c73..46b1a0e83b 100644 --- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java +++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java @@ -4,6 +4,12 @@ */ package org.mockitousage; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; + +import java.util.function.Function; + import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,21 +23,15 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.exceptions.misusing.UnnecessaryStubbingException; -import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import java.util.function.Function; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; - /** * Test that runs the inner test using a launcher {@see #invokeTestClassAndRetrieveMethodResult}. * We then assert on the actual test run output, to see if test actually failed as a result * of our extension. */ -@SuppressWarnings("ConstantConditions") class StrictnessTest { @MockitoSettings(strictness = Strictness.STRICT_STUBS) @@ -53,6 +53,28 @@ void session_checks_for_strict_stubs() { assertThat(result.getThrowable().get()).isInstanceOf(UnnecessaryStubbingException.class); } + @MockitoSettings(strictness = Strictness.STRICT_STUBS) + static class StrictStubsNotReportedOnTestFailure { + @Mock + private Function rootMock; + + @Test + void should_not_throw_exception_on_strict_stubs_because_of_test_failure() { + Mockito.when(rootMock.apply(10)).thenReturn("Foo"); + fail("Test failed"); + } + } + + @Test + void session_does_not_check_for_strict_stubs_on_test_failure() { + TestExecutionResult result = invokeTestClassAndRetrieveMethodResult(StrictStubsNotReportedOnTestFailure.class); + + assertThat(result.getStatus()).isEqualTo(TestExecutionResult.Status.FAILED); + Throwable throwable = result.getThrowable().get(); + assertThat(throwable).isInstanceOf(AssertionError.class); + assertThat(throwable.getSuppressed()).isEmpty(); + } + @MockitoSettings(strictness = Strictness.STRICT_STUBS) static class ConfiguredStrictStubs { @Nested From 1f63f57945394772f623506967b4b68590ba9dfe Mon Sep 17 00:00:00 2001 From: Andrei Silviu Dragnea Date: Fri, 8 May 2020 23:31:37 +0300 Subject: [PATCH 025/963] Fix import order documentation in CONTRIBUTING.md (#1927) --- .github/CONTRIBUTING.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 1cdaaa1fac..e45e2ef61c 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -12,7 +12,7 @@ # Contributing to Mockito -Which branch : +Which branch : * On mockito 3.x (or 2.x), make your pull request target `release/3.x` (or `release/2.x`) * On next mockito version make your pull request target `release/3.x` @@ -73,7 +73,7 @@ This section is not about some kind of fruitless tabs vs spaces debate. It's abo _This includes IntelliJ IDEA instructions, however we are sure there's similar settings in all major IDEs._ -But first of all, make sure that : +But first of all, make sure that : * Don't use tabs, only spaces * Character encoding is **UTF-8** @@ -100,6 +100,7 @@ Imports must be sorted in the following order 1. blank line 1. `import java.*` 1. `import javax.*` +1. blank line 1. `import all other imports` This order can be set in `IntelliJ setting > Editor > Code Style > Java > Imports > Import Layout` @@ -108,8 +109,8 @@ Also make sure that * One blank lines before imports. * One blank lines after imports. * Never import with wildcard `*` - * Set `IntelliJ setting > Editor > Code Style > Java > Imports > Class count to use import with '*'` to `100` - * Set `IntelliJ setting > Editor > Code Style > Java > Imports > Names count to use import static with '*'` to `100` + * Set `IntelliJ setting > Editor > Code Style > Java > Imports > Class count to use import with '*'` to `100` + * Set `IntelliJ setting > Editor > Code Style > Java > Imports > Names count to use import static with '*'` to `100` ### Alignment @@ -164,7 +165,7 @@ We found vertical alignment helping when reading the code, for that reason we wa ```java @Mock(answer = Answers.RETURNS_DEFAULTS, - serializable = true, + serializable = true, extraInterfaces = { List.class, YetAnotherInterface.class }) ``` From 56b0e54a99d70a17e4c305e3b23370ce7d5b33df Mon Sep 17 00:00:00 2001 From: Eitan Adler Date: Sun, 10 May 2020 03:26:34 -0700 Subject: [PATCH 026/963] Add Gradle upgrade finder task (#1922) --- .github/CONTRIBUTING.md | 4 ++++ build.gradle | 1 + 2 files changed, 5 insertions(+) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index e45e2ef61c..f8135316b5 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -189,3 +189,7 @@ We found vertical alignment helping when reading the code, for that reason we wa 1. For parameter `Throws list` choose : `Do not wrap` 2. For sub-parameter `Align when multiline` tick the checkbox +## Gradle Tips + +1. It is possible to run `./gradlew dependencyUpdates` to find out of date dependencies, including tools. Note that this + may show beta or alpha dependencies. diff --git a/build.gradle b/build.gradle index 7e11a05e1f..5009dc14bd 100644 --- a/build.gradle +++ b/build.gradle @@ -18,6 +18,7 @@ plugins { id 'com.gradle.build-scan' version '2.2.1' id "com.diffplug.gradle.spotless" version "3.24.3" id 'eclipse' + id 'com.github.ben-manes.versions' version '0.28.0' } description = 'Mockito mock objects library core API and implementation' From c86d015e246b87dc0dd2916fdc7587a1445bee46 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Mon, 11 May 2020 06:43:13 -0700 Subject: [PATCH 027/963] Fortified an assertion --- .../java/org/mockitousage/StrictnessTest.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java index 46b1a0e83b..31a5d6a649 100644 --- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java +++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/StrictnessTest.java @@ -4,12 +4,6 @@ */ package org.mockitousage; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; - -import java.util.function.Function; - import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -27,6 +21,11 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import java.util.function.Function; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; + /** * Test that runs the inner test using a launcher {@see #invokeTestClassAndRetrieveMethodResult}. * We then assert on the actual test run output, to see if test actually failed as a result @@ -53,6 +52,9 @@ void session_checks_for_strict_stubs() { assertThat(result.getThrowable().get()).isInstanceOf(UnnecessaryStubbingException.class); } + static class MyAssertionError extends AssertionError { + } + @MockitoSettings(strictness = Strictness.STRICT_STUBS) static class StrictStubsNotReportedOnTestFailure { @Mock @@ -61,7 +63,7 @@ static class StrictStubsNotReportedOnTestFailure { @Test void should_not_throw_exception_on_strict_stubs_because_of_test_failure() { Mockito.when(rootMock.apply(10)).thenReturn("Foo"); - fail("Test failed"); + throw new MyAssertionError(); } } @@ -71,7 +73,7 @@ void session_does_not_check_for_strict_stubs_on_test_failure() { assertThat(result.getStatus()).isEqualTo(TestExecutionResult.Status.FAILED); Throwable throwable = result.getThrowable().get(); - assertThat(throwable).isInstanceOf(AssertionError.class); + assertThat(throwable).isInstanceOf(MyAssertionError.class); assertThat(throwable.getSuppressed()).isEmpty(); } From 76a3ab89bec8222243f40b778457d13160cecad1 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 14 May 2020 14:53:11 +0000 Subject: [PATCH 028/963] 3.3.11 release (previous 3.3.10) + release notes updated by CI build 4450 [ci skip-release] --- doc/release-notes/official.md | 6 ++++++ version.properties | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 643afe0880..4300d354d7 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,11 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.11 + - 2020-05-14 - [5 commits](https://github.com/mockito/mockito/compare/v3.3.10...v3.3.11) by [Andrei Silviu Dragnea](https://github.com/andreisilviudragnea) (2), [Szczepan Faber](https://github.com/mockitoguy) (2), [Eitan Adler](https://github.com/grimreaper) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.11-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.11) + - JUnit 5 strict stubs check should not suppress the regular test failure [(#1928)](https://github.com/mockito/mockito/pull/1928) + - Fix import order [(#1927)](https://github.com/mockito/mockito/pull/1927) + - [build] add ben-manes dependency upgrade finder [(#1922)](https://github.com/mockito/mockito/pull/1922) + #### 3.3.10 - 2020-04-30 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.9...v3.3.10) by [netbeansuser2019](https://github.com/netbeansuser2019) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.10-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.10) - Update dependencies.gradle [(#1920)](https://github.com/mockito/mockito/pull/1920) diff --git a/version.properties b/version.properties index 72017d3c4b..2f162df908 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.11 +version=3.3.12 #Previous version used to generate release notes delta -previousVersion=3.3.10 +previousVersion=3.3.11 From a3331ae21d94a02b3834f408df7eb6efd2767669 Mon Sep 17 00:00:00 2001 From: Vinicius Scheidegger Date: Mon, 25 May 2020 17:01:43 +0200 Subject: [PATCH 029/963] Remove reference to internal class in AdditionalAnswers javadoc (#1938) --- src/main/java/org/mockito/AdditionalAnswers.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java index 0281f32227..684e5461ac 100644 --- a/src/main/java/org/mockito/AdditionalAnswers.java +++ b/src/main/java/org/mockito/AdditionalAnswers.java @@ -308,7 +308,7 @@ public static Answer delegatesTo(Object delegate) { * when(mock.foo()).thenReturn(1, 2, 3); * * //is equivalent to: - * when(mock.foo()).thenAnswer(new ReturnsElementsOf(Arrays.asList(1, 2, 3))); + * when(mock.foo()).thenAnswer(AdditionalAnswers.returnsElementsOf(Arrays.asList(1, 2, 3))); *
    * * @param elements The collection of elements to return. From 1983c75f4640a5dac56ddfd38cd205f213948bdb Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Mon, 25 May 2020 15:07:58 +0000 Subject: [PATCH 030/963] 3.3.12 release (previous 3.3.11) + release notes updated by CI build 4456 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 4300d354d7..10ffc95186 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.3.12 + - 2020-05-25 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.11...v3.3.12) by [Vinicius Scheidegger](https://github.com/vinischeidegger) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.12-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.12) + - Update javadoc - remove deprecated class [(#1938)](https://github.com/mockito/mockito/pull/1938) + #### 3.3.11 - 2020-05-14 - [5 commits](https://github.com/mockito/mockito/compare/v3.3.10...v3.3.11) by [Andrei Silviu Dragnea](https://github.com/andreisilviudragnea) (2), [Szczepan Faber](https://github.com/mockitoguy) (2), [Eitan Adler](https://github.com/grimreaper) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.11-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.11) - JUnit 5 strict stubs check should not suppress the regular test failure [(#1928)](https://github.com/mockito/mockito/pull/1928) diff --git a/version.properties b/version.properties index 2f162df908..de331257ca 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.12 +version=3.3.13 #Previous version used to generate release notes delta -previousVersion=3.3.11 +previousVersion=3.3.12 From 662017026f1cb0a50bc28cb32e4b5806dfbdb552 Mon Sep 17 00:00:00 2001 From: Eitan Adler Date: Wed, 27 May 2020 00:18:33 -0700 Subject: [PATCH 031/963] [checkstyle] Switch to new DTD (#1940) The location for the checkstyle DTD has moved. --- config/checkstyle/checkstyle.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index b000ccb311..850e3c8ec8 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -1,7 +1,7 @@ + "https://checkstyle.org/dtds/configuration_1_2.dtd"> ;tt;6F?E5=fUWDwQhp*drQ%hH0<5t2m)rFP%=6aPIC0j$R znGI0hcV~}vk?^&G`v~YCKc7#DrdMM3TcPBmxx#XUC_JVEt@k=%3-+7<3*fTcQ>f~?TdLjv96nb66xj=wVQfpuCD(?kzs~dUV<}P+Fpd)BOTO^<*E#H zeE80(b~h<*Qgez(iFFOkl!G!6#9NZAnsxghe$L=Twi^(Q&48 zD0ohTj)kGLD){xu%pm|}f#ZaFPYpHtg!HB30>F1c=cP)RqzK2co`01O5qwAP zUJm0jS0#mci>|Nu4#MF@u-%-4t>oUTnn_#3K09Hrwnw13HO@9L;wFJ*Z@=gCgpA@p zMswqk;)PTXWuMC-^MQxyNu8_G-i3W9!MLd2>;cM+;Hf&w| zLv{p*hArp9+h2wsMqT5WVqkkc0>1uokMox{AgAvDG^YJebD-czexMB!lJKWllLoBI zetW2;;FKI1xNtA(ZWys!_un~+834+6y|uV&Lo%dKwhcoDzRADYM*peh{o`-tHvwWIBIXW`PKwS3|M>CW37Z2dr!uJWNFS5UwY4;I zNIy1^sr+@8Fob%DHRNa&G{lm?KWU7sV2x9(Ft5?QKsLXi!v6@n&Iyaz5&U*|hCz+d z9vu60IG<v6+^ZmBs_aN!}p|{f(ikVl&LcB+UY;PPz* zj84Tm>g5~-X=GF_4JrVmtEtm=3mMEL1#z+pc~t^Iify^ft~cE=R0TymXu*iQL+XLX zdSK$~5pglr3f@Lrcp`>==b5Z6r7c=p=@A5nXNacsPfr(5m;~ks@*Wu7A z%WyY$Pt*RAKHz_7cghHuQqdU>hq$vD?plol_1EU(Fkgyo&Q2&2e?FT3;H%!|bhU~D z>VX4-6}JLQz8g3%Bq}n^NhfJur~v5H0dbB^$~+7lY{f3ES}E?|JnoLsAG%l^%eu_PM zEl0W(sbMRB3rFeYG&tR~(i2J0)RjngE`N_Jvxx!UAA1mc7J>9)`c=`}4bVbm8&{A` z3sMPU-!r-8de=P(C@7-{GgB<5I%)x{WfzJwEvG#hn3ict8@mexdoTz*(XX!C&~}L* z^%3eYQ8{Smsmq(GIM4d5ilDUk{t@2@*-aevxhy7yk(wH?8yFz%gOAXRbCYzm)=AsM z?~+vo2;{-jkA%Pqwq&co;|m{=y}y2lN$QPK>G_+jP`&?U&Ubq~T`BzAj1TlC`%8+$ zzdwNf<3suPnbh&`AI7RAYuQ<#!sD|A=ky2?hca{uHsB|0VqShI1G3lG5g}9~WSvy4 zX3p~Us^f5AfXlBZ0hA;mR6aj~Q8yb^QDaS*LFQwg!!<|W!%WX9Yu}HThc7>oC9##H zEW`}UQ%JQ38UdsxEUBrA@=6R-v1P6IoIw8$8fw6F{OSC7`cOr*u?p_0*Jvj|S)1cd z-9T);F8F-Y_*+h-Yt9cQQq{E|y^b@r&6=Cd9j0EZL}Pj*RdyxgJentY49AyC@PM<< zl&*aq_ubX%*pqUkQ^Zsi@DqhIeR&Ad)slJ2g zmeo&+(g!tg$z1ao1a#Qq1J022mH4}y?AvWboI4H028;trScqDQrB36t!gs|uZS9}KG0}DD$ zf2xF}M*@VJSzEJ5>ucf+L_AtN-Ht=34g&C?oPP>W^bwoigIncKUyf61!ce!2zpcNT zj&;rPGI~q2!Sy>Q7_lRX*DoIs-1Cei=Cd=+Xv4=%bn#Yqo@C=V`|QwlF0Y- zONtrwpHQ##4}VCL-1ol(e<~KU9-ja^kryz!g!})y-2S5z2^gE$Isj8l{%tF=Rzy`r z^RcP7vu`jHgHLKUE957n3j+BeE(bf;f)Zw($XaU6rZ26Upl#Yv28=8Y`hew{MbH>* z-sGI6dnb5D&dUCUBS`NLAIBP!Vi!2+~=AU+)^X^IpOEAn#+ab=`7c z%7B|mZ>wU+L;^&abXKan&N)O;=XI#dTV|9OMYxYqLbtT#GY8PP$45Rm2~of+J>>HIKIVn(uQf-rp09_MwOVIp@6!8bKV(C#(KxcW z;Pesq(wSafCc>iJNV8sg&`!g&G55<06{_1pIoL`2<7hPvAzR1+>H6Rx0Ra%4j7H-<-fnivydlm{TBr06;J-Bq8GdE^Amo)ptV>kS!Kyp*`wUx=K@{3cGZnz53`+C zLco1jxLkLNgbEdU)pRKB#Pq(#(Jt>)Yh8M?j^w&RPUueC)X(6`@@2R~PV@G(8xPwO z^B8^+`qZnQr$8AJ7<06J**+T8xIs)XCV6E_3W+al18!ycMqCfV>=rW0KBRjC* zuJkvrv;t&xBpl?OB3+Li(vQsS(-TPZ)Pw2>s8(3eF3=n*i0uqv@RM^T#Ql7(Em{(~%f2Fw|Reg@eSCey~P zBQlW)_DioA*yxxDcER@_=C1MC{UswPMLr5BQ~T6AcRyt0W44ffJG#T~Fk}wU^aYoF zYTayu-s?)<`2H(w+1(6X&I4?m3&8sok^jpXBB<|ZENso#?v@R1^DdVvKoD?}3%@{}}_E7;wt9USgrfR3(wabPRhJ{#1es81yP!o4)n~CGsh2_Yj2F^z|t zk((i&%nDLA%4KFdG96pQR26W>R2^?C1X4+a*hIzL$L=n4M7r$NOTQEo+k|2~SUI{XL{ynLSCPe%gWMMPFLO{&VN2pom zBUCQ(30qj=YtD_6H0-ZrJ46~YY*A;?tmaGvHvS^H&FXUG4)%-a1K~ly6LYaIn+4lG zt=wuGLw!%h=Pyz?TP=?6O-K-sT4W%_|Nl~;k~YA^_`gqfe{Xw=PWn#9f1mNz)sFuL zJbrevo(DPgpirvGMb6ByuEPd=Rgn}fYXqeUKyM+!n(cKeo|IY%p!#va6`D8?A*{u3 zEeWw0*oylJ1X!L#OCKktX2|>-z3#>`9xr~azOH+2dXHRwdfnpri9|xmK^Q~AuY!Fg z`9Xx?hxkJge~)NVkPQ(VaW(Ce2pXEtgY*cL8i4E)mM(iz_vdm|f@%cSb*Lw{WbShh41VGuplex9E^VvW}irx|;_{VK=N_WF39^ zH4<*peWzgc)0UQi4fBk2{FEzldDh5+KlRd!$_*@eYRMMRb1gU~9lSO_>Vh-~q|NTD zL}X*~hgMj$*Gp5AEs~>Bbjjq7G>}>ki1VxA>@kIhLe+(EQS0mjNEP&eXs5)I;7m1a zmK0Ly*!d~Dk4uxRIO%iZ!1-ztZxOG#W!Q_$M7_DKND0OwI+uC;PQCbQ#k#Y=^zQve zTZVepdX>5{JSJb;DX3%3g42Wz2D@%rhIhLBaFmx#ZV8mhya}jo1u{t^tzoiQy=jJp zjY2b7D2f$ZzJx)8fknqdD6fd5-iF8e(V}(@xe)N=fvS%{X$BRvW!N3TS8jn=P%;5j zShSbzsLs3uqycFi3=iSvqH~}bQn1WQGOL4?trj(kl?+q2R23I42!ipQ&`I*&?G#i9 zWvNh8xoGKDt>%@i0+}j?Ykw&_2C4!aYEW0^7)h2Hi7$;qgF3;Go?bs=v)kHmvd|`R z%(n94LdfxxZ)zh$ET8dH1F&J#O5&IcPH3=8o;%>OIT6w$P1Yz4S!}kJHNhMQ1(prc zM-jSA-7Iq=PiqxKSWb+YbLB-)lSkD6=!`4VL~`ExISOh2ud=TI&SKfR4J08Bad&rj zcXxMpcNgOB?w$~L7l^wPcXxw$0=$oV?)`I44)}b#ChS`_lBQhvb6ks?HDr3tFgkg&td19?b8=!sETXtp=&+3T$cCwZe z0nAET-7561gsbBws$TVjP7QxY(NuBYXVn9~9%vyN-B#&tJhWgtL1B<%BTS*-2$xB` zO)cMDHoWsm%JACZF--Pa7oP;f!n%p`*trlpvZ!HKoB={l+-(8O;;eYv2A=ra z3U7rSMCkP_6wAy`l|Se(&5|AefXvV1E#XA(LT!% zjj4|~xlZ-kPLNeQLFyXb%$K}YEfCBvHA-Znw#dZSI6V%3YD{Wj2@utT5Hieyofp6Qi+lz!u)htnI1GWzvQsA)baEuw9|+&(E@p8M+#&fsX@Kf`_YQ>VM+40YLv`3-(!Z7HKYg@+l00WGr779i-%t`kid%e zDtbh8UfBVT3|=8FrNian@aR3*DTUy&u&05x%(Lm3yNoBZXMHWS7OjdqHp>cD>g!wK z#~R{1`%v$IP;rBoP0B0P><;dxN9Xr+fp*s_EK3{EZ94{AV0#Mtv?;$1YaAdEiq5)g zYME;XN9cZs$;*2p63Q9^x&>PaA1p^5m7|W?hrXp2^m;B@xg0bD?J;wIbm6O~Nq^^K z2AYQs@7k)L#tgUkTOUHsh&*6b*EjYmwngU}qesKYPWxU-z_D> zDWr|K)XLf_3#k_9Rd;(@=P^S^?Wqlwert#9(A$*Y$s-Hy)BA0U0+Y58zs~h=YtDKxY0~BO^0&9{?6Nny;3=l59(6ec9j(79M?P1cE zex!T%$Ta-KhjFZLHjmPl_D=NhJULC}i$}9Qt?nm6K6-i8&X_P+i(c*LI3mtl3 z*B+F+7pnAZ5}UU_eImDj(et;Khf-z^4uHwrA7dwAm-e4 zwP1$Ov3NP5ts+e(SvM)u!3aZMuFQq@KE-W;K6 zag=H~vzsua&4Sb$4ja>&cSJ)jjVebuj+?ivYqrwp3!5>ul`B*4hJGrF;!`FaE+wKo z#};5)euvxC1zX0-G;AV@R(ZMl=q_~u8mQ5OYl;@BAkt)~#PynFX#c1K zUQ1^_N8g+IZwUl*n0Bb-vvliVtM=zuMGU-4a8|_8f|2GEd(2zSV?aSHUN9X^GDA8M zgTZW06m*iAy@7l>F3!7+_Y3mj^vjBsAux3$%U#d$BT^fTf-7{Y z_W0l=7$ro5IDt7jp;^cWh^Zl3Ga1qFNrprdu#g=n9=KH!CjLF#ucU5gy6*uASO~|b z7gcqm90K@rqe({P>;ww_q%4}@bq`ST8!0{V08YXY)5&V!>Td)?j7#K}HVaN4FU4DZ z%|7OppQq-h`HJ;rw-BAfH* z1H$ufM~W{%+b@9NK?RAp-$(P0N=b<(;wFbBN0{u5vc+>aoZ|3&^a866X@el7E8!E7 z=9V(Ma**m_{DKZit2k;ZOINI~E$|wO99by=HO{GNc1t?nl8soP@gxk8)WfxhIoxTP zoO`RA0VCaq)&iRDN9yh_@|zqF+f07Esbhe!e-j$^PS57%mq2p=+C%0KiwV#t^%_hH zoO?{^_yk5x~S)haR6akK6d|#2TN& zfWcN zc7QAWl)E9`!KlY>7^DNw$=yYmmRto>w0L(~fe?|n6k2TBsyG@sI)goigj=mn)E)I* z4_AGyEL7?(_+2z=1N@D}9$7FYdTu;%MFGP_mEJXc2OuXEcY1-$fpt8m_r2B|<~Xfs zX@3RQi`E-1}^9N{$(|YS@#{ZWuCxo)91{k>ESD54g_LYhm~vlOK_CAJHeYFfuIVB^%cqCfvpy#sU8Do8u}# z>>%PLKOZ^+$H54o@brtL-hHorSKcsjk_ZibBKBgyHt~L z=T6?e0oLX|h!Z3lbkPMO27MM?xn|uZAJwvmX?Yvp#lE3sQFY)xqet>`S2Y@1t)Z*& z;*I3;Ha8DFhk=YBt~{zp=%%*fEC}_8?9=(-k7HfFeN^GrhNw4e?vx*#oMztnO*&zY zmRT9dGI@O)t^=Wj&Og1R3b%(m*kb&yc;i`^-tqY9(0t!eyOkH<$@~1lXmm!SJllE_ zr~{a&w|8*LI>Z^h!m%YLgKv06Js7j7RaoX}ZJGYirR<#4Mghd{#;38j3|V+&=ZUq#1$ zgZb-7kV)WJUko?{R`hpSrC;w2{qa`(Z4gM5*ZL`|#8szO=PV^vpSI-^K_*OQji^J2 zZ_1142N}zG$1E0fI%uqHOhV+7%Tp{9$bAR=kRRs4{0a`r%o%$;vu!_Xgv;go)3!B#;hC5qD-bcUrKR&Sc%Zb1Y($r78T z=eG`X#IpBzmXm(o6NVmZdCQf6wzqawqI63v@e%3TKuF!cQ#NQbZ^?6K-3`_b=?ztW zA>^?F#dvVH=H-r3;;5%6hTN_KVZ=ps4^YtRk>P1i>uLZ)Ii2G7V5vy;OJ0}0!g>j^ z&TY&E2!|BDIf1}U(+4G5L~X6sQ_e7In0qJmWYpn!5j|2V{1zhjZt9cdKm!we6|Pp$ z07E+C8=tOwF<<}11VgVMzV8tCg+cD_z?u+$sBjwPXl^(Ge7y8-=c=fgNg@FxI1i5Y-HYQMEH z_($je;nw`Otdhd1G{Vn*w*u@j8&T=xnL;X?H6;{=WaFY+NJfB2(xN`G)LW?4u39;x z6?eSh3Wc@LR&yA2tJj;0{+h6rxF zKyHo}N}@004HA(adG~0solJ(7>?LoXKoH0~bm+xItnZ;3)VJt!?ue|~2C=ylHbPP7 zv2{DH()FXXS_ho-sbto)gk|2V#;BThoE}b1EkNYGT8U#0ItdHG>vOZx8JYN*5jUh5Fdr9#12^ zsEyffqFEQD(u&76zA^9Jklbiz#S|o1EET$ujLJAVDYF znX&4%;vPm-rT<8fDutDIPC@L=zskw49`G%}q#l$1G3atT(w70lgCyfYkg7-=+r7$%E`G?1NjiH)MvnKMWo-ivPSQHbk&_l5tedNp|3NbU^wk0SSXF9ohtM zUqXiOg*8ERKx{wO%BimK)=g^?w=pxB1Vu_x<9jKOcU7N;(!o3~UxyO+*ZCw|jy2}V*Z22~KhmvxoTszc+#EMWXTM6QF*ks% zW47#2B~?wS)6>_ciKe1Fu!@Tc6oN7e+6nriSU;qT7}f@DJiDF@P2jXUv|o|Wh1QPf zLG31d>@CpThA+Ex#y)ny8wkC4x-ELYCXGm1rFI=1C4`I5qboYgDf322B_Nk@#eMZ% znluCKW2GZ{r9HR@VY`>sNgy~s+D_GkqFyz6jgXKD)U|*eKBkJRRIz{gm3tUd*yXmR z(O4&#ZA*us6!^O*TzpKAZ#}B5@}?f=vdnqnRmG}xyt=)2o%<9jj>-4wLP1X-bI{(n zD9#|rN#J;G%LJ&$+Gl2eTRPx6BQC6Uc~YK?nMmktvy^E8#Y*6ZJVZ>Y(cgsVnd!tV z!%twMNznd)?}YCWyy1-#P|2Fu%~}hcTGoy>_uawRTVl=(xo5!%F#A38L109wyh@wm zdy+S8E_&$Gjm=7va-b7@Hv=*sNo0{i8B7=n4ex-mfg`$!n#)v@xxyQCr3m&O1Jxg! z+FXX^jtlw=utuQ+>Yj$`9!E<5-c!|FX(~q`mvt6i*K!L(MHaqZBTtuSA9V~V9Q$G? zC8wAV|#XY=;TQD#H;;dcHVb9I7Vu2nI0hHo)!_{qIa@|2}9d ztpC*Q{4Py~2;~6URN^4FBCBip`QDf|O_Y%iZyA0R`^MQf$ce0JuaV(_=YA`knEMXw zP6TbjYSGXi#B4eX=QiWqb3bEw-N*a;Yg?dsVPpeYFS*&AsqtW1j2D$h$*ZOdEb$8n0 zGET4Igs^cMTXWG{2#A7w_usx=KMmNfi4oAk8!MA8Y=Rh9^*r>jEV(-{I0=rc);`Y) zm+6KHz-;MIy|@2todN&F+Yv1e&b&ZvycbTHpDoZ>FIiUn+M-=%A2C(I*^Yx@VKf(Z zxJOny&WoWcyKodkeN^5))aV|-UBFw{?AGo?;NNFFcKzk+6|gYfA#FR=y@?;3IoQ zUMI=7lwo9gV9fRvYi}Nd)&gQw7(K3=a0#p27u6Q)7JlP#A)piUUF8B3Li&38Xk$@| z9OR+tU~qgd3T3322E))eV)hAAHYIj$TmhH#R+C-&E-}5Qd{3B}gD{MXnsrS;{Erv1 z6IyQ=S2qD>Weqqj#Pd65rDSdK54%boN+a?=CkR|agnIP6;INm0A*4gF;G4PlA^3%b zN{H%#wYu|!3fl*UL1~f+Iu|;cqDax?DBkZWSUQodSDL4Es@u6zA>sIm>^Aq-&X#X8 zI=#-ucD|iAodfOIY4AaBL$cFO@s(xJ#&_@ZbtU+jjSAW^g;_w`FK%aH_hAY=!MTjI zwh_OEJ_25zTQv$#9&u0A11x_cGd92E74AbOrD`~f6Ir9ENNQAV2_J2Ig~mHWhaO5a zc>fYG$zke^S+fBupw+klDkiljJAha z6DnTemhkf>hv`8J*W_#wBj-2w(cVtXbkWWtE(3j@!A-IfF?`r$MhVknTs3D1N`rYN zKth9jZtX#>v#%U@^DVN!;ni#n1)U&H_uB{6pcq7$TqXJX!Q0P7U*JUZyclb~)l*DS zOLpoQfW_3;a0S$#V0SOwVeeqE$Hd^L`$;l_~2giLYd?7!gUYIpOs!jqSL~pI)4`YuB_692~A z^T#YYQ_W3Rakk}$SL&{`H8mc{>j+3eKprw6BK`$vSSIn;s31M~YlJLApJ)+Gi1{^- zw96WnT9M0Vr_D=e=a}${raR{(35Q!g+8`}vOFj1e&Or(_wp2U2aVQP0_jP57 z2(R4E(E$n!xl<}Zx38wO;27wuQ`P#_j!}L2 z2qr;As4D4n2X$-Jd_-!fsbu_D(64i;c4cJnP576x_>Q4WNushFwkBV!kVd(AYFXe{ zaqO5`Qfr!#ETmE(B;u_&FITotv~W}QYFCI!&ENKIb1p4fg*Yv1)EDMb==EjHHWM#{ zGMpqb2-LXdHB@D~pE3|+B392Gh4q)y9jBd$a^&cJM60VEUnLtHQD5i-X6PVF>9m_k zDvG3P(?CzdaIrC8s4cu~N9MEb!Tt(g*GK~gIp1Gyeaw3b7#YPx_1T6i zRi#pAMr~PJKe9P~I+ARa$a!K~)t(4LaVbjva1yd;b1Yz2$7MMc`aLmMl(a^DgN(u? zq2o9&Gif@Tq~Yq+qDfx^F*nCnpuPv%hRFc$I!p74*quLt^M}D_rwl10uMTr!)(*=7 zSC5ea@#;l(h87k4T4x)(o^#l76P-GYJA(pOa&F9YT=fS<*O{4agzba^dIrh0hjls<~APlIz9{ zgRY{OMv2s|`;VCoYVj?InYoq^QWuA&*VDyOn@pPvK8l~g#1~~MGVVvtLDt}>id_Z` zn(ihfL?Y}Y4YX335m*Xx(y+bbukchHrM zycIGp#1*K3$!(tgTsMD2VyUSg^yvCwB8*V~sACE(yq2!MS6f+gsxv^GR|Q7R_euYx z&X+@@H?_oQddGxJYS&ZG-9O(X+l{wcw;W7srpYjZZvanY(>Q1utSiyuuonkjh5J0q zGz6`&meSuxixIPt{UoHVupUbFKIA+3V5(?ijn}(C(v>=v?L*lJF8|yRjl-m#^|krg zLVbFV6+VkoEGNz6he;EkP!Z6|a@n8?yCzX9>FEzLnp21JpU0x!Qee}lwVKA})LZJq zlI|C??|;gZ8#fC3`gzDU%7R87KZyd)H__0c^T^$zo@TBKTP*i{)Gp3E0TZ}s3mKSY zix@atp^j#QnSc5K&LsU38#{lUdwj%xF zcx&l^?95uq9on1m*0gp$ruu||5MQo)XaN>|ngV5Jb#^wWH^5AdYcn_1>H~XtNwJd3 zd9&?orMSSuj=lhO?6)Ay7;gdU#E}pTBa5wFu`nejq##Xd71BHzH2XqLA5 zeLEo;9$}~u0pEu@(?hXB_l;{jQ=7m?~mwj-ME~Tw-OHPrR7K2Xq9eCNwQO$hR z3_A?=`FJctNXA#yQEorVoh{RWxJbdQga zU%K##XEPgy?E|K(=o#IPgnbk7E&5%J=VHube|2%!Qp}@LznjE%VQhJ?L(XJOmFVY~ zo-az+^5!Ck7Lo<7b~XC6JFk>17*_dY;=z!<0eSdFD2L?CSp_XB+?;N+(5;@=_Ss3& zXse>@sA7hpq;IAeIp3hTe9^$DVYf&?)={zc9*hZAV)|UgKoD!1w{UVo8D)Htwi8*P z%#NAn+8sd@b{h=O)dy9EGKbpyDtl@NBZw0}+Wd=@65JyQ2QgU}q2ii;ot1OsAj zUI&+Pz+NvuRv#8ugesT<<@l4L$zso0AQMh{we$tkeG*mpLmOTiy8|dNYhsqhp+q*yfZA`Z)UC*(oxTNPfOFk3RXkbzAEPofVUy zZ3A%mO?WyTRh@WdXz+zD!ogo}gbUMV!YtTNhr zrt@3PcP%5F;_SQ>Ui`Gq-lUe&taU4*h2)6RDh@8G1$o!){k~3)DT87%tQeHYdO?B` zAmoJvG6wWS?=0(Cj?Aqj59`p(SIEvYyPGJ^reI z`Hr?3#U2zI7k0=UmqMD35l`>3xMcWlDv$oo6;b`dZq3d!~)W z=4Qk)lE8&>#HV>?kRLOHZYz83{u7?^KoXmM^pazj8`7OwQ=5I!==; zA!uN`Q#n=Drmzg}@^nG!mJp9ml3ukWk96^6*us*;&>s+7hWfLXtl?a}(|-#=P12>A zon1}yqh^?9!;on?tRd6Fk0knQSLl4vBGb87A_kJNDGyrnpmn48lz_%P{* z_G*3D#IR<2SS54L5^h*%=)4D9NPpji7DZ5&lHD|99W86QN_(|aJ<5C~PX%YB`Qt_W z>jF_Os@kI6R!ub4n-!orS(G6~mKL7()1g=Lf~{D!LR7#wRHfLxTjYr{*c{neyhz#U zbm@WBKozE+kTd+h-mgF+ELWqTKin57P;0b){ zii5=(B%S(N!Z=rAFGnM6iePtvpxB_Q9-oq_xH!URn2_d-H~i;lro8r{-g!k-Ydb6_w5K@FOV?zPF_hi z%rlxBv$lQi%bjsu^7KT~@u#*c$2-;AkuP)hVEN?W5MO8C9snj*EC&|M!aK6o12q3+ z8e?+dH17E!A$tRlbJW~GtMDkMPT=m1g-v67q{sznnWOI$`g(8E!Pf!#KpO?FETxLK z2b^8^@mE#AR1z(DT~R3!nnvq}LG2zDGoE1URR=A2SA z%lN$#V@#E&ip_KZL}Q6mvm(dsS?oHoRf8TWL~1)4^5<3JvvVbEsQqSa3(lF*_mA$g zv`LWarC79G)zR0J+#=6kB`SgjQZ2460W zN%lZt%M@=EN>Wz4I;eH>C0VnDyFe)DBS_2{h6=0ZJ*w%s)QFxLq+%L%e~UQ0mM9ud zm&|r){_<*Om%vlT(K9>dE(3AHjSYro5Y1I?ZjMqWyHzuCE0nyCn`6eq%MEt(aY=M2rIzHeMds)4^Aub^iTIT|%*izG4YH;sT`D9MR(eND-SB+e66LZT z2VX)RJsn${O{D48aUBl|(>ocol$1@glsxisc#GE*=DXHXA?|hJT#{;X{i$XibrA}X zFHJa+ssa2$F_UC(o2k2Z0vwx%Wb(<6_bdDO#=a$0gK2NoscCr;vyx?#cF)JjM%;a| z$^GIlIzvz%Hx3WVU481}_e4~aWcyC|j&BZ@uWW1`bH1y9EWXOxd~f-VE5DpueNofN zv7vZeV<*!A^|36hUE;`#x%MHhL(~?eZ5fhA9Ql3KHTWoAeO-^7&|2)$IcD1r5X#-u zN~N0$6pHPhop@t1_d`dO3#TC0>y5jm>8;$F5_A2& zt#=^IDfYv?JjPPTPNx2TL-Lrl82VClQSLWW_$3=XPbH}xM34)cyW5@lnxy=&h%eRq zv29&h^fMoxjsDnmua(>~OnX{Cq!7vM0M4Mr@_18|YuSKPBKUTV$s^So zc}JlAW&bVz|JY#Eyup6Ny{|P_s0Pq;5*tinH+>5Xa--{ z2;?2PBs((S4{g=G`S?B3Ien`o#5DmUVwzpGuABthYG~OKIY`2ms;33SN9u^I8i_H5`BQ%yOfW+N3r|ufHS_;U;TWT5z;b14n1gX%Pn`uuO z6#>Vl)L0*8yl|#mICWQUtgzeFp9$puHl~m&O+vj3Ox#SxQUa?fY*uK?A;00RiFg(G zK?g=7b5~U4QIK`C*um%=Sw=OJ1eeaV@WZ%hh-3<=lR#(Xesk%?)l4p(EpTwPvN99V@TT)!A8SeFTV+frN=r|5l?K#odjijx2nFgc3kI zC$hVs1S-!z9>xn9MZcRk0YXdYlf~8*LfH$IHKD59H&gLz%6 z#mAYSRJufbRi~LRadwM*G!O2>&U<^d`@<)otXZJJxT@G}4kTx0zPDVhVXwiU)$}5Y z`0iV`8EEh&GlUk&VY9m0Mqr*U&|^Bc?FB`<%{x-o0ATntwIA%(YDcxWs$C)%a%d_@ z?fx!Co+@3p7ha$|pWYD}p6#(PG%_h8K7sQjT_P~|3ZEH0DRxa3~bP&&lPMj3C~!H2QD zq>(f^RUFSqf6K3BMBFy$jiuoSE+DhEq$xLDb7{57 z0B|1pSjYJ5F@cHG%qDZ{ogL$P!BK&sR%zD`gbK#9gRZX17EtAJxN% zys^gb2=X9=7HP}N(iRqt(tot2yyeE%s;L}AcMh;~-W~s_eAe!gIUYdQz5j~T)0trh z>#1U$uOyyl%!Pi(gD&)uHe9Q^27_kHyFCC}n^-KL(=OxHqUfex1YS__RJh0m-S>eM zqAk`aSev*z1lI&-?CycgDm=bdQCp}RqS0_d-4Mf&>u2KyGFxKe8JM1N{GNWw0n$FL z1UDp(h0(1I2Jh9I`?IS}h4R~n zRwRz>8?$fFMB2{UPe^$Ifl;Oc>}@Q9`|8DCeR{?LUQLPfaMsxs8ps=D_aAXORZH~< zdcIOca-F;+D3~M+)Vi4h)I4O3<)$65yI)goQ_vk#fb;Uim>UI4Dv9#2b1;N_Wg>-F zNwKeMKY+su#~NL0uE%_$mw1%ddX2Qs2P!ncM+>wnz}OCQX1!q~oS?OqYU;&ESAAwP z452QWL0&u^mraF#=j_ZeBWhm&F|d!QjwRl^7=Bl7@(43=BkN=3{BRv#QHIk>Umc_w zvP>q|q{lJ=zs|W9%a@8%W>C@MYN1D5{(=Af31+pR#kB`cd0-YlQQTg}+ zL|_h=F9JQ|Gux5c0ehaffHNYLf8VwF+qnM6IjBEI_eceee;o;FY@#~FFVsZjBSp!j z8V*Bgmn{RK!!zqGc;jy)z@Zjo>5{%m1?K}fLEL$l6Dl4f=ye0wNI#)2L=^K(&18Gb zJoj8@WBB;P^T#V)I0`aDSy?$rJU{+-5472NyFp>;Vw43j@3Z=;D2eSfyw5*0Q+&ML zsV&&*3c3$pa`qcaGbEB0*CA~Wp3%PkF?B87FV&rWNb|@GU$LB;l|;YutU*k za1hjUL_BX%G^s;BuzRi4Hl?eqC2z&ZrKh1tZDwnufG$g$LX(j!h%F5(n8D@in3lnX z(*8+3ZT6TVYRcSpM1eMeCps=Fz8q%gyM&B=a7(Vf`4k3dN$IM+`BO^_7HZq4BR|7w z+5kOJ;9_$X%-~arA@qmXSzD|+NMh--%5-9u6t(M=f%&z$<_V#Y_lzn{E$MZZG)+A> zu2E`_Y(MBJ2l*AqvCUmU;yBT}#oQ{V=((mC-QGJwsCOH*a;{1JRTKv7DBNG+M!XL7(^jbv&Qy-o9HNFrmN)-`D3WFtXs>1vBOJpI(=x; zKhJlFdfMf^G#oU(w1+ucMKYPZaDp>$kt=wiYsBCjUY-uz<4JziB>6fXDSLH*2Y z&Px5y`#3!fF=c4>fCMdg-tX582pemU@ZxyFbznL8-=TTo1Sybg9>7h*J^9^~XxXJO z`k9v~=4amxl<;FCV9h2k%?^-ZUzQy^#{JleyH23o1S{r<+t#z6jKS<9rbAM96^1iY zi6{IjauB)UwBhC-_L(MzGCxhhv`?ryc zja_Uwi7$8l!}*vjJppGyp#Wz=*?;jC*xQ&J894rql5A$2giJRtV&DWQh#(+Vs3-5_ z69_tj(>8%z1VtVp>a74r5}j2rG%&;uaTQ|fr&r%ew-HO}76i8`&ki%#)~}q4Y|d$_ zfNp9uc#$#OEca>>MaY6rF`dB|5#S)bghf>>TmmE&S~IFw;PF0UztO6+R-0!TSC?QP z{b(RA_;q3QAPW^XN?qQqu{h<}Vfiv}Rr!lA$C79^1=U>+ng9Dh>v{`?AOZt>CrQ=o zI}=mSnR))8fJpO->rcX?H);oqSQUZ?sR!fH2SoFdcPm5*2y<_u;4h;BqcF*XbwWSv zcJN%!g|L(22Xp!^1?c;T&qm%rpkP&2EQC3JF+SENm$+@7#e!UKD1uQ{TDw43?!b!3 zUooS_rt=xJfa&h?c^hfV>YwQXre3qosz_^c#)FO~d!<)2o}Oxz5HWtr<)1Yw012v4 zhv0w(RfJspDnA^-6Jmr;GkWt%{mAYOm6yPb&Vl&rv@D^K&;#?=X{kaK5FhScNJ_3> z#5u(Saisq2(~pVlrfG#@kLM#Ot~5rZZc%B&h1=gen?R+#t^1bYKf zVvtefX=D$*)39e^2@!~A_}9c${Gf0?1;dk=!Itp#s%0>Io%k`9(bDeI-udd&E6Zfu zcaiv(h`DM3W3Mfda)fYwhB=8RAPkotVt5-z21Ij~Ot9A^SK-1u*zFVK&mF?q1;|wy zrF+XWs^5Q-%Z6I62gTwrRe#F>riVM#fv_TihxSJ6to1X7NVszgivoTa!fPfBBYj94 zuc2m zL_k-<1FoORng1aL{Zx(P7JmUiH zlmTHdzkn75=mS{V=o$V;gzhEaunoJzJ3uq>0_w~77eID^U*w+v0po_N8=sS-DL~!V z%-~rL<0V7PCEWPCpNgpfsein`Fr)+8=N}mUn2x=K`z%efnhSs#23&N1fjdO`M>s%z zP3(;v93%lLq>ZfqBi#QI-aCXAP8-may8x5s`G)KA;{HSYe2szWINWf^b*fc{jl0KecD zRTle?)%_YzJJcVb>;VJ>P?3Lu2S)vCJZlF>Jxj~~X2U5-NNNy(H?8%XD~yFUxNKs&hwWx^)iF@ zGmEv<|7Q7hGrY_+`iz+d_=^9c(_c}UCzq2#%A0|5WjzCXjZUOxOX zU&-^smw$iwKPe;r`&{rP{L35^&+wk6f2-Sn;D2Ww@sjAJj{Gwbp4H!o{#5_}qALFq z{-q%LGklZvKf%A4D!+t%sRRBDi(>mvuz&V4yu^GdD*KFy?fg%ef5ZU%w=d&M`POGt zNSEJ0{qJI~FRTAjlJc1-+x>Tm{%D?m3sk-&cq#w)OpxI98wCF#2KbWcrAXK_(}M4B zF#VQf*h|irx=+uXZUMi+`A;fPFR5M%Wjs^Wh5rWCKgedhWO^w|@XS;b^&3oom;>K0 zB??|ry^IBarYem6Z7RU`#rDs-ZZAn*hSollv?csD$sh0QpTtI9vb>Dpd}e7*`fZj! zM|8d{~YM@vfW-r0z8vJ z<^6B6Ur(}L?ms_c9@hO0^Iy&J_uc51^?d33e#Y!-``?)VG)BGjCq5$&0G8A*r!2qk zUHscGc;VxE=1KqbH=dW%&Ogl({>L!>((m$2W8M9KQ@a1=h51jN|KoG{v(x0K&*iy% e1c3cF4~(n?C}6GmGu)3JNC)6=LGAhZ*Z%`+-T+_# diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ea13fdfd19..9fe9d37d43 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.3.1-bin.zip +distributionSha256Sum=e58cdff0cee6d9b422dcd08ebeb3177bc44eaa09bd9a2e838ff74c408fe1cbcd +distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index cccdd3d517..b0d6d0ab5d 100755 --- a/gradlew +++ b/gradlew @@ -1,5 +1,21 @@ #!/usr/bin/env sh +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + ############################################################################## ## ## Gradle start up script for UN*X @@ -28,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" diff --git a/gradlew.bat b/gradlew.bat index f9553162f1..9991c50326 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome diff --git a/settings.gradle.kts b/settings.gradle.kts index fdd9f374fb..be0e981f7f 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -34,6 +34,18 @@ rootProject.children.forEach { project -> } } +plugins { + id("com.gradle.enterprise").version("3.3.4") +} + +//Posting Build scans to https://scans.gradle.com +gradleEnterprise { + buildScan { + termsOfServiceUrl = "https://gradle.com/terms-of-service" + termsOfServiceAgree = "yes" + } +} + buildCache { local { isEnabled = !System.getenv().containsKey("CI") diff --git a/subprojects/kotlinReleaseCoroutinesTest/kotlinReleaseCoroutinesTest.gradle b/subprojects/kotlinReleaseCoroutinesTest/kotlinReleaseCoroutinesTest.gradle index 0812f26b35..d3c809ff5e 100644 --- a/subprojects/kotlinReleaseCoroutinesTest/kotlinReleaseCoroutinesTest.gradle +++ b/subprojects/kotlinReleaseCoroutinesTest/kotlinReleaseCoroutinesTest.gradle @@ -4,7 +4,7 @@ buildscript { maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' } } dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${libraries.kotlin.version_1_3}" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${libraries.kotlin.version}" } } @@ -21,6 +21,6 @@ dependencies { testCompile project(":") testCompile libraries.junit4 - testCompile libraries.kotlin.stdlib_1_3 - testCompile libraries.kotlin.releaseCoroutines + testCompile libraries.kotlin.stdlib + testCompile libraries.kotlin.coroutines } diff --git a/subprojects/kotlinTest/kotlinTest.gradle b/subprojects/kotlinTest/kotlinTest.gradle index 38eb74b166..9e40101a52 100644 --- a/subprojects/kotlinTest/kotlinTest.gradle +++ b/subprojects/kotlinTest/kotlinTest.gradle @@ -1,17 +1,11 @@ plugins { // Can not use libraries.kotlin.version here per https://stackoverflow.com/questions/37555196/in-gradle-how-to-use-a-variable-for-a-plugin-version - id 'org.jetbrains.kotlin.jvm' version '1.2.31' + id 'org.jetbrains.kotlin.jvm' version '1.3.72' id 'java' } description = "Kotlin tests for Mockito." -kotlin { - experimental { - coroutines "enable" - } -} - apply from: "$rootDir/gradle/dependencies.gradle" dependencies { diff --git a/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt b/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt index bfef4071e4..85131ac6f8 100644 --- a/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt +++ b/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt @@ -4,7 +4,7 @@ */ package org.mockito.kotlin -import kotlinx.coroutines.experimental.runBlocking +import kotlinx.coroutines.runBlocking import org.hamcrest.core.IsEqual import org.junit.Assert.assertThat import org.junit.Test From 9e16fee71665fc155ed1db1cb73bdb2ea1ed4b84 Mon Sep 17 00:00:00 2001 From: Erhard Pointl Date: Wed, 17 Jun 2020 22:06:29 +0200 Subject: [PATCH 035/963] Update jacoco to 0.8.5 for Java 14 support (#1950) --- gradle/root/coverage.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/root/coverage.gradle b/gradle/root/coverage.gradle index 5e973c0db8..a161b87f19 100644 --- a/gradle/root/coverage.gradle +++ b/gradle/root/coverage.gradle @@ -19,7 +19,7 @@ task mockitoCoverage(type: JacocoReport) { apply plugin: "jacoco" jacoco { - toolVersion = '0.8.2' + toolVersion = '0.8.5' if (currentProject != rootProject) { //already automatically enhanced in mockito main project as "java" plugin was applied before applyTo test From e5a9da5f999c56dbfa0d76758b96638eb9bc1915 Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Wed, 17 Jun 2020 21:42:22 +0100 Subject: [PATCH 036/963] Move spotless check to separate build task (#1946) This means the tests can run in parallel of the formatting changes. Therefore, formatting changes would not block obtaining your test results, which should hopefully reduce the amount of Travis builds necessary to work on a community PR. This is also in preparation of #1934 which requires spotless to run on JDK11 minimum. --- .travis.yml | 10 +++++++++- settings.gradle.kts | 8 ++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3ba1dbfa39..394e3e1ed7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,8 +34,16 @@ matrix: env: SKIP_RELEASE=true - jdk: openjdk11 env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline + # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) + - jdk: openjdk11 + name: "Verify code formatting with Spotless" + script: ./gradlew spotlessCheck + # Do not upload a coverage report, as we don't run the tests for this job + after_success: true - jdk: openjdk8 + name: "Check reproducibility of jars" script: ./check_reproducibility.sh + # Do not upload a coverage report, as we don't run the tests for this job after_success: true branches: @@ -53,7 +61,7 @@ script: # We are using && below on purpose # ciPerformRelease must run only when the entire build has completed # This guarantees that no release steps are executed when the build or tests fail - - ./gradlew spotlessCheck && ./gradlew build idea -s && ./gradlew ciPerformRelease + - ./gradlew build idea -s && ./gradlew ciPerformRelease after_success: #Generates coverage report: diff --git a/settings.gradle.kts b/settings.gradle.kts index be0e981f7f..5ece24a4b3 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,3 +1,7 @@ +plugins { + id("com.gradle.enterprise").version("3.3.4") +} + include("deprecatedPluginsTest", "inline", "extTest", @@ -34,10 +38,6 @@ rootProject.children.forEach { project -> } } -plugins { - id("com.gradle.enterprise").version("3.3.4") -} - //Posting Build scans to https://scans.gradle.com gradleEnterprise { buildScan { From 6f6766cd536e94a825f4cc15b9ee4e5605889481 Mon Sep 17 00:00:00 2001 From: Erhard Pointl Date: Wed, 17 Jun 2020 23:00:13 +0200 Subject: [PATCH 037/963] Update errorprone to 2.4.0 for Java 14 support (#1951) --- gradle/dependencies.gradle | 2 +- gradle/errorprone.gradle | 4 ---- src/test/java/org/mockito/internal/matchers/EqualityTest.java | 1 + .../mockito/internal/util/collections/IdentitySetTest.java | 1 + .../internal/util/reflection/GenericMetadataSupportTest.java | 1 + src/test/java/org/mockitousage/matchers/MatchersTest.java | 1 + 6 files changed, 5 insertions(+), 5 deletions(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 8fc97e4c92..d165c85a20 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -6,7 +6,7 @@ def versions = [:] versions.bytebuddy = '1.10.10' versions.junitJupiter = '5.4.2' -versions.errorprone = '2.3.2' +versions.errorprone = '2.4.0' libraries.junit4 = 'junit:junit:4.12' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" diff --git a/gradle/errorprone.gradle b/gradle/errorprone.gradle index 43c8633fcd..1d9cf7428e 100644 --- a/gradle/errorprone.gradle +++ b/gradle/errorprone.gradle @@ -10,7 +10,3 @@ if (JavaVersion.current() == JavaVersion.VERSION_1_8) { dependencies { errorprone libraries.errorprone } - -tasks.named("compileTestJava").configure { - options.errorprone.errorproneArgs << "-Xep:MockitoCast:OFF" -} diff --git a/src/test/java/org/mockito/internal/matchers/EqualityTest.java b/src/test/java/org/mockito/internal/matchers/EqualityTest.java index 6f0f71be20..5002701d2f 100644 --- a/src/test/java/org/mockito/internal/matchers/EqualityTest.java +++ b/src/test/java/org/mockito/internal/matchers/EqualityTest.java @@ -31,6 +31,7 @@ public void shouldKnowIfObjectsAreEqual() throws Exception { assertFalse(areEqual(new int[] {1}, new double[] {1.0})); } + @SuppressWarnings("EqualsHashCode") private final class BadEquals { @Override public boolean equals(Object oth) { 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 462a6fc4d5..5c44ee9846 100644 --- a/src/test/java/org/mockito/internal/util/collections/IdentitySetTest.java +++ b/src/test/java/org/mockito/internal/util/collections/IdentitySetTest.java @@ -24,6 +24,7 @@ public void shouldWork() throws Exception { assertFalse(set.contains(new Object())); } + @SuppressWarnings("EqualsHashCode") class Fake { @Override public boolean equals(Object obj) { 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 c7985fd713..15574acf46 100644 --- a/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java @@ -272,6 +272,7 @@ public void can_extract_interface_type_from_bounds_on_terminal_typeVariable() { ).isEmpty(); } + @SuppressWarnings("EqualsHashCode") private ParameterizedType parameterizedTypeOf(final Class rawType, final Class ownerType, final Type... actualTypeArguments) { return new ParameterizedType() { @Override diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java index 25f49da5d5..71cc1ff621 100644 --- a/src/test/java/org/mockitousage/matchers/MatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java @@ -340,6 +340,7 @@ public void should_use_smart_equals_for_primitive_arrays() throws Exception { verify(mock).objectArgMethod(new int[]{1, 2}); } + @SuppressWarnings("ReturnValueIgnored") @Test(expected = ArgumentsAreDifferent.class) public void array_equals_should_throw_ArgumentsAreDifferentException_for_non_matching_arguments() { List list = Mockito.mock(List.class); From 9873ab30c2d6ecfbaa5b5c85d4efb045c66c414a Mon Sep 17 00:00:00 2001 From: Erhard Pointl Date: Wed, 17 Jun 2020 23:16:19 +0200 Subject: [PATCH 038/963] Update bnd gradle plugin to v5.1.1 for Java 14 support (#1952) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index d165c85a20..bda27edc28 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -32,7 +32,7 @@ libraries.asm = 'org.ow2.asm:asm:7.0' libraries.osgi = 'org.osgi:osgi.core:7.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.15.0' -libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:4.3.1' +libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.1.1' def kotlinVersion = '1.3.72' libraries.kotlin = [ From ddba09264c945b942142793dbf94d8befd73629a Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Wed, 17 Jun 2020 22:48:54 +0100 Subject: [PATCH 039/963] [Travis] Replace JDK 9/10 with 14 (#1945) 9/10 are EOL since September 2018. 14 is the currently supported Java version. --- .travis.yml | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index 394e3e1ed7..5a83c8afc2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,20 +20,14 @@ matrix: - jdk: openjdk8 - jdk: openjdk8 env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk9 - env: SKIP_RELEASE=true - - jdk: openjdk9 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk9 - env: SKIP_RELEASE=true SIMULATE_JAVA11=true - - jdk: openjdk10 - env: SKIP_RELEASE=true - - jdk: openjdk10 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - jdk: openjdk11 env: SKIP_RELEASE=true - jdk: openjdk11 env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline + - jdk: openjdk14 + env: SKIP_RELEASE=true + - jdk: openjdk14 + env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) - jdk: openjdk11 name: "Verify code formatting with Spotless" From a0dd0b9968f9a6c7b105dea4c296be1c7095f232 Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Thu, 18 Jun 2020 11:47:49 +0100 Subject: [PATCH 040/963] Use google-java-format in spotless (#1934) Google-java-format is an open source formatter [1]. It automatically formats source code based on the Google Java Style. The Mockito source code to a very large extent already adheres to this style guide. While this PR in itself is large, many of the changes are related to string formatting and nested method calls. Most notably, google-java-format is an improvement over the current formatting strategy in that: 1. It handles comment formatting (e.g. spacing between comments) 2. It handles nested method calls. You can see the difference in our usage of the ByteBuddy API, which is now more consistent 3. It enforces the max-line length. It essentially automates all of the styling rules we list in https://github.com/mockito/mockito/blob/release/3.x/.github/CONTRIBUTING.md#alignment As such, for new contributors it should be a lot easier (and less scary) to contribute to Mockito, as they no longer have to be concerned about formatting. Hopefully, this once again lowers the bar for external contributors who want to help the project, but would otherwise feel overwhelmed by the rules we have to adhere to. (If we wouldn't have these rules, it would be a lot harder for us to maintain a consistent and maintainable codebase). The only interesting changes in this PR are those in `build.gradle`. All other changes were auto-generated by running `./gradlew spotlessApply`. Note that I disabled the formatting of Javadoc, as I think we should keep formatting that ourselves. We normally put a lot of time and effort in our Javadoc and changing that all at once seems like the wrong decision at this point in time. [1]: https://github.com/google/google-java-format --- build.gradle | 20 +- src/main/java/org/mockito/Answers.java | 6 +- src/main/java/org/mockito/ArgumentCaptor.java | 3 +- .../java/org/mockito/ArgumentMatchers.java | 11 +- src/main/java/org/mockito/BDDMockito.java | 32 +- .../java/org/mockito/CheckReturnValue.java | 11 +- src/main/java/org/mockito/InOrder.java | 1 - src/main/java/org/mockito/Incubating.java | 3 +- src/main/java/org/mockito/Matchers.java | 3 +- src/main/java/org/mockito/Mockito.java | 34 +- .../java/org/mockito/MockitoAnnotations.java | 6 +- .../java/org/mockito/MockitoDebugger.java | 2 +- src/main/java/org/mockito/NotExtensible.java | 3 +- src/main/java/org/mockito/Spy.java | 2 +- .../configuration/AnnotationEngine.java | 5 +- .../DefaultMockitoConfiguration.java | 2 - .../creation/instance/Instantiator.java | 1 - .../exceptions/base/MockitoException.java | 1 - .../junit/ArgumentsAreDifferent.java | 1 - .../opentest4j/ArgumentsAreDifferent.java | 1 - .../org/mockito/hamcrest/MockitoHamcrest.java | 6 +- .../org/mockito/internal/InOrderImpl.java | 8 +- .../org/mockito/internal/MockitoCore.java | 25 +- .../CaptorAnnotationProcessor.java | 9 +- .../configuration/ClassPathLoader.java | 18 +- .../configuration/DefaultInjectionEngine.java | 4 +- .../configuration/GlobalConfiguration.java | 9 +- .../IndependentAnnotationEngine.java | 26 +- .../InjectingAnnotationEngine.java | 20 +- .../MockAnnotationProcessor.java | 6 +- .../configuration/SpyAnnotationEngine.java | 77 +- .../injection/ConstructorInjection.java | 14 +- .../injection/MockInjectionStrategy.java | 14 +- .../injection/PropertyAndSetterInjection.java | 63 +- .../injection/SpyOnInjectedFieldsHandler.java | 13 +- .../injection/filter/MockCandidateFilter.java | 3 +- .../filter/NameBasedCandidateFilter.java | 31 +- .../injection/filter/OngoingInjector.java | 11 +- .../filter/TerminalMockCandidateFilter.java | 17 +- .../filter/TypeBasedCandidateFilter.java | 12 +- .../injection/scanner/InjectMocksScanner.java | 7 +- .../injection/scanner/MockScanner.java | 3 +- .../plugins/DefaultMockitoPlugins.java | 54 +- .../plugins/PluginFileReader.java | 2 +- .../configuration/plugins/PluginFinder.java | 9 +- .../plugins/PluginInitializer.java | 5 +- .../configuration/plugins/PluginLoader.java | 36 +- .../configuration/plugins/PluginRegistry.java | 27 +- .../configuration/plugins/Plugins.java | 2 +- .../internal/creation/MockSettingsImpl.java | 25 +- .../internal/creation/SuspendMethod.java | 3 +- ...yCrossClassLoaderSerializationSupport.java | 98 +- .../bytebuddy/InlineByteBuddyMockMaker.java | 185 ++- .../bytebuddy/InlineBytecodeGenerator.java | 247 +-- .../creation/bytebuddy/MockFeatures.java | 15 +- .../creation/bytebuddy/MockMethodAdvice.java | 119 +- .../bytebuddy/MockMethodInterceptor.java | 69 +- .../creation/bytebuddy/ModuleHandler.java | 195 ++- .../bytebuddy/SubclassByteBuddyMockMaker.java | 112 +- .../bytebuddy/SubclassBytecodeGenerator.java | 158 +- .../bytebuddy/SubclassInjectionLoader.java | 51 +- .../creation/bytebuddy/SubclassLoader.java | 3 +- .../TypeCachingBytecodeGenerator.java | 41 +- .../inject/MockMethodDispatcher.java | 10 +- .../instance/ConstructorInstantiator.java | 63 +- .../instance/DefaultInstantiatorProvider.java | 5 +- .../creation/instance/Instantiator.java | 1 - .../instance/ObjenesisInstantiator.java | 10 +- .../creation/settings/CreationSettings.java | 16 +- .../creation/util/MockitoMethodProxy.java | 2 +- .../debugging/InvocationsPrinter.java | 17 +- .../mockito/internal/debugging/Localized.java | 1 - .../internal/debugging/LocationImpl.java | 5 +- .../internal/debugging/LoggingListener.java | 23 +- .../debugging/MockitoDebuggerImpl.java | 6 +- .../VerboseMockInvocationLogger.java | 26 +- .../internal/debugging/WarningsFinder.java | 9 +- .../debugging/WarningsPrinterImpl.java | 5 +- .../mockito/internal/exceptions/Reporter.java | 1385 +++++++++-------- .../VerificationAwareInvocation.java | 1 - .../stacktrace/DefaultStackTraceCleaner.java | 7 +- .../stacktrace/StackTraceFilter.java | 21 +- .../exceptions/util/ScenarioPrinter.java | 8 +- .../framework/DefaultMockitoSession.java | 44 +- .../hamcrest/HamcrestArgumentMatcher.java | 2 +- .../hamcrest/MatcherGenericTypeExtractor.java | 2 +- .../handler/InvocationNotifierHandler.java | 14 +- .../internal/handler/MockHandlerImpl.java | 43 +- .../NotifiedMethodInvocationReport.java | 12 +- .../internal/handler/NullResultGuardian.java | 6 +- .../invocation/ArgumentsProcessor.java | 17 +- .../invocation/DefaultInvocationFactory.java | 53 +- .../invocation/InterceptedInvocation.java | 33 +- .../internal/invocation/InvocationMarker.java | 5 +- .../invocation/InvocationMatcher.java | 23 +- .../invocation/InvocationsFinder.java | 44 +- .../MatcherApplicationStrategy.java | 25 +- .../internal/invocation/MatchersBinder.java | 4 +- .../internal/invocation/RealMethod.java | 14 +- .../invocation/SerializableMethod.java | 48 +- .../internal/invocation/TypeSafeMatching.java | 17 +- .../invocation/UnusedStubsFinder.java | 7 +- .../finder/AllInvocationsFinder.java | 6 +- .../finder/VerifiableInvocationsFinder.java | 2 +- .../invocation/mockref/MockWeakReference.java | 17 +- .../internal/junit/ArgMismatchFinder.java | 10 +- .../junit/DefaultStubbingLookupListener.java | 38 +- .../junit/DefaultTestFinishedEvent.java | 3 +- .../internal/junit/ExceptionFactory.java | 8 +- .../org/mockito/internal/junit/JUnitRule.java | 6 +- .../internal/junit/JUnitSessionStore.java | 89 +- .../junit/MismatchReportingTestListener.java | 13 +- .../junit/StrictStubsRunnerTestListener.java | 11 +- .../internal/junit/StubbingArgMismatches.java | 3 +- .../mockito/internal/junit/StubbingHint.java | 8 +- .../internal/junit/TestFinishedEvent.java | 1 - .../internal/junit/UniversalTestListener.java | 60 +- .../junit/UnnecessaryStubbingsReporter.java | 16 +- .../internal/junit/UnusedStubbingsFinder.java | 26 +- .../junit/VerificationCollectorImpl.java | 35 +- .../junit/util/JUnitFailureHacker.java | 28 +- .../listeners/StubbingLookupNotifier.java | 27 +- .../VerificationStartedNotifier.java | 48 +- .../org/mockito/internal/matchers/And.java | 4 +- .../internal/matchers/ArrayEquals.java | 2 +- .../internal/matchers/CapturesArguments.java | 2 - .../internal/matchers/CapturingMatcher.java | 3 +- .../mockito/internal/matchers/CompareTo.java | 5 +- .../mockito/internal/matchers/Contains.java | 1 - .../mockito/internal/matchers/Equality.java | 9 +- .../org/mockito/internal/matchers/Equals.java | 5 +- .../internal/matchers/EqualsWithDelta.java | 3 +- .../mockito/internal/matchers/InstanceOf.java | 7 +- .../org/mockito/internal/matchers/Not.java | 2 +- .../mockito/internal/matchers/NotNull.java | 3 +- .../org/mockito/internal/matchers/Null.java | 3 +- .../org/mockito/internal/matchers/Or.java | 4 +- .../internal/matchers/VarargMatcher.java | 3 +- .../matchers/apachecommons/EqualsBuilder.java | 51 +- .../matchers/text/MatcherToString.java | 6 +- .../matchers/text/MatchersPrinter.java | 3 +- .../internal/matchers/text/ValuePrinter.java | 47 +- .../progress/ArgumentMatcherStorage.java | 1 - .../progress/ArgumentMatcherStorageImpl.java | 4 +- .../progress/MockingProgressImpl.java | 46 +- .../progress/ThreadSafeMockingProgress.java | 18 +- .../internal/reporting/PrintSettings.java | 5 +- .../internal/reporting/SmartPrinter.java | 22 +- .../runners/DefaultInternalRunner.java | 103 +- .../internal/runners/InternalRunner.java | 1 - .../internal/runners/RunnerFactory.java | 74 +- .../internal/runners/StrictRunner.java | 13 +- .../internal/runners/util/RunnerProvider.java | 6 +- .../runners/util/TestMethodsFinder.java | 2 +- .../session/DefaultMockitoSessionBuilder.java | 16 +- .../internal/stubbing/BaseStubbing.java | 10 +- .../stubbing/ConsecutiveStubbing.java | 1 - .../stubbing/DefaultLenientStubber.java | 8 +- .../stubbing/InvocationContainerImpl.java | 25 +- .../stubbing/OngoingStubbingImpl.java | 4 +- .../internal/stubbing/StrictnessSelector.java | 3 +- .../stubbing/StubbedInvocationMatcher.java | 7 +- .../internal/stubbing/StubberImpl.java | 4 +- .../answers/AbstractThrowsException.java | 6 +- .../answers/AnswerFunctionalInterfaces.java | 95 +- .../stubbing/answers/ClonesArguments.java | 9 +- .../answers/DefaultAnswerValidator.java | 3 +- .../stubbing/answers/DoesNothing.java | 4 +- .../stubbing/answers/InvocationInfo.java | 14 +- .../internal/stubbing/answers/Returns.java | 8 +- .../stubbing/answers/ReturnsArgumentAt.java | 42 +- .../stubbing/answers/ReturnsElementsOf.java | 11 +- .../stubbing/answers/ThrowsException.java | 2 - .../defaultanswers/ForwardsInvocations.java | 17 +- .../RetrieveGenericsForDefaultAnswers.java | 17 +- .../defaultanswers/ReturnsDeepStubs.java | 70 +- .../defaultanswers/ReturnsEmptyValues.java | 20 +- .../stubbing/defaultanswers/ReturnsMocks.java | 24 +- .../ReturnsMoreEmptyValues.java | 2 +- .../defaultanswers/ReturnsSmartNulls.java | 26 +- .../defaultanswers/TriesToReturnSelf.java | 3 +- .../org/mockito/internal/util/Checks.java | 2 +- .../internal/util/DefaultMockingDetails.java | 14 +- .../mockito/internal/util/JavaEightUtil.java | 18 +- .../internal/util/MockCreationValidator.java | 3 +- .../mockito/internal/util/MockNameImpl.java | 4 +- .../org/mockito/internal/util/MockUtil.java | 21 +- .../internal/util/ObjectMethodsGuru.java | 11 +- .../org/mockito/internal/util/Platform.java | 79 +- .../org/mockito/internal/util/Primitives.java | 13 +- .../org/mockito/internal/util/StringUtil.java | 4 +- .../HashCodeAndEqualsMockWrapper.java | 17 +- .../collections/HashCodeAndEqualsSafeSet.java | 25 +- .../util/collections/IdentitySet.java | 2 +- .../internal/util/collections/Iterables.java | 5 +- .../internal/util/collections/ListUtil.java | 5 +- .../internal/util/collections/Sets.java | 5 +- .../util/concurrent/DetachedThreadLocal.java | 30 +- .../util/concurrent/WeakConcurrentMap.java | 3 +- .../util/concurrent/WeakConcurrentSet.java | 4 +- .../org/mockito/internal/util/io/IOUtil.java | 4 +- .../util/reflection/AccessibilityChanger.java | 2 +- .../util/reflection/BeanPropertySetter.java | 37 +- .../reflection/FieldInitializationReport.java | 5 +- .../util/reflection/FieldInitializer.java | 160 +- .../internal/util/reflection/FieldReader.java | 5 +- .../internal/util/reflection/FieldSetter.java | 27 +- .../internal/util/reflection/Fields.java | 9 +- .../util/reflection/GenericMaster.java | 3 +- .../reflection/GenericMetadataSupport.java | 118 +- .../util/reflection/GenericTypeExtractor.java | 13 +- .../util/reflection/InstanceField.java | 2 +- .../util/reflection/LenientCopyTool.java | 2 +- .../util/reflection/SuperTypesLastSorter.java | 17 +- .../internal/verification/AtLeast.java | 9 +- .../mockito/internal/verification/Calls.java | 12 +- .../DefaultRegisteredInvocations.java | 9 +- .../internal/verification/InOrderWrapper.java | 6 +- .../MockAwareVerificationMode.java | 5 +- .../internal/verification/NoInteractions.java | 1 - .../mockito/internal/verification/Only.java | 2 +- .../verification/RegisteredInvocations.java | 2 - .../mockito/internal/verification/Times.java | 3 +- .../verification/VerificationEventImpl.java | 4 +- .../verification/VerificationModeFactory.java | 4 +- .../VerificationOverTimeImpl.java | 21 +- .../verification/VerificationWrapper.java | 16 +- .../VerificationWrapperInOrderWrapper.java | 35 +- .../verification/api/InOrderContext.java | 1 - .../api/VerificationDataInOrder.java | 1 - .../api/VerificationDataInOrderImpl.java | 3 +- .../ArgumentMatchingTool.java | 5 +- .../AtLeastXNumberOfInvocationsChecker.java | 18 +- .../checkers/MissingInvocationChecker.java | 33 +- .../checkers/NumberOfInvocationsChecker.java | 45 +- .../invocation/DescribedInvocation.java | 1 - .../mockito/invocation/InvocationFactory.java | 14 +- .../org/mockito/junit/MockitoJUnitRunner.java | 6 +- .../org/mockito/junit/MockitoTestRule.java | 1 - .../mockito/listeners/MockitoListener.java | 3 +- .../org/mockito/plugins/InlineMockMaker.java | 1 - .../java/org/mockito/plugins/MockMaker.java | 13 +- .../java/org/mockito/quality/MockitoHint.java | 3 +- .../ConsoleSpammingMockitoJUnitRunner.java | 24 +- .../mockito/runners/MockitoJUnitRunner.java | 1 - .../runners/VerboseMockitoJUnitRunner.java | 31 +- .../mockito/session/MockitoSessionLogger.java | 1 - .../java/org/mockito/stubbing/Answer6.java | 3 +- .../org/mockito/stubbing/BaseStubber.java | 8 +- .../org/mockito/stubbing/OngoingStubbing.java | 14 +- .../org/mockito/stubbing/ValidableAnswer.java | 1 - .../org/mockito/stubbing/VoidAnswer5.java | 3 +- .../org/mockito/stubbing/VoidAnswer6.java | 3 +- .../java/org/mockito/verification/After.java | 3 +- .../org/mockito/verification/Timeout.java | 7 +- .../verification/VerificationAfterDelay.java | 2 - ...rifiesContinuouslyInteractingMockTest.java | 27 +- .../ThreadsRunAllTestsHalfManualTest.java | 150 +- .../ThreadsShareAMockTest.java | 15 +- ...ThreadsShareGenerouslyStubbedMockTest.java | 49 +- ...icationInOrderFromMultipleThreadsTest.java | 25 +- ...nnotationsAreCopiedFromMockedTypeTest.java | 40 +- .../java/org/mockito/ArgumentCaptorTest.java | 3 - .../org/mockito/InvocationFactoryTest.java | 64 +- src/test/java/org/mockito/MockitoTest.java | 23 +- .../mockito/StaticMockingExperimentTest.java | 248 ++- .../configuration/MockitoConfiguration.java | 12 +- .../base/MockitoAssertionErrorTest.java | 3 +- .../base/MockitoSerializationIssueTest.java | 18 +- .../exceptions/base/StackTraceBuilder.java | 2 +- .../mockito/exceptions/base/TraceBuilder.java | 4 +- .../stacktrace/StackTraceCleanerTest.java | 10 +- .../internal/AllInvocationsFinderTest.java | 25 +- .../org/mockito/internal/InOrderImplTest.java | 6 +- .../internal/InvalidStateDetectionTest.java | 11 +- .../configuration/ClassPathLoaderTest.java | 11 +- .../GlobalConfigurationTest.java | 47 +- .../InjectingAnnotationEngineTest.java | 17 +- .../configuration/MockInjectionTest.java | 23 +- .../injection/SimpleArgumentResolverTest.java | 23 +- .../plugins/DefaultMockitoPluginsTest.java | 12 +- .../plugins/PluginFileReaderTest.java | 7 +- .../plugins/PluginFinderTest.java | 75 +- .../plugins/PluginLoaderTest.java | 37 +- .../creation/MockSettingsImplTest.java | 215 +-- .../AbstractByteBuddyMockMakerTest.java | 85 +- .../bytebuddy/ByteBuddyMockMakerTest.java | 6 +- .../InlineByteBuddyMockMakerTest.java | 177 ++- .../SubclassByteBuddyMockMakerTest.java | 36 +- .../TypeCachingMockBytecodeGeneratorTest.java | 133 +- .../instance/ConstructorInstantiatorTest.java | 65 +- .../debugging/LoggingListenerTest.java | 114 +- .../VerboseMockInvocationLoggerTest.java | 12 +- .../debugging/WarningsFinderTest.java | 19 +- .../internal/exceptions/ReporterTest.java | 76 +- .../ConditionalStackTraceFilterTest.java | 21 +- .../stacktrace/StackTraceFilterTest.java | 167 +- .../exceptions/util/ScenarioPrinterTest.java | 16 +- .../DefaultMockitoFrameworkTest.java | 75 +- .../MatcherGenericTypeExtractorTest.java | 82 +- .../InvocationNotifierHandlerTest.java | 48 +- .../handler/MockHandlerFactoryTest.java | 24 +- .../internal/handler/MockHandlerImplTest.java | 43 +- .../invocation/InvocationBuilder.java | 55 +- .../invocation/InvocationMarkerTest.java | 28 +- .../invocation/InvocationMatcherTest.java | 74 +- .../invocation/InvocationsFinderTest.java | 132 +- .../MatcherApplicationStrategyTest.java | 79 +- .../invocation/SerializableMethodTest.java | 3 +- .../invocation/TypeSafeMatchingTest.java | 14 +- .../mockref/MockWeakReferenceTest.java | 4 +- .../internal/junit/ArgMismatchFinderTest.java | 65 +- .../internal/junit/ExceptionFactoryTest.java | 44 +- .../mockito/internal/junit/JUnitRuleTest.java | 9 +- .../junit/StubbingArgMismatchesTest.java | 62 +- .../internal/junit/UnusedStubbingsTest.java | 46 +- .../junit/util/JUnitFailureHackerTest.java | 25 +- .../listeners/StubbingLookupNotifierTest.java | 8 +- .../VerificationStartedNotifierTest.java | 79 +- .../matchers/CapturingMatcherTest.java | 31 +- .../matchers/ComparableMatchersTest.java | 8 +- .../internal/matchers/EqualityTest.java | 4 +- .../mockito/internal/matchers/EqualsTest.java | 13 +- .../internal/matchers/InstanceOfTest.java | 9 +- .../matchers/MatchersPrinterTest.java | 44 +- .../matchers/MatchersToStringTest.java | 40 +- .../internal/matchers/StringMatchersTest.java | 1 - .../apachecommons/EqualsBuilderTest.java | 317 ++-- .../matchers/text/MatcherToStringTest.java | 12 +- .../matchers/text/ValuePrinterTest.java | 41 +- .../progress/MockingProgressImplTest.java | 34 +- .../ThreadSafeMockingProgressTest.java | 8 +- .../mockito/internal/progress/TimesTest.java | 6 +- .../progress/VerificationModeBuilder.java | 1 - .../runners/DefaultInternalRunnerTest.java | 40 +- .../runners/util/RunnerProviderTest.java | 9 +- .../runners/util/TestMethodsFinderTest.java | 3 +- .../DefaultMockitoSessionBuilderTest.java | 100 +- .../InvocationContainerImplStubbingTest.java | 29 +- .../stubbing/InvocationContainerImplTest.java | 53 +- .../answers/AbstractThrowsExceptionTest.java | 26 +- .../answers/AnswersWithDelayTest.java | 15 +- .../answers/CallsRealMethodsTest.java | 24 +- .../answers/DefaultAnswerValidatorTest.java | 14 +- .../stubbing/answers/DoesNothingTest.java | 9 +- .../stubbing/answers/InvocationInfoTest.java | 138 +- .../answers/ReturnsArgumentAtTest.java | 205 +-- .../stubbing/answers/ReturnsTest.java | 54 +- .../ThrowsExceptionForClassTypeTest.java | 6 +- .../stubbing/answers/ThrowsExceptionTest.java | 24 +- .../ForwardsInvocationsTest.java | 9 +- .../defaultanswers/HasPrimitiveMethods.java | 7 + .../ReturnsEmptyValuesTest.java | 25 +- .../ReturnsGenericDeepStubsTest.java | 95 +- .../defaultanswers/ReturnsMocksTest.java | 32 +- .../defaultanswers/ReturnsSmartNullsTest.java | 298 ++-- .../org/mockito/internal/util/ChecksTest.java | 3 +- .../util/DefaultMockingDetailsTest.java | 90 +- .../util/MockCreationValidatorTest.java | 21 +- .../internal/util/MockNameImplTest.java | 15 +- .../internal/util/MockSettingsTest.java | 17 +- .../mockito/internal/util/MockUtilTest.java | 12 +- .../internal/util/ObjectMethodsGuruTest.java | 35 +- .../mockito/internal/util/PlatformTest.java | 87 +- .../mockito/internal/util/PrimitivesTest.java | 1 - .../internal/util/SimpleMockitoLogger.java | 3 +- .../util/SimpleMockitoLoggerTest.java | 6 +- .../mockito/internal/util/StringUtilTest.java | 16 +- .../org/mockito/internal/util/TimerTest.java | 15 +- .../HashCodeAndEqualsSafeSetTest.java | 41 +- .../util/collections/IdentitySetTest.java | 12 +- .../util/collections/ListUtilTest.java | 13 +- .../reflection/AccessibilityChangerTest.java | 2 - .../reflection/BeanPropertySetterTest.java | 15 +- .../util/reflection/DummyClassForTests.java | 4 +- .../reflection/DummyParentClassForTests.java | 2 +- .../util/reflection/FieldInitializerTest.java | 58 +- .../util/reflection/FieldReaderTest.java | 8 +- .../internal/util/reflection/FieldsTest.java | 35 +- .../GenericArrayReturnTypeTest.java | 3 +- .../util/reflection/GenericMasterTest.java | 22 +- .../GenericMetadataSupportTest.java | 317 ++-- .../reflection/GenericTypeExtractorTest.java | 45 +- .../util/reflection/LenientCopyToolTest.java | 36 +- ...ameterizedConstructorInstantiatorTest.java | 60 +- .../reflection/SuperTypesLastSorterTest.java | 99 +- .../verification/DescriptionTest.java | 6 +- .../verification/DummyVerificationMode.java | 3 +- .../verification/NoInteractionsTest.java | 10 +- .../verification/NoMoreInteractionsTest.java | 43 +- .../internal/verification/OnlyTest.java | 19 +- .../verification/SmartPrinterTest.java | 21 +- .../VerificationDataImplTest.java | 6 +- .../VerificationOverTimeImplTest.java | 6 +- .../VerificationWithDescriptionTest.java | 3 +- .../ArgumentMatchingToolTest.java | 44 +- ...tLeastXNumberOfInvocationsCheckerTest.java | 39 +- .../MissingInvocationCheckerTest.java | 45 +- .../MissingInvocationInOrderCheckerTest.java | 21 +- .../NumberOfInvocationsCheckerTest.java | 16 +- ...NumberOfInvocationsInOrderCheckerTest.java | 12 +- .../mockito/junit/TestableJUnitRunner.java | 31 +- ...ConsoleSpammingMockitoJUnitRunnerTest.java | 30 +- .../verification/NegativeDurationTest.java | 3 +- .../org/mockito/verification/TimeoutTest.java | 26 +- .../NoByteCodeDependenciesTest.java | 36 +- .../NoJUnitDependenciesTest.java | 52 +- .../mockitousage/CompilationWarningsTest.java | 178 ++- src/test/java/org/mockitousage/IMethods.java | 21 +- .../java/org/mockitousage/MethodsImpl.java | 36 +- .../java/org/mockitousage/PlaygroundTest.java | 126 +- ...thDemoOfUnclonedParametersProblemTest.java | 47 +- .../annotation/AnnotationsTest.java | 19 +- .../annotation/CaptorAnnotationBasicTest.java | 21 +- .../annotation/CaptorAnnotationTest.java | 39 +- .../CaptorAnnotationUnhappyPathTest.java | 10 +- .../DeprecatedAnnotationEngineApiTest.java | 17 +- ...InjectionOfInlinedMockDeclarationTest.java | 9 +- ...InjectionUsingConstructorIssue421Test.java | 6 +- .../MockInjectionUsingConstructorTest.java | 67 +- ...ockInjectionUsingSetterOrPropertyTest.java | 47 +- ...yAnnotationInitializedInBaseClassTest.java | 21 +- .../annotation/SpyAnnotationTest.java | 154 +- .../annotation/SpyInjectionTest.java | 1 + .../annotation/WrongSetOfAnnotationsTest.java | 64 +- .../mockitousage/basicapi/MockAccessTest.java | 1 - .../MockingMultipleInterfacesTest.java | 66 +- .../basicapi/MocksCreationTest.java | 53 +- .../MocksSerializationForAnnotationTest.java | 77 +- .../basicapi/MocksSerializationTest.java | 78 +- .../basicapi/ObjectsSerializationTest.java | 20 +- .../basicapi/ReplacingObjectMethodsTest.java | 22 +- .../basicapi/ResetInvocationsTest.java | 8 +- .../org/mockitousage/basicapi/ResetTest.java | 19 +- .../basicapi/UsingVarargsTest.java | 38 +- .../bugs/AIOOBExceptionWithAtLeastTest.java | 4 +- ...alInvocationHasNullArgumentNPEBugTest.java | 10 +- .../AtLeastMarksAllInvocationsVerified.java | 9 +- .../bugs/BridgeMethodsHitAgainTest.java | 61 +- .../bugs/CaptorAnnotationAutoboxingTest.java | 7 +- ...assCastExOnVerifyZeroInteractionsTest.java | 26 +- .../mockitousage/bugs/CompareMatcherTest.java | 16 +- ...eptionOnMultiThreadedVerificationTest.java | 11 +- .../bugs/ConfusedSignatureTest.java | 11 +- .../bugs/CovariantOverrideTest.java | 2 +- ...mondInheritanceIsConfusingMockitoTest.java | 8 +- .../bugs/FillInStackTraceScenariosTest.java | 8 +- ...hCodeAndEqualsRaiseNPEInInitMocksTest.java | 3 +- .../bugs/GenericsMockitoAnnotationsTest.java | 6 +- .../InheritedGenericsPolimorphicCallTest.java | 31 +- .../bugs/ListenersLostOnResetMockTest.java | 1 - ...kitoRunnerBreaksWhenNoTestMethodsTest.java | 26 +- .../bugs/MockitoStubbedCallInAnswerTest.java | 81 +- .../bugs/MultipleInOrdersTest.java | 4 +- .../MultithreadedStubbingHalfManualTest.java | 12 +- .../NPEOnAnyClassMatcherAutounboxTest.java | 2 +- .../bugs/NPEWhenMockingThrowablesTest.java | 5 +- ...ksCompareToBeConsistentWithEqualsTest.java | 32 +- .../ShouldNotDeadlockAnswerExecutionTest.java | 6 +- ...ldOnlyModeAllowCapturingArgumentsTest.java | 8 +- .../bugs/SpyShouldHaveNiceNameTest.java | 6 +- ...cksThatAreConfiguredToReturnMocksTest.java | 2 +- ...ngWithAnExtraCallToADifferentMockTest.java | 11 +- ...kingMethodShouldNotRaiseExceptionTest.java | 25 +- ...arentWithNonPublicTypeInSignatureTest.java | 1 - .../ShouldAllowInlineMockCreationTest.java | 2 +- .../bugs/creation/api/PublicClass.java | 3 +- .../otherpackage/PublicParentClass.java | 5 +- ...FailingWhenGenericNestedAsRawTypeTest.java | 28 +- ...onglyReportsSerializationProblemsTest.java | 11 +- ...ChildWithSameParentFieldInjectionTest.java | 9 +- ...ertySettersFirstBeforeFieldAccessTest.java | 1 - ...FirstLookForExactTypeThenAncestorTest.java | 7 +- ...htNotHappenInCertainConfigurationTest.java | 10 +- .../ParentTestMockInjectionTest.java | 8 +- ...tTryToInjectInFinalOrStaticFieldsTest.java | 4 +- ...dAnyObjectPicksUpExtraInvocationsTest.java | 15 +- ...VarargsErrorWhenCallingRealMethodTest.java | 2 +- .../VarargsNotPlayingWithAnyObjectTest.java | 2 +- .../ClassCacheVersusClassReloadingTest.java | 38 +- .../configuration/ClassToBeMocked.java | 2 +- .../CustomizedAnnotationForSmartMockTest.java | 16 +- .../CreatingMocksWithConstructorTest.java | 213 ++- .../customization/BDDMockitoTest.java | 102 +- .../java/org/mockitousage/debugging/Foo.java | 1 + .../InvocationListenerCallbackTest.java | 8 +- .../debugging/InvocationsPrinterTest.java | 70 +- .../mockitousage/debugging/NewMockito.java | 2 +- .../StubbingLookupListenerCallbackTest.java | 89 +- ...VerboseLoggingOfInvocationsOnMockTest.java | 13 +- .../VerificationListenerCallBackTest.java | 44 +- .../examples/use/ArticleCalculator.java | 5 +- .../examples/use/ArticleDatabase.java | 12 +- .../examples/use/ExampleTest.java | 6 +- .../internal/debugging/LocationImplTest.java | 40 +- .../junit/UnusedStubbingsFinderTest.java | 54 +- .../mockitousage/jls/JLS_15_12_2_5Test.java | 75 +- .../InvalidTargetMockitoJUnitRuleTest.java | 11 +- ...itTestRuleIntegratesWithRuleChainTest.java | 78 +- .../junitrule/LenientJUnitRuleTest.java | 21 +- .../junitrule/MockitoJUnitRuleTest.java | 14 +- .../junitrule/MockitoJUnitTestRuleTest.java | 14 +- .../junitrule/MutableStrictJUnitRuleTest.java | 38 +- .../MutableStrictJUnitTestRuleTest.java | 47 +- .../RuleTestWithFactoryMethodTest.java | 13 +- .../RuleTestWithParameterConstructorTest.java | 13 +- .../junitrule/StrictJUnitRuleTest.java | 173 +- .../StubbingWarningsJUnitRuleTest.java | 213 +-- .../StubbingWarningsMultiThreadingTest.java | 61 +- .../VerificationCollectorImplTest.java | 46 +- .../DeepStubbingWithJUnitRunnerTest.java | 11 +- .../junitrunner/JUnit45RunnerTest.java | 2 +- .../ModellingVerboseMockitoTest.java | 15 +- .../junitrunner/SilentRunnerTest.java | 69 +- .../junitrunner/StrictRunnerTest.java | 118 +- .../junitrunner/StrictStubsRunnerTest.java | 42 +- .../StubbingWarningsJUnitRunnerTest.java | 75 +- .../UnusedStubsExceptionMessageTest.java | 28 +- .../junitrunner/VerboseMockitoRunnerTest.java | 14 +- .../matchers/CapturingArgumentsTest.java | 91 +- .../CustomMatcherDoesYieldCCETest.java | 3 +- .../matchers/CustomMatchersTest.java | 17 +- .../matchers/GenericMatchersTest.java | 3 +- .../matchers/HamcrestMatchersTest.java | 18 +- .../matchers/InvalidUseOfMatchersTest.java | 27 +- .../MatchersMixedWithRawArgumentsTest.java | 29 +- .../mockitousage/matchers/MatchersTest.java | 78 +- .../matchers/MoreMatchersTest.java | 51 +- .../matchers/ReflectionMatchersTest.java | 18 +- .../mockitousage/matchers/VarargsTest.java | 51 +- ...ificationAndStubbingUsingMatchersTest.java | 9 +- .../CleaningUpPotentialStubbingTest.java | 7 +- .../DescriptiveMessagesOnMisuseTest.java | 74 +- .../misuse/DetectingFinalMethodsTest.java | 6 +- .../misuse/DetectingMisusedMatchersTest.java | 13 +- .../ExplicitFrameworkValidationTest.java | 9 +- .../mockitousage/misuse/InvalidUsageTest.java | 33 +- .../misuse/RestrictedObjectMethodsTest.java | 12 +- .../misuse/SpyStubbingMisuseTest.java | 10 +- .../packageprotected/PackageProtected.java | 4 +- .../plugins/MockitoPluginsTest.java | 3 +- .../puzzlers/BridgeMethodPuzzleTest.java | 10 +- .../puzzlers/OverloadingPuzzleTest.java | 3 +- .../AcrossClassLoaderSerializationTest.java | 44 +- .../DeepStubsSerializableTest.java | 38 +- .../ParallelSerializationTest.java | 80 +- .../StrictStubsSerializableTest.java | 6 +- .../session/MockitoSessionTest.java | 171 +- .../spies/PartialMockingWithSpiesTest.java | 19 +- .../spies/SpyingOnInterfacesTest.java | 81 +- .../spies/SpyingOnRealObjectsTest.java | 53 +- .../stacktrace/ClickableStackTracesTest.java | 4 +- ...leStackTracesWhenFrameworkMisusedTest.java | 8 +- .../ModellingDescriptiveMessagesTest.java | 2 +- ...aceToActualInvocationChunkInOrderTest.java | 3 + ...ackTraceToActualInvocationInOrderTest.java | 5 +- ...ntingStackTraceToActualInvocationTest.java | 5 +- .../stacktrace/StackTraceFilteringTest.java | 33 +- .../strictness/LenientMockAnnotationTest.java | 21 +- .../PotentialStubbingSensitivityTest.java | 23 +- .../strictness/StrictnessPerMockTest.java | 87 +- .../strictness/StrictnessPerStubbingTest.java | 259 +-- .../StrictnessPerStubbingWithRunnerTest.java | 22 +- ...ctnessWhenRuleStrictnessIsUpdatedTest.java | 36 +- .../strictness/StrictnessWithRulesTest.java | 22 +- .../stubbing/BasicStubbingTest.java | 38 +- .../stubbing/CallingRealMethodTest.java | 3 +- .../stubbing/CloningParameterTest.java | 31 +- .../stubbing/DeepStubbingTest.java | 64 +- .../stubbing/MisusingStubbingTest.java | 14 +- .../stubbing/SmartNullsGenericBugTest.java | 50 +- .../stubbing/SmartNullsStubbingTest.java | 17 +- .../stubbing/StrictStubbingEndToEndTest.java | 129 +- .../stubbing/StrictStubbingTest.java | 92 +- .../StubbingConsecutiveAnswersTest.java | 142 +- .../stubbing/StubbingReturnsSelfTest.java | 1 - .../stubbing/StubbingUsingDoReturnTest.java | 66 +- .../stubbing/StubbingWarningsTest.java | 75 +- .../StubbingWithAdditionalAnswersTest.java | 228 ++- .../StubbingWithBadThrowablesTest.java | 21 +- .../StubbingWithCustomAnswerTest.java | 63 +- .../stubbing/StubbingWithDelegateTest.java | 39 +- .../StubbingWithDelegateVarArgsTest.java | 10 +- .../StubbingWithExtraAnswersTest.java | 23 +- .../stubbing/StubbingWithThrowablesTest.java | 96 +- .../AtLeastXVerificationTest.java | 14 +- .../verification/AtMostXVerificationTest.java | 8 +- .../BasicVerificationInOrderTest.java | 2 +- .../verification/BasicVerificationTest.java | 29 +- .../verification/CustomVerificationTest.java | 29 +- ...ssagesOnVerificationInOrderErrorsTest.java | 99 +- ...ssagesWhenTimesXVerificationFailsTest.java | 12 +- ...tiveMessagesWhenVerificationFailsTest.java | 183 +-- .../ExactNumberOfTimesVerificationTest.java | 17 +- ...indingRedundantInvocationsInOrderTest.java | 39 +- .../NoMoreInteractionsVerificationTest.java | 19 +- .../verification/OnlyVerificationTest.java | 13 +- ...VerificationPrintsAllInteractionsTest.java | 19 +- ...PrintingVerboseTypesWithArgumentsTest.java | 68 +- .../RelaxedVerificationInOrderTest.java | 33 +- .../SelectedMocksInOrderVerificationTest.java | 21 +- .../VerificationExcludingStubsTest.java | 27 +- ...rderMixedWithOrdiraryVerificationTest.java | 11 +- .../verification/VerificationInOrderTest.java | 9 +- .../VerificationInOrderWithCallsTest.java | 397 +++-- .../VerificationInOrderWithTimeoutTest.java | 103 +- .../VerificationStartedListenerTest.java | 122 +- .../VerificationUsingMatchersTest.java | 16 +- .../VerificationWithAfterAndCaptorTest.java | 4 +- .../VerificationWithAfterTest.java | 154 +- .../VerificationWithTimeoutTest.java | 93 +- ...VerifyPrintsAllInvocationsOnErrorTest.java | 5 +- .../java/org/mockitoutil/ClassLoaders.java | 120 +- .../org/mockitoutil/ClassLoadersTest.java | 265 ++-- .../org/mockitoutil/ConcurrentTesting.java | 2 +- src/test/java/org/mockitoutil/Conditions.java | 30 +- .../org/mockitoutil/JUnitResultAssert.java | 63 +- .../java/org/mockitoutil/SafeJUnitRule.java | 41 +- .../org/mockitoutil/SafeJUnitRuleTest.java | 162 +- .../org/mockitoutil/SimpleClassGenerator.java | 9 +- .../SimplePerRealmReloadingClassLoader.java | 53 +- .../mockitoutil/SimpleSerializationUtil.java | 9 +- src/test/java/org/mockitoutil/Stopwatch.java | 20 +- src/test/java/org/mockitoutil/TestBase.java | 23 +- .../java/org/mockitoutil/TestBaseTest.java | 14 +- .../java/org/mockitoutil/ThrowableAssert.java | 10 +- .../org/mockitoutil/VmArgAssumptions.java | 1 - .../org/mockitoutil/async/AsyncTesting.java | 49 +- .../mockitoutil/async/AsyncTestingTest.java | 24 +- 629 files changed, 12781 insertions(+), 9098 deletions(-) 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()); } } From 4fd405da2e199a06ca5950af910b102a62d66b21 Mon Sep 17 00:00:00 2001 From: Artem Prigoda Date: Thu, 18 Jun 2020 13:09:19 +0200 Subject: [PATCH 041/963] Fix a confusing typo in subclassing error message (#1953) --- .../internal/creation/bytebuddy/SubclassInjectionLoader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 5211629449..c70de01355 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java @@ -21,7 +21,7 @@ class SubclassInjectionLoader implements SubclassLoader { 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", + "Currently, Mockito supports injection via either by method handle lookups or using sun.misc.Unsafe", "Neither seems to be available on your current JVM."); private final SubclassLoader loader; From 397b4d247c74bd36761007d10f9c36f74d3aa310 Mon Sep 17 00:00:00 2001 From: Eitan Adler Date: Fri, 19 Jun 2020 14:29:16 -0700 Subject: [PATCH 042/963] Update gradle-errorprone-plugin to 1.1.0 (#1908) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 18c35ea3dd..bf9d46254d 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { dependencies { classpath 'gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.14.0' - classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.6' + classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.1.0' //Using buildscript.classpath so that we can resolve shipkit from maven local, during local testing classpath 'org.shipkit:shipkit:2.1.6' From 0ed81f72359b1a0625fa22956d34e54fdfc1d7ce Mon Sep 17 00:00:00 2001 From: adrianriley Date: Sat, 20 Jun 2020 17:54:36 +0100 Subject: [PATCH 043/963] Fixes #1712: prepend description to AssertionError thrown in verification (#1949) --- .../base/MockitoAssertionError.java | 12 ++++ .../internal/verification/Description.java | 2 + .../java/org/mockito/DescriptionTest.java | 58 +++++++++++++++++++ .../verification/DescriptionTest.java | 24 ++++++++ 4 files changed, 96 insertions(+) create mode 100644 src/test/java/org/mockito/DescriptionTest.java diff --git a/src/main/java/org/mockito/exceptions/base/MockitoAssertionError.java b/src/main/java/org/mockito/exceptions/base/MockitoAssertionError.java index a3e046c479..5e463c7288 100644 --- a/src/main/java/org/mockito/exceptions/base/MockitoAssertionError.java +++ b/src/main/java/org/mockito/exceptions/base/MockitoAssertionError.java @@ -46,6 +46,18 @@ public MockitoAssertionError(MockitoAssertionError error, String message) { unfilteredStackTrace = error.getUnfilteredStackTrace(); } + /** + * Creates a copy of the given assertion error with the custom failure message prepended. + * @param error The assertion error to copy + * @param message The custom message to prepend + * @since 3.3.13 + */ + public MockitoAssertionError(AssertionError error, String message) { + super(message + "\n" + error.getMessage()); + unfilteredStackTrace = error.getStackTrace(); + super.setStackTrace(unfilteredStackTrace); + } + public StackTraceElement[] getUnfilteredStackTrace() { return unfilteredStackTrace; } diff --git a/src/main/java/org/mockito/internal/verification/Description.java b/src/main/java/org/mockito/internal/verification/Description.java index d9c133e03d..7732ceb98e 100644 --- a/src/main/java/org/mockito/internal/verification/Description.java +++ b/src/main/java/org/mockito/internal/verification/Description.java @@ -41,6 +41,8 @@ public void verify(VerificationData data) { } catch (MockitoAssertionError e) { throw new MockitoAssertionError(e, description); + } catch (AssertionError e) { + throw new MockitoAssertionError(e, description); } } } diff --git a/src/test/java/org/mockito/DescriptionTest.java b/src/test/java/org/mockito/DescriptionTest.java new file mode 100644 index 0000000000..32565e4b6c --- /dev/null +++ b/src/test/java/org/mockito/DescriptionTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito; + +import static org.mockito.Mockito.*; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.exceptions.base.MockitoAssertionError; + +/** + * Tests for https://github.com/mockito/mockito/issues/1712 + */ +public class DescriptionTest { + @Rule public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void verify_method_not_called_should_include_description_in_report() { + final String description = "Failed to call doSomethingElse"; + expectedException.expect(MockitoAssertionError.class); + expectedException.expectMessage(description); + + Dependency dependency = spy(Dependency.class); + SystemUnderTest systemUnderTest = new SystemUnderTest(); + systemUnderTest.doNothing(dependency); + verify(dependency, description(description)).doSomethingElse(false); + } + + @Test + public void + verify_method_called_with_unexpected_argument_should_include_description_in_report() { + final String description = "Failed to call doSomethingElse with expected argument"; + expectedException.expect(MockitoAssertionError.class); + expectedException.expectMessage(description); + + Dependency dependency = spy(Dependency.class); + SystemUnderTest systemUnderTest = new SystemUnderTest(); + systemUnderTest.doSomething(dependency); + verify(dependency, description(description)).doSomethingElse(false); + } + + static class SystemUnderTest { + @SuppressWarnings("unused") + void doNothing(Dependency dependency) {} + + void doSomething(Dependency dependency) { + dependency.doSomethingElse(true); + } + } + + static class Dependency { + @SuppressWarnings("unused") + void doSomethingElse(boolean value) {} + } +} diff --git a/src/test/java/org/mockito/internal/verification/DescriptionTest.java b/src/test/java/org/mockito/internal/verification/DescriptionTest.java index 5444ca342f..224aa02f06 100644 --- a/src/test/java/org/mockito/internal/verification/DescriptionTest.java +++ b/src/test/java/org/mockito/internal/verification/DescriptionTest.java @@ -51,4 +51,28 @@ public void verification_failure_should_prepend_expected_message() { assertEquals(expectedResult, e.getMessage()); } } + + /** + * Test of verify method, of class Description. This test validates that the custom message is prepended to the + * error message when verification fails and throws a Throwable which is not a MockitoAssertionError. + */ + @Test + public void verification_failure_throwing_AssertionError_should_prepend_expected_message() { + String failureMessage = "message should be prepended to the original message"; + String exceptionMessage = "original error message"; + String expectedResult = failureMessage + "\n" + exceptionMessage; + AssertionError error = new AssertionError(exceptionMessage); + doThrow(error).when(mockVerificationMode).verify(mockVerificationData); + + Description instance = new Description(mockVerificationMode, failureMessage); + + try { + instance.verify(mockVerificationData); + verify(mockVerificationMode).verify(mockVerificationData); + fail("Should not have made it this far"); + + } catch (MockitoAssertionError e) { + assertEquals(expectedResult, e.getMessage()); + } + } } From c5edffef198185ea9e5a91a71a26372e64fe2132 Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Sat, 20 Jun 2020 18:13:43 +0100 Subject: [PATCH 044/963] Update spotless Travis job name to be more descriptive (#1957) --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5a83c8afc2..f8d4486d73 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,7 +30,7 @@ matrix: env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) - jdk: openjdk11 - name: "Verify code formatting with Spotless" + name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." script: ./gradlew spotlessCheck # Do not upload a coverage report, as we don't run the tests for this job after_success: true From 0501e02994959c997dd0a5bdafc6288ae1e487ac Mon Sep 17 00:00:00 2001 From: Erhard Pointl Date: Mon, 22 Jun 2020 22:40:26 +0200 Subject: [PATCH 045/963] Update errorprone gradle plugin to v1.2.1 (#1958) see https://github.com/tbroyer/gradle-errorprone-plugin/releases for details --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index bf9d46254d..160cf24a6e 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { dependencies { classpath 'gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.14.0' - classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.1.0' + classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.2.1' //Using buildscript.classpath so that we can resolve shipkit from maven local, during local testing classpath 'org.shipkit:shipkit:2.1.6' From 87aacaeca72f99941323d7d5d981cde333177b23 Mon Sep 17 00:00:00 2001 From: Jamie Tanna Date: Mon, 29 Jun 2020 17:15:18 +0100 Subject: [PATCH 046/963] Document using `@Mock` with method parameters (#1961) Although we've called it out in the [JUnit extension], we should also make sure it's clear in the core documentation to make it more visible. We can fully-quality the `@Test` annotation to make clear that it has to be with JUnit 5. Closes #1960. [JUnit extension]: https://javadoc.io/doc/org.mockito/mockito-junit-jupiter/latest/org/mockito/junit/jupiter/MockitoExtension.html --- src/main/java/org/mockito/Mockito.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 07a5dfcb56..f6d0870001 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -455,6 +455,9 @@ * @Mock private UserProvider userProvider; * * private ArticleManager manager; + * + * @org.junit.jupiter.api.Test + * void testSomethingInJunit5(@Mock ArticleDatabase database) { * * * Important! This needs to be somewhere in the base class or a test From b3fc349e8e525e41f34ff04aca8c3140ff2b335a Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Fri, 19 Jun 2020 11:12:31 +0200 Subject: [PATCH 047/963] Mockito \#1013: Defines and implements API for static mocking. --- src/main/java/org/mockito/Captor.java | 11 +- src/main/java/org/mockito/InjectMocks.java | 22 ++- src/main/java/org/mockito/Mock.java | 23 ++- src/main/java/org/mockito/MockSettings.java | 15 ++ src/main/java/org/mockito/MockedStatic.java | 78 ++++++++ src/main/java/org/mockito/Mockito.java | 99 +++++++++- .../java/org/mockito/MockitoAnnotations.java | 56 +++++- src/main/java/org/mockito/MockitoSession.java | 4 +- src/main/java/org/mockito/Spy.java | 18 +- .../configuration/AnnotationEngine.java | 2 +- .../mockito/internal/MockedStaticImpl.java | 184 ++++++++++++++++++ .../org/mockito/internal/MockitoCore.java | 19 ++ .../IndependentAnnotationEngine.java | 17 +- .../InjectingAnnotationEngine.java | 41 +++- .../MockAnnotationProcessor.java | 38 +++- .../configuration/SpyAnnotationEngine.java | 5 +- .../injection/SpyOnInjectedFieldsHandler.java | 2 +- .../internal/creation/MockSettingsImpl.java | 30 ++- .../bytebuddy/ByteBuddyMockMaker.java | 6 + .../creation/bytebuddy/BytecodeGenerator.java | 2 + .../bytebuddy/InlineByteBuddyMockMaker.java | 122 +++++++++++- .../bytebuddy/InlineBytecodeGenerator.java | 72 +++++-- .../creation/bytebuddy/MockMethodAdvice.java | 102 +++++++++- .../bytebuddy/SubclassBytecodeGenerator.java | 5 + .../TypeCachingBytecodeGenerator.java | 5 + .../inject/MockMethodDispatcher.java | 27 ++- .../mockito/internal/exceptions/Reporter.java | 6 +- .../framework/DefaultMockitoSession.java | 28 ++- .../invocation/InterceptedInvocation.java | 12 -- .../internal/junit/JUnitSessionStore.java | 7 +- .../runners/DefaultInternalRunner.java | 13 +- .../mockito/internal/util/MockNameImpl.java | 13 +- .../org/mockito/internal/util/MockUtil.java | 6 + .../util/concurrent/WeakConcurrentSet.java | 2 +- .../org/mockito/junit/MockitoJUnitRunner.java | 2 +- .../java/org/mockito/junit/MockitoRule.java | 2 +- .../org/mockito/plugins/AnnotationEngine.java | 10 +- .../java/org/mockito/plugins/MockMaker.java | 43 ++++ .../session/MockitoSessionBuilder.java | 4 +- src/test/java/org/mockito/MockitoTest.java | 7 + .../GlobalConfigurationTest.java | 4 +- .../util/DefaultMockingDetailsTest.java | 2 +- .../internal/util/MockNameImplTest.java | 32 ++- .../verification/DescriptionTest.java | 4 +- .../VerificationOverTimeImplTest.java | 4 +- .../VerificationWithDescriptionTest.java | 2 +- .../annotation/AnnotationsTest.java | 6 +- .../annotation/CaptorAnnotationTest.java | 10 +- .../CaptorAnnotationUnhappyPathTest.java | 2 +- .../DeprecatedAnnotationEngineApiTest.java | 4 +- .../MockInjectionUsingConstructorTest.java | 18 +- ...ockInjectionUsingSetterOrPropertyTest.java | 16 +- ...yAnnotationInitializedInBaseClassTest.java | 4 +- .../annotation/SpyAnnotationTest.java | 20 +- .../annotation/WrongSetOfAnnotationsTest.java | 14 +- .../MocksSerializationForAnnotationTest.java | 2 +- ...hCodeAndEqualsRaiseNPEInInitMocksTest.java | 2 +- .../bugs/GenericsMockitoAnnotationsTest.java | 4 +- ...kingMethodShouldNotRaiseExceptionTest.java | 6 +- .../ParentTestMockInjectionTest.java | 4 +- src/test/java/org/mockitoutil/TestBase.java | 2 +- .../MockitoAnyClassWithPrimitiveType.java | 4 +- .../org/mockitoinline/StaticMockTest.java | 175 +++++++++++++++++ .../junit/jupiter/MockitoExtension.java | 24 ++- version.properties | 2 +- 65 files changed, 1328 insertions(+), 199 deletions(-) create mode 100644 src/main/java/org/mockito/MockedStatic.java create mode 100644 src/main/java/org/mockito/internal/MockedStaticImpl.java create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java diff --git a/src/main/java/org/mockito/Captor.java b/src/main/java/org/mockito/Captor.java index 225bf700f2..358f37ef0a 100644 --- a/src/main/java/org/mockito/Captor.java +++ b/src/main/java/org/mockito/Captor.java @@ -15,9 +15,16 @@ * * @Captor ArgumentCaptor<AsyncCallback<Foo>> captor; * + * private AutoCloseable closeable; + * * @Before - * public void init(){ - * MockitoAnnotations.initMocks(this); + * public void open() { + * MockitoAnnotations.openMocks(this); + * } + * + * @After + * public void release() throws Exception { + * closeable.close(); * } * * @Test public void shouldDoSomethingUseful() { diff --git a/src/main/java/org/mockito/InjectMocks.java b/src/main/java/org/mockito/InjectMocks.java index 375c35514d..3327f9dc33 100644 --- a/src/main/java/org/mockito/InjectMocks.java +++ b/src/main/java/org/mockito/InjectMocks.java @@ -71,8 +71,14 @@ * * public class SampleBaseTestCase { * - * @Before public void initMocks() { - * MockitoAnnotations.initMocks(this); + * private AutoCloseable closeable; + * + * @Before public void openMocks() { + * closeable = MockitoAnnotations.openMocks(this); + * } + * + * @After public void releaseMocks() throws Exception { + * closeable.close(); * } * } * @@ -141,11 +147,11 @@ *

    * *

    - * MockitoAnnotations.initMocks(this) method has to be called to initialize annotated objects. - * In above example, initMocks() is called in @Before (JUnit4) method of test's base class. - * For JUnit3 initMocks() can go to setup() method of a base class. - * Instead you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in - * {@link MockitoJUnitRunner}. + * MockitoAnnotations.openMocks(this) method has to be called to initialize annotated objects. + * In above example, openMocks() is called in @Before (JUnit4) method of test's base class. + * For JUnit3 openMocks() can go to setup() method of a base class. + * Instead you can also put openMocks() in your JUnit runner (@RunWith) or use the built-in + * {@link MockitoJUnitRunner}. Also, make sure to release any mocks after disposing your test class with a corresponding hook. *

    * *

    @@ -155,7 +161,7 @@ * * @see Mock * @see Spy - * @see MockitoAnnotations#initMocks(Object) + * @see MockitoAnnotations#openMocks(Object) * @see MockitoJUnitRunner * @since 1.8.3 */ diff --git a/src/main/java/org/mockito/Mock.java b/src/main/java/org/mockito/Mock.java index 2473557e56..cb5bfba157 100644 --- a/src/main/java/org/mockito/Mock.java +++ b/src/main/java/org/mockito/Mock.java @@ -23,6 +23,7 @@ *

  • Minimizes repetitive mock creation code.
  • *
  • Makes the test class more readable.
  • *
  • Makes the verification error easier to read because the field name is used to identify the mock.
  • + *
  • Automatically detects static mocks of type {@link MockedStatic} and infers the static mock type of the type parameter.
  • * * *
    
    @@ -43,24 +44,30 @@
      *
      *   public class SampleBaseTestCase {
      *
    - *       @Before public void initMocks() {
    - *           MockitoAnnotations.initMocks(this);
    + *       private AutoCloseable closeable;
    + *
    + *       @Before public void openMocks() {
    + *           closeable = MockitoAnnotations.openMocks(this);
    + *       }
    + *
    + *       @After public void releaseMocks() throws Exception {
    + *           closeable.close();
      *       }
      *   }
      * 
    * *

    - * MockitoAnnotations.initMocks(this) method has to be called to initialize annotated objects. - * In above example, initMocks() is called in @Before (JUnit4) method of test's base class. - * For JUnit3 initMocks() can go to setup() method of a base class. - * Instead you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in - * {@link MockitoJUnitRunner}. + * MockitoAnnotations.openMocks(this) method has to be called to initialize annotated objects. + * In above example, openMocks() is called in @Before (JUnit4) method of test's base class. + * For JUnit3 openMocks() can go to setup() method of a base class. + * Instead you can also put openMocks() in your JUnit runner (@RunWith) or use the built-in + * {@link MockitoJUnitRunner}. Also, make sure to release any mocks after disposing your test class with a corresponding hook. *

    * * @see Mockito#mock(Class) * @see Spy * @see InjectMocks - * @see MockitoAnnotations#initMocks(Object) + * @see MockitoAnnotations#openMocks(Object) * @see MockitoJUnitRunner */ @Target({FIELD, PARAMETER}) diff --git a/src/main/java/org/mockito/MockSettings.java b/src/main/java/org/mockito/MockSettings.java index 30496d164c..a1fdb508fd 100644 --- a/src/main/java/org/mockito/MockSettings.java +++ b/src/main/java/org/mockito/MockSettings.java @@ -340,6 +340,21 @@ public interface MockSettings extends Serializable { @Incubating MockCreationSettings build(Class typeToMock); + /** + * Creates immutable view of mock settings used later by Mockito, for use within a static mocking. + * Framework integrators can use this method to create instances of creation settings + * and use them in advanced use cases, for example to create invocations with {@link InvocationFactory}, + * or to implement custom {@link MockHandler}. + * Since {@link MockCreationSettings} is {@link NotExtensible}, Mockito public API needs a creation method for this type. + * + * @param classToMock class to mock + * @param type to mock + * @return immutable view of mock settings + * @since 2.10.0 + */ + @Incubating + MockCreationSettings buildStatic(Class classToMock); + /** * Lenient mocks bypass "strict stubbing" validation (see {@link Strictness#STRICT_STUBS}). * When mock is declared as lenient none of its stubbings will be checked for potential stubbing problems such as diff --git a/src/main/java/org/mockito/MockedStatic.java b/src/main/java/org/mockito/MockedStatic.java new file mode 100644 index 0000000000..19ed5e944c --- /dev/null +++ b/src/main/java/org/mockito/MockedStatic.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2007 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito; + +import org.mockito.stubbing.OngoingStubbing; +import org.mockito.verification.VerificationMode; + +import static org.mockito.Mockito.*; + +/** + * Represents an active mock of a type's static methods. The mocking only affects the thread + * on which this static mock was created and it is not safe to use this object from another + * thread. The static mock is released when this object's {@link MockedStatic#close()} method + * is invoked. If this object is never closed, the static mock will remain active on the + * initiating thread. It is therefore recommended to create this object within a try-with-resources + * statement unless when managed explicitly, for example by using a JUnit rule or extension. + *

    + * If the {@link Mock} annotation is used on fields or method parameters of this type, a static mock + * is created instead of a regular mock. The static mock is activated and released upon completing any + * relevant test. + * + * @param The type being mocked. + */ +@Incubating +public interface MockedStatic extends AutoCloseable { + + /** + * See {@link Mockito#when(Object)}. + */ + OngoingStubbing when(Verification verification); + + /** + * See {@link Mockito#verify(Object)}. + */ + default void verify(Verification verification) { + verify(times(1), verification); + } + + /** + * See {@link Mockito#verify(Object, VerificationMode)}. + */ + void verify(VerificationMode mode, Verification verification); + + /** + * See {@link Mockito#reset(Object[])}. + */ + void reset(); + + /** + * See {@link Mockito#clearInvocations(Object[])}. + */ + void clearInvocations(); + + /** + * {@link Mockito#verifyNoMoreInteractions(Object...)}. + */ + void verifyNoMoreInteractions(); + + /** + * See {@link Mockito#verifyNoInteractions(Object...)}. + */ + void verifyNoInteractions(); + + @Override + void close(); + + /** + * Releases this static mock and is non-operational if already released. + */ + void closeOnDemand(); + + interface Verification { + + void apply() throws Throwable; + } +} diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 07a5dfcb56..602eb1cfb8 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -105,6 +105,7 @@ * 45. New JUnit Jupiter (JUnit5+) extension
    * 46. New Mockito.lenient() and MockSettings.lenient() methods (Since 2.20.0)
    * 47. New API for clearing mock state in inline mocking (Since 2.25.0)
    + * 48. New API for mocking static methods (Since 3.4.0)
    * * *

    0. Migrating to Mockito 2

    @@ -461,7 +462,7 @@ * runner: * *
    
    - * MockitoAnnotations.initMocks(testClass);
    + * MockitoAnnotations.openMocks(testClass);
      * 
    * * You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}. @@ -863,7 +864,7 @@ * should only use partial mocks as a last resort. See point 16 about partial mocks. * *

    - * All new annotations are *only* processed on {@link MockitoAnnotations#initMocks(Object)}. + * All new annotations are *only* processed on {@link MockitoAnnotations#openMocks(Object)}. * Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule: * {@link MockitoRule}. *

    @@ -907,7 +908,7 @@ * Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields * using constructor injection, setter injection, or field injection. *

    - * To take advantage of this feature you need to use {@link MockitoAnnotations#initMocks(Object)}, {@link MockitoJUnitRunner} + * To take advantage of this feature you need to use {@link MockitoAnnotations#openMocks(Object)}, {@link MockitoJUnitRunner} * or {@link MockitoRule}. *

    * Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks} @@ -1144,7 +1145,7 @@ * *

      *
    • Annotating the JUnit test class with a @{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)
    • - *
    • Invoking {@link MockitoAnnotations#initMocks(Object)} in the @{@link org.junit.Before} method
    • + *
    • Invoking {@link MockitoAnnotations#openMocks(Object)} in the @{@link org.junit.Before} method
    • *
    * * Now you can choose to use a rule : @@ -1541,6 +1542,29 @@ * Hence, we introduced a new API to explicitly clear mock state (only make sense in inline mocking!). * See example usage in {@link MockitoFramework#clearInlineMocks()}. * If you have feedback or a better idea how to solve the problem please reach out. + * + * + *

    48. Mocking static methods (since 3.4.0)

    + * + * When using the inline mock maker, it is possible to mock static method invocations within the current + * thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere. + * + * To make sure a static mock remains temporary, it is recommended to define the scope within a try-with-resources construct. + * In the following example, the Foo type's static method would return foo unless mocked: + * + *
    
    + * assertEquals("foo", Foo.method());
    + * try (MockedStatic mocked = mockStatic(Foo.class)) {
    + * mocked.when(Foo::method).thenReturn("bar");
    + * assertEquals("bar", Foo.method());
    + * mocked.verify(Foo::method);
    + * }
    + * assertEquals("foo", Foo.method());
    + * 
    + * + * Due to the defined scope of the static mock, it returns to its original behvior once the scope is released. To define mock + * behavior and to verify static method invocations, use the MockedStatic that is returned. + *

    */ @SuppressWarnings("unchecked") public class Mockito extends ArgumentMatchers { @@ -2026,6 +2050,73 @@ public static T spy(Class classToSpy) { classToSpy, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS)); } + /** + * Creates a thread-local mock controller for all static methods of the given class or interface. + * The returned object's {@link MockedStatic#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock class or interface of which static mocks should be mocked. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedStatic mockStatic(Class classToMock) { + return mockStatic(classToMock, withSettings()); + } + + /** + * Creates a thread-local mock controller for all static methods of the given class or interface. + * The returned object's {@link MockedStatic#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock class or interface of which static mocks should be mocked. + * @param defaultAnswer the default answer when invoking static methods. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedStatic mockStatic(Class classToMock, Answer defaultAnswer) { + return mockStatic(classToMock, withSettings().defaultAnswer(defaultAnswer)); + } + + /** + * Creates a thread-local mock controller for all static methods of the given class or interface. + * The returned object's {@link MockedStatic#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock class or interface of which static mocks should be mocked. + * @param name the name of the mock to use in error messages. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedStatic mockStatic(Class classToMock, String name) { + return mockStatic(classToMock, withSettings().name(name)); + } + + /** + * Creates a thread-local mock controller for all static methods of the given class or interface. + * The returned object's {@link MockedStatic#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock class or interface of which static mocks should be mocked. + * @param mockSettings the settings to use where only name and default answer are considered. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedStatic mockStatic(Class classToMock, MockSettings mockSettings) { + return MOCKITO_CORE.mockStatic(classToMock, mockSettings); + } + /** * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called. *

    diff --git a/src/main/java/org/mockito/MockitoAnnotations.java b/src/main/java/org/mockito/MockitoAnnotations.java index ba355e702f..effddcea17 100644 --- a/src/main/java/org/mockito/MockitoAnnotations.java +++ b/src/main/java/org/mockito/MockitoAnnotations.java @@ -9,8 +9,10 @@ import org.mockito.junit.MockitoJUnitRunner; import org.mockito.plugins.AnnotationEngine; +import static org.mockito.internal.util.StringUtil.*; + /** - * MockitoAnnotations.initMocks(this); initializes fields annotated with Mockito annotations. + * MockitoAnnotations.openMocks(this); initializes fields annotated with Mockito annotations. * See also {@link MockitoSession} which not only initializes mocks * but also adds extra validation for cleaner tests! *

    @@ -37,19 +39,27 @@ * * public class SampleBaseTestCase { * - * @Before public void initMocks() { - * MockitoAnnotations.initMocks(this); + * private AutoCloseable closeable; + * + * @Before public void openMocks() { + * closeable = MockitoAnnotations.openMocks(this); + * } + * + * @After public void releaseMocks() throws Exception { + * closeable.close(); * } * } * *

    * Read also about other annotations @{@link Spy}, @{@link Captor}, @{@link InjectMocks} *

    - * MockitoAnnotations.initMocks(this) method has to be called to initialize annotated fields. + * MockitoAnnotations.openMocks(this) method has to be called to initialize annotated fields. *

    - * In above example, initMocks() is called in @Before (JUnit4) method of test's base class. - * For JUnit3 initMocks() can go to setup() method of a base class. - * You can also put initMocks() in your JUnit runner (@RunWith) or use built-in runner: {@link MockitoJUnitRunner} + * In above example, openMocks() is called in @Before (JUnit4) method of test's base class. + * For JUnit3 openMocks() can go to setup() method of a base class. + * You can also put openMocks() in your JUnit runner (@RunWith) or use built-in runner: {@link MockitoJUnitRunner}. + * If static method mocks are used, it is required to close the initialization. Additionally, if using third-party + * mock-makers, other life-cycles might be handled by the open-release routine. */ public class MockitoAnnotations { @@ -58,8 +68,10 @@ public class MockitoAnnotations { * @{@link org.mockito.Mock}, @{@link Spy}, @{@link Captor}, @{@link InjectMocks} *

    * See examples in javadoc for {@link MockitoAnnotations} class. + * + * @return A closable to close when completing any tests in {@code testClass}. */ - public static void initMocks(Object testClass) { + public static AutoCloseable openMocks(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"); @@ -67,6 +79,32 @@ public static void initMocks(Object testClass) { AnnotationEngine annotationEngine = new GlobalConfiguration().tryGetPluginAnnotationEngine(); - annotationEngine.process(testClass.getClass(), testClass); + return annotationEngine.process(testClass.getClass(), testClass); + } + + /** + * Initializes objects annotated with Mockito annotations for given testClass: + * @{@link org.mockito.Mock}, @{@link Spy}, @{@link Captor}, @{@link InjectMocks} + *

    + * See examples in javadoc for {@link MockitoAnnotations} class. + * + * @deprecated Use {@link MockitoAnnotations#openMocks(Object)} instead. + * This method is equivalent to {@code openMocks(testClass).close()}. + * The close method should however only be called after completed usage of {@code testClass}. + * If using static-mocks or custom {@link org.mockito.plugins.MockMaker}s, using this method might + * cause misbehavior of mocks injected into the test class. + */ + @Deprecated + public static void initMocks(Object testClass) { + try { + openMocks(testClass).close(); + } catch (Exception e) { + throw new MockitoException( + join( + "Failed to release mocks", + "", + "This should not happen unless you are using a third-part mock maker"), + e); + } } } diff --git a/src/main/java/org/mockito/MockitoSession.java b/src/main/java/org/mockito/MockitoSession.java index 6a529fde43..903fd0fdd0 100644 --- a/src/main/java/org/mockito/MockitoSession.java +++ b/src/main/java/org/mockito/MockitoSession.java @@ -67,7 +67,7 @@ *

    * Why to use {@code MockitoSession}? * What's the difference between {@code MockitoSession}, {@link MockitoJUnitRunner}, {@link MockitoRule} - * and traditional {@link MockitoAnnotations#initMocks(Object)}? + * and traditional {@link MockitoAnnotations#openMocks(Object)}? *

    * Great questions! * There is no need to use {@code MockitoSession} if you already use {@link MockitoJUnitRunner} or {@link MockitoRule}. @@ -78,7 +78,7 @@ * You can automatically take advantage of strict stubbing ({@link Strictness}), * automatic initialization of annotated mocks ({@link MockitoAnnotations}), * and extra validation ({@link Mockito#validateMockitoUsage()}). - * If you use Mockito annotations with {@link MockitoAnnotations#initMocks(Object)} + * If you use Mockito annotations with {@link MockitoAnnotations#openMocks(Object)} * but not Mockito runner/rule please try out Mockito's JUnit support (runner or rule) or * start using {@code MockitoSession}. You'll get cleaner tests and better productivity. *

    diff --git a/src/main/java/org/mockito/Spy.java b/src/main/java/org/mockito/Spy.java index b164c8f590..aa485a355d 100644 --- a/src/main/java/org/mockito/Spy.java +++ b/src/main/java/org/mockito/Spy.java @@ -25,9 +25,14 @@ * @Spy Foo spyOnFoo = new Foo("argument"); * //Instance for spying is created by mockito via reflection (only default constructors supported): * @Spy Bar spyOnBar; + * private AutoCloseable closeable; * @Before - * public void init(){ - * MockitoAnnotations.initMocks(this); + * public void init() { + * closeable = MockitoAnnotations.openMocks(this); + * } + * @After + * public void release() throws Exception { + * closeable.close(); * } * ... * } @@ -84,12 +89,13 @@ * * *

    - * One last warning : if you call MockitoAnnotations.initMocks(this) in a + * One last warning : if you call MockitoAnnotations.openMocks(this) in a * super class constructor then this will not work. It is because fields * in subclass are only instantiated after super class constructor has returned. * It's better to use @Before. - * Instead you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in - * {@link MockitoJUnitRunner}. + * Instead you can also put openMocks() in your JUnit runner (@RunWith) or use the built-in + * {@link MockitoJUnitRunner}. Also, make sure to release any mocks after disposing your test class with a + * corresponding hook. *

    * *

    Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them. @@ -98,7 +104,7 @@ * @see Mockito#spy(Object) * @see Mock * @see InjectMocks - * @see MockitoAnnotations#initMocks(Object) + * @see MockitoAnnotations#openMocks(Object) * @see MockitoJUnitRunner * @since 1.8.3 */ diff --git a/src/main/java/org/mockito/configuration/AnnotationEngine.java b/src/main/java/org/mockito/configuration/AnnotationEngine.java index d4f8fb0b1f..897878169a 100644 --- a/src/main/java/org/mockito/configuration/AnnotationEngine.java +++ b/src/main/java/org/mockito/configuration/AnnotationEngine.java @@ -9,7 +9,7 @@ /** * Configures mock creation logic behind @Mock, @Captor and @Spy annotations *

    - * If you are interested then see implementations or source code of {@link MockitoAnnotations#initMocks(Object)} + * If you are interested then see implementations or source code of {@link MockitoAnnotations#openMocks(Object)} * *

    This interface can be used to configure a different annotation engine through * {@link org.mockito.configuration.IMockitoConfiguration}, however this mechanism is being superseded by the new diff --git a/src/main/java/org/mockito/internal/MockedStaticImpl.java b/src/main/java/org/mockito/internal/MockedStaticImpl.java new file mode 100644 index 0000000000..908b810be0 --- /dev/null +++ b/src/main/java/org/mockito/internal/MockedStaticImpl.java @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2007 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal; + +import org.mockito.Incubating; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.MockingDetails; +import org.mockito.Mockito; +import org.mockito.exceptions.base.MockitoAssertionError; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.debugging.LocationImpl; +import org.mockito.internal.listeners.VerificationStartedNotifier; +import org.mockito.internal.progress.MockingProgress; +import org.mockito.internal.stubbing.InvocationContainerImpl; +import org.mockito.internal.verification.MockAwareVerificationMode; +import org.mockito.internal.verification.VerificationDataImpl; +import org.mockito.invocation.Location; +import org.mockito.invocation.MockHandler; +import org.mockito.plugins.MockMaker; +import org.mockito.stubbing.OngoingStubbing; +import org.mockito.verification.VerificationMode; + +import static org.mockito.internal.exceptions.Reporter.*; +import static org.mockito.internal.progress.ThreadSafeMockingProgress.*; +import static org.mockito.internal.util.MockUtil.*; +import static org.mockito.internal.util.StringUtil.*; +import static org.mockito.internal.verification.VerificationModeFactory.*; + +/** + * Represents an active mock of a type's static methods. The mocking only affects the thread + * on which this static mock was created and it is not safe to use this object from another + * thread. The static mock is released when this object's {@link MockedStaticImpl#close()} method + * is invoked. If this object is never closed, the static mock will remain active on the + * initiating thread. It is therefore recommended to create this object within a try-with-resources + * statement unless when managed explicitly, for example by using a JUnit rule or extension. + *

    + * If the {@link Mock} annotation is used on fields or method parameters of this type, a static mock + * is created instead of a regular mock. The static mock is activated and released upon completing any + * relevant test. + * + * @param The type being mocked. + */ +@Incubating +public final class MockedStaticImpl implements MockedStatic { + + private final MockMaker.StaticMockControl control; + + private boolean closed; + + private final Location location = new LocationImpl(); + + protected MockedStaticImpl(MockMaker.StaticMockControl control) { + this.control = control; + } + + @Override + public OngoingStubbing when(Verification verification) { + assertNotClosed(); + + try { + verification.apply(); + } catch (Throwable ignored) { + } + + MockingProgress mockingProgress = mockingProgress(); + mockingProgress.stubbingStarted(); + @SuppressWarnings("unchecked") + OngoingStubbing stubbing = (OngoingStubbing) mockingProgress.pullOngoingStubbing(); + if (stubbing == null) { + mockingProgress.reset(); + throw missingMethodInvocation(); + } + return stubbing; + } + + @Override + public void verify(VerificationMode mode, Verification verification) { + assertNotClosed(); + + MockingDetails mockingDetails = Mockito.mockingDetails(control.getType()); + MockHandler handler = mockingDetails.getMockHandler(); + + VerificationStartedNotifier.notifyVerificationStarted( + handler.getMockSettings().getVerificationStartedListeners(), mockingDetails); + + MockingProgress mockingProgress = mockingProgress(); + VerificationMode actualMode = mockingProgress.maybeVerifyLazily(mode); + mockingProgress.verificationStarted( + new MockAwareVerificationMode( + control.getType(), actualMode, mockingProgress.verificationListeners())); + + try { + verification.apply(); + } catch (MockitoException | MockitoAssertionError e) { + throw e; + } catch (Throwable t) { + throw new MockitoException( + join( + "An unexpected error occurred while verifying a static stub", + "", + "To correctly verify a stub, invoke a single static method of " + + control.getType().getName() + + " in the provided lambda.", + "For example, if a method 'sample' was defined, provide a lambda or anonymous class containing the code", + "", + "() -> " + control.getType().getSimpleName() + ".sample()", + "or", + control.getType().getSimpleName() + "::sample"), + t); + } + } + + @Override + public void reset() { + assertNotClosed(); + + MockingProgress mockingProgress = mockingProgress(); + mockingProgress.validateState(); + mockingProgress.reset(); + mockingProgress.resetOngoingStubbing(); + + resetMock(control.getType()); + } + + @Override + public void clearInvocations() { + assertNotClosed(); + + MockingProgress mockingProgress = mockingProgress(); + mockingProgress.validateState(); + mockingProgress.reset(); + mockingProgress.resetOngoingStubbing(); + + getInvocationContainer(control.getType()).clearInvocations(); + } + + @Override + public void verifyNoMoreInteractions() { + assertNotClosed(); + + mockingProgress().validateState(); + InvocationContainerImpl invocations = getInvocationContainer(control.getType()); + VerificationDataImpl data = new VerificationDataImpl(invocations, null); + noMoreInteractions().verify(data); + } + + @Override + public void verifyNoInteractions() { + assertNotClosed(); + + mockingProgress().validateState(); + InvocationContainerImpl invocations = getInvocationContainer(control.getType()); + VerificationDataImpl data = new VerificationDataImpl(invocations, null); + noInteractions().verify(data); + } + + @Override + public void close() { + assertNotClosed(); + + closed = true; + control.disable(); + } + + @Override + public void closeOnDemand() { + if (!closed) { + close(); + } + } + + private void assertNotClosed() { + if (closed) { + throw new MockitoException( + join( + "The static mock created at", + location.toString(), + "is already resolved and cannot longer be used")); + } + } +} diff --git a/src/main/java/org/mockito/internal/MockitoCore.java b/src/main/java/org/mockito/internal/MockitoCore.java index 4353e0fbda..bccb045fe1 100644 --- a/src/main/java/org/mockito/internal/MockitoCore.java +++ b/src/main/java/org/mockito/internal/MockitoCore.java @@ -7,6 +7,7 @@ import static org.mockito.internal.exceptions.Reporter.*; import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; import static org.mockito.internal.util.MockUtil.createMock; +import static org.mockito.internal.util.MockUtil.createStaticMock; import static org.mockito.internal.util.MockUtil.getInvocationContainer; import static org.mockito.internal.util.MockUtil.getMockHandler; import static org.mockito.internal.util.MockUtil.isMock; @@ -20,6 +21,7 @@ import org.mockito.InOrder; import org.mockito.MockSettings; +import org.mockito.MockedStatic; import org.mockito.MockingDetails; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.internal.creation.MockSettingsImpl; @@ -40,6 +42,7 @@ import org.mockito.invocation.Invocation; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; +import org.mockito.plugins.MockMaker; import org.mockito.quality.Strictness; import org.mockito.stubbing.LenientStubber; import org.mockito.stubbing.OngoingStubbing; @@ -68,6 +71,22 @@ public T mock(Class typeToMock, MockSettings settings) { return mock; } + public MockedStatic mockStatic(Class classToMock, 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."); + } + MockSettingsImpl impl = MockSettingsImpl.class.cast(settings); + MockCreationSettings creationSettings = impl.buildStatic(classToMock); + MockMaker.StaticMockControl control = createStaticMock(classToMock, creationSettings); + control.enable(); + mockingProgress().mockingStarted(classToMock, creationSettings); + return new MockedStaticImpl<>(control); + } + public OngoingStubbing when(T methodCall) { MockingProgress mockingProgress = mockingProgress(); mockingProgress.stubbingStarted(); diff --git a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java index 9b1c3767d0..24cb7a1cb2 100644 --- a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java @@ -9,11 +9,14 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Field; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.mockito.Captor; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; import org.mockito.exceptions.base.MockitoException; import org.mockito.plugins.AnnotationEngine; @@ -60,18 +63,25 @@ private void registerAnnotationProcessor( } @Override - public void process(Class clazz, Object testInstance) { + public AutoCloseable process(Class clazz, Object testInstance) { + List> mockedStatics = new ArrayList<>(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { boolean alreadyAssigned = false; for (Annotation annotation : field.getAnnotations()) { Object mock = createMockFor(annotation, field); + if (mock instanceof MockedStatic) { + mockedStatics.add((MockedStatic) mock); + } if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); alreadyAssigned = true; try { setField(testInstance, field, mock); } catch (Exception e) { + for (MockedStatic mockedStatic : mockedStatics) { + mockedStatic.close(); + } throw new MockitoException( "Problems setting field " + field.getName() @@ -82,6 +92,11 @@ public void process(Class clazz, Object testInstance) { } } } + return () -> { + for (MockedStatic mockedStatic : mockedStatics) { + mockedStatic.closeOnDemand(); + } + }; } void throwIfAlreadyAssigned(Field field, boolean alreadyAssigned) { diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java index ccc7ae4d85..2f6667015c 100644 --- a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java @@ -7,9 +7,12 @@ import static org.mockito.internal.util.collections.Sets.newMockSafeHashSet; import java.lang.reflect.Field; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import java.util.Set; +import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; import org.mockito.internal.configuration.injection.scanner.InjectMocksScanner; import org.mockito.internal.configuration.injection.scanner.MockScanner; @@ -39,29 +42,41 @@ public class InjectingAnnotationEngine * * @see org.mockito.plugins.AnnotationEngine#process(Class, Object) */ - public void process(Class clazz, Object testInstance) { - processIndependentAnnotations(testInstance.getClass(), testInstance); - processInjectMocks(testInstance.getClass(), testInstance); + public AutoCloseable process(Class clazz, Object testInstance) { + List closeables = new ArrayList<>(); + closeables.addAll(processIndependentAnnotations(testInstance.getClass(), testInstance)); + closeables.addAll(processInjectMocks(testInstance.getClass(), testInstance)); + return () -> { + for (AutoCloseable closeable : closeables) { + closeable.close(); + } + }; } - private void processInjectMocks(final Class clazz, final Object testInstance) { + private List processInjectMocks( + final Class clazz, final Object testInstance) { + List closeables = new ArrayList<>(); Class classContext = clazz; while (classContext != Object.class) { - injectMocks(testInstance); + closeables.add(injectMocks(testInstance)); classContext = classContext.getSuperclass(); } + return closeables; } - private void processIndependentAnnotations(final Class clazz, final Object testInstance) { + private List processIndependentAnnotations( + final Class clazz, final Object testInstance) { + List closeables = new ArrayList<>(); Class classContext = clazz; while (classContext != Object.class) { // this will create @Mocks, @Captors, etc: - delegate.process(classContext, testInstance); + closeables.add(delegate.process(classContext, testInstance)); // this will create @Spies: - spyAnnotationEngine.process(classContext, testInstance); + closeables.add(spyAnnotationEngine.process(classContext, testInstance)); classContext = classContext.getSuperclass(); } + return closeables; } /** @@ -73,7 +88,7 @@ private void processIndependentAnnotations(final Class clazz, final Object te * @param testClassInstance * Test class, usually this */ - public void injectMocks(final Object testClassInstance) { + private AutoCloseable injectMocks(final Object testClassInstance) { Class clazz = testClassInstance.getClass(); Set mockDependentFields = new HashSet(); Set mocks = newMockSafeHashSet(); @@ -87,6 +102,14 @@ public void injectMocks(final Object testClassInstance) { new DefaultInjectionEngine() .injectMocksOnFields(mockDependentFields, mocks, testClassInstance); + + return () -> { + for (Object mock : mocks) { + if (mock instanceof MockedStatic) { + ((MockedStatic) mock).closeOnDemand(); + } + } + }; } protected void onInjection( diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java index 2994f1c84e..c7f562a830 100644 --- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java +++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java @@ -4,11 +4,18 @@ */ package org.mockito.internal.configuration; +import static org.mockito.internal.util.StringUtil.join; + import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import org.mockito.Mock; import org.mockito.MockSettings; +import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.util.Supplier; /** * Instantiates a mock on a field annotated by {@link Mock} @@ -16,10 +23,12 @@ public class MockAnnotationProcessor implements FieldAnnotationProcessor { @Override public Object process(Mock annotation, Field field) { - return processAnnotationForMock(annotation, field.getType(), field.getName()); + return processAnnotationForMock( + annotation, field.getType(), field::getGenericType, field.getName()); } - public static Object processAnnotationForMock(Mock annotation, Class type, String name) { + public static Object processAnnotationForMock( + Mock annotation, Class type, Supplier genericType, String name) { MockSettings mockSettings = Mockito.withSettings(); if (annotation.extraInterfaces().length > 0) { // never null mockSettings.extraInterfaces(annotation.extraInterfaces()); @@ -41,6 +50,29 @@ public static Object processAnnotationForMock(Mock annotation, Class type, St // see @Mock answer default value mockSettings.defaultAnswer(annotation.answer()); - return Mockito.mock(type, mockSettings); + + if (type == MockedStatic.class) { + return Mockito.mockStatic(inferStaticMock(genericType.get(), name), mockSettings); + } else { + return Mockito.mock(type, mockSettings); + } + } + + private static Class inferStaticMock(Type type, String name) { + if (type instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) type; + return (Class) parameterizedType.getRawType(); + } else { + throw new MockitoException( + join( + "Mockito cannot infer a static mock from a raw type for " + name, + "", + "Instead of @Mock MockedStatic you need to specify a parameterized type", + "For example, if you would like to mock static methods of Sample.class, specify", + "", + "@Mock MockedStatic", + "", + "as the type parameter")); + } } } diff --git a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java index 27ebc4a04d..b4686b30d8 100644 --- a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java @@ -48,7 +48,7 @@ public class SpyAnnotationEngine implements AnnotationEngine, org.mockito.configuration.AnnotationEngine { @Override - public void process(Class context, Object testInstance) { + public AutoCloseable process(Class context, Object testInstance) { Field[] fields = context.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Spy.class) @@ -60,7 +60,7 @@ 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 + // for example happens when MockitoAnnotations.openMocks is called two // times. Mockito.reset(instance); } else if (instance != null) { @@ -78,6 +78,7 @@ public void process(Class context, Object testInstance) { } } } + return new NoAction(); } private static Object spyInstance(Field field, Object instance) { 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 34b8682a5c..cd8fcc5e3a 100644 --- a/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java +++ b/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java @@ -36,7 +36,7 @@ protected boolean processInjection(Field field, Object fieldOwner, Set m Object instance = fieldReader.read(); if (MockUtil.isMock(instance)) { // A. instance has been spied earlier - // B. protect against multiple use of MockitoAnnotations.initMocks() + // B. protect against multiple use of MockitoAnnotations.openMocks() Mockito.reset(instance); } else { Object mock = diff --git a/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java b/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java index dee7f45c06..da0321545d 100644 --- a/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java +++ b/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java @@ -21,6 +21,7 @@ import java.util.Set; import org.mockito.MockSettings; +import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.creation.settings.CreationSettings; import org.mockito.internal.debugging.VerboseMockInvocationLogger; import org.mockito.internal.util.Checks; @@ -231,6 +232,11 @@ public MockCreationSettings build(Class typeToMock) { return validatedSettings(typeToMock, (CreationSettings) this); } + @Override + public MockCreationSettings buildStatic(Class classToMock) { + return validatedStaticSettings(classToMock, (CreationSettings) this); + } + @Override public MockSettings lenient() { this.lenient = true; @@ -254,12 +260,34 @@ private static CreationSettings validatedSettings( // 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.setMockName(new MockNameImpl(source.getName(), typeToMock, false)); settings.setTypeToMock(typeToMock); settings.setExtraInterfaces(prepareExtraInterfaces(source)); return settings; } + private static CreationSettings validatedStaticSettings( + Class classToMock, CreationSettings source) { + + if (classToMock.isPrimitive()) { + throw new MockitoException( + "Cannot create static mock of primitive type " + classToMock); + } + if (!source.getExtraInterfaces().isEmpty()) { + throw new MockitoException( + "Cannot specify additional interfaces for static mock of " + classToMock); + } + if (source.getSpiedInstance() != null) { + throw new MockitoException( + "Cannot specify spied instance for static mock of " + classToMock); + } + + CreationSettings settings = new CreationSettings(source); + settings.setMockName(new MockNameImpl(source.getName(), classToMock, true)); + settings.setTypeToMock(classToMock); + return settings; + } + private static Set> prepareExtraInterfaces(CreationSettings settings) { Set> interfaces = new HashSet>(settings.getExtraInterfaces()); if (settings.isSerializable()) { diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java index 3b124dcaab..8ea513e2c6 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java @@ -45,4 +45,10 @@ public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings public TypeMockability isTypeMockable(Class type) { return defaultByteBuddyMockMaker.isTypeMockable(type); } + + @Override + public StaticMockControl createStaticMock( + Class type, MockCreationSettings settings, MockHandler handler) { + return defaultByteBuddyMockMaker.createStaticMock(type, settings, handler); + } } diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java index a131c04bc7..b87d7cb6b7 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java @@ -7,4 +7,6 @@ public interface BytecodeGenerator { Class mockClass(MockFeatures features); + + void mockClassStatic(Class type); } 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 d110451e3d..9bbe9ffee7 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -13,6 +13,9 @@ import java.io.InputStream; import java.lang.instrument.Instrumentation; import java.lang.reflect.Modifier; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -26,6 +29,7 @@ import org.mockito.exceptions.base.MockitoInitializationException; import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.Platform; +import org.mockito.internal.util.concurrent.DetachedThreadLocal; import org.mockito.internal.util.concurrent.WeakConcurrentMap; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; @@ -182,6 +186,9 @@ public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineM private final WeakConcurrentMap mocks = new WeakConcurrentMap.WithInlinedExpunction(); + private final DetachedThreadLocal, MockMethodInterceptor>> mockedStatics = + new DetachedThreadLocal<>(DetachedThreadLocal.Cleaner.INLINE); + public InlineByteBuddyMockMaker() { if (INITIALIZATION_ERROR != null) { throw new MockitoInitializationException( @@ -195,7 +202,7 @@ public InlineByteBuddyMockMaker() { } bytecodeGenerator = new TypeCachingBytecodeGenerator( - new InlineBytecodeGenerator(INSTRUMENTATION, mocks), true); + new InlineBytecodeGenerator(INSTRUMENTATION, mocks, mockedStatics), true); } @Override @@ -288,7 +295,13 @@ private RuntimeException prettifyFailure( @Override public MockHandler getHandler(Object mock) { - MockMethodInterceptor interceptor = mocks.get(mock); + MockMethodInterceptor interceptor; + if (mock instanceof Class) { + Map, MockMethodInterceptor> interceptors = mockedStatics.get(); + interceptor = interceptors != null ? interceptors.get(mock) : null; + } else { + interceptor = mocks.get(mock); + } if (interceptor == null) { return null; } else { @@ -300,19 +313,41 @@ public MockHandler getHandler(Object mock) { public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) { MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(newHandler, settings); - mocks.put(mock, mockMethodInterceptor); - if (mock instanceof MockAccess) { - ((MockAccess) mock).setMockitoInterceptor(mockMethodInterceptor); + if (mock instanceof Class) { + Map, MockMethodInterceptor> interceptors = mockedStatics.get(); + if (interceptors == null || !interceptors.containsKey(mock)) { + throw new MockitoException( + "Cannot reset " + + mock + + " which is not currently registered as a static mock"); + } + interceptors.put((Class) mock, mockMethodInterceptor); + } else { + if (!mocks.containsKey(mock)) { + throw new MockitoException( + "Cannot reset " + mock + " which is not currently registered as a mock"); + } + mocks.put(mock, mockMethodInterceptor); + if (mock instanceof MockAccess) { + ((MockAccess) mock).setMockitoInterceptor(mockMethodInterceptor); + } } } @Override public void clearMock(Object mock) { - mocks.remove(mock); + if (mock instanceof Class) { + for (Map, ?> entry : mockedStatics.getBackingMap().target.values()) { + entry.remove(mock); + } + } else { + mocks.remove(mock); + } } @Override public void clearAllMocks() { + mockedStatics.getBackingMap().clear(); mocks.clear(); } @@ -339,4 +374,79 @@ public String nonMockableReason() { } }; } + + @Override + public StaticMockControl createStaticMock( + Class type, MockCreationSettings settings, MockHandler handler) { + if (type == ConcurrentHashMap.class) { + throw new MockitoException( + "It is not possible to mock static methods of ConcurrentHashMap " + + "to avoid infinitive loops within Mockito's implementation of static mock handling"); + } + + bytecodeGenerator.mockClassStatic(type); + + Map, MockMethodInterceptor> interceptors = mockedStatics.get(); + if (interceptors == null) { + interceptors = new WeakHashMap<>(); + mockedStatics.set(interceptors); + } + + return new InlineStaticMockControl<>(type, interceptors, settings, handler); + } + + private static class InlineStaticMockControl implements StaticMockControl { + + private final Class type; + + private final Map, MockMethodInterceptor> interceptors; + + private final MockCreationSettings settings; + private final MockHandler handler; + + private InlineStaticMockControl( + Class type, + Map, MockMethodInterceptor> interceptors, + MockCreationSettings settings, + MockHandler handler) { + this.type = type; + this.interceptors = interceptors; + this.settings = settings; + this.handler = handler; + } + + @Override + public Class getType() { + return type; + } + + @Override + public void enable() { + if (interceptors.putIfAbsent(type, new MockMethodInterceptor(handler, settings)) + != null) { + throw new MockitoException( + join( + "For " + + type.getName() + + ", static mocking is already registered in the current thread", + "", + "To create a new mock, the existing static mock registration must be deregistered")); + } + } + + @Override + public void disable() { + if (interceptors.remove(type) == null) { + throw new MockitoException( + join( + "Could not deregister " + + type.getName() + + " as a static mock since it is not currently registered", + "", + "To register a static mock, use Mockito.mockStatic(" + + type.getSimpleName() + + ".class)")); + } + } + } } 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 dfca195b4d..187f1ea945 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -38,6 +38,7 @@ import net.bytebuddy.utility.RandomString; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher; +import org.mockito.internal.util.concurrent.DetachedThreadLocal; import org.mockito.internal.util.concurrent.WeakConcurrentMap; import org.mockito.internal.util.concurrent.WeakConcurrentSet; import org.mockito.mock.SerializableMode; @@ -63,7 +64,7 @@ public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTran private final Instrumentation instrumentation; private final ByteBuddy byteBuddy; - private final WeakConcurrentSet> mocked; + private final WeakConcurrentSet> mocked, flatMocked; private final BytecodeGenerator subclassEngine; private final AsmVisitorWrapper mockTransformer; @@ -73,7 +74,8 @@ public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTran public InlineBytecodeGenerator( Instrumentation instrumentation, - WeakConcurrentMap mocks) { + WeakConcurrentMap mocks, + DetachedThreadLocal, MockMethodInterceptor>> mockedStatics) { preload(); this.instrumentation = instrumentation; byteBuddy = @@ -81,7 +83,8 @@ public InlineBytecodeGenerator( .with(TypeValidation.DISABLED) .with(Implementation.Context.Disabled.Factory.INSTANCE) .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE); - mocked = new WeakConcurrentSet>(WeakConcurrentSet.Cleaner.INLINE); + mocked = new WeakConcurrentSet<>(WeakConcurrentSet.Cleaner.INLINE); + flatMocked = new WeakConcurrentSet<>(WeakConcurrentSet.Cleaner.INLINE); String identifier = RandomString.make(); subclassEngine = new TypeCachingBytecodeGenerator( @@ -110,6 +113,11 @@ public InlineBytecodeGenerator( Advice.withCustomMapping() .bind(MockMethodAdvice.Identifier.class, identifier) .to(MockMethodAdvice.class)) + .method( + isStatic(), + Advice.withCustomMapping() + .bind(MockMethodAdvice.Identifier.class, identifier) + .to(MockMethodAdvice.ForStatic.class)) .method( isHashCode(), Advice.withCustomMapping() @@ -141,7 +149,8 @@ public InlineBytecodeGenerator( this.getModule = getModule; this.canRead = canRead; this.redefineModule = redefineModule; - MockMethodDispatcher.set(identifier, new MockMethodAdvice(mocks, identifier)); + MockMethodDispatcher.set( + identifier, new MockMethodAdvice(mocks, mockedStatics, identifier)); instrumentation.addTransformer(this, true); } @@ -182,27 +191,46 @@ public Class mockClass(MockFeatures features) { checkSupportedCombination(subclassingRequired, features); + Set> types = new HashSet<>(); + types.add(features.mockedType); + types.addAll(features.interfaces); synchronized (this) { - triggerRetransformation(features); + triggerRetransformation(types, false); } return subclassingRequired ? subclassEngine.mockClass(features) : features.mockedType; } - private void triggerRetransformation(MockFeatures features) { - Set> types = new HashSet>(); - Class type = features.mockedType; - do { - if (mocked.add(type)) { - types.add(type); - addInterfaces(types, type.getInterfaces()); + @Override + public void mockClassStatic(Class type) { + triggerRetransformation(Collections.singleton(type), true); + } + + private void triggerRetransformation(Set> types, boolean flat) { + Set> targets = new HashSet>(); + + for (Class type : types) { + if (flat) { + if (!mocked.contains(type) && flatMocked.add(type)) { + targets.add(type); + } + } else { + do { + if (mocked.add(type)) { + if (!flatMocked.remove(type)) { + targets.add(type); + } + addInterfaces(targets, type.getInterfaces()); + } + type = type.getSuperclass(); + } while (type != null); } - type = type.getSuperclass(); - } while (type != null); - if (!types.isEmpty()) { + } + + if (!targets.isEmpty()) { try { - assureCanReadMockito(types); - instrumentation.retransformClasses(types.toArray(new Class[types.size()])); + assureCanReadMockito(targets); + instrumentation.retransformClasses(targets.toArray(new Class[targets.size()])); Throwable throwable = lastException; if (throwable != null) { throw new IllegalStateException( @@ -215,10 +243,11 @@ private void triggerRetransformation(MockFeatures features) { throwable); } } catch (Exception exception) { - for (Class failed : types) { + for (Class failed : targets) { mocked.remove(failed); + flatMocked.remove(failed); } - throw new MockitoException("Could not modify all classes " + types, exception); + throw new MockitoException("Could not modify all classes " + targets, exception); } finally { lastException = null; } @@ -281,7 +310,9 @@ private void checkSupportedCombination( private void addInterfaces(Set> types, Class[] interfaces) { for (Class type : interfaces) { if (mocked.add(type)) { - types.add(type); + if (!flatMocked.remove(type)) { + types.add(type); + } addInterfaces(types, type.getInterfaces()); } } @@ -296,6 +327,7 @@ public byte[] transform( byte[] classfileBuffer) { if (classBeingRedefined == null || !mocked.contains(classBeingRedefined) + && !flatMocked.contains(classBeingRedefined) || EXCLUDES.contains(classBeingRedefined)) { return null; } else { 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 87640a4441..072a958577 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -13,6 +13,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.Map; import java.util.concurrent.Callable; import net.bytebuddy.asm.Advice; @@ -30,11 +31,13 @@ import org.mockito.internal.invocation.SerializableMethod; import org.mockito.internal.invocation.mockref.MockReference; import org.mockito.internal.invocation.mockref.MockWeakReference; +import org.mockito.internal.util.concurrent.DetachedThreadLocal; import org.mockito.internal.util.concurrent.WeakConcurrentMap; public class MockMethodAdvice extends MockMethodDispatcher { private final WeakConcurrentMap interceptors; + private final DetachedThreadLocal, MockMethodInterceptor>> mockedStatics; private final String identifier; @@ -44,8 +47,11 @@ public class MockMethodAdvice extends MockMethodDispatcher { new WeakConcurrentMap.WithInlinedExpunction, SoftReference>(); public MockMethodAdvice( - WeakConcurrentMap interceptors, String identifier) { + WeakConcurrentMap interceptors, + DetachedThreadLocal, MockMethodInterceptor>> mockedStatics, + String identifier) { this.interceptors = interceptors; + this.mockedStatics = mockedStatics; this.identifier = identifier; } @@ -120,6 +126,24 @@ public Callable handle(Object instance, Method origin, Object[] arguments) th new LocationImpl(new Throwable(), true))); } + @Override + public Callable handleStatic(Class type, Method origin, Object[] arguments) + throws Throwable { + Map, MockMethodInterceptor> interceptors = mockedStatics.get(); + if (interceptors == null || !interceptors.containsKey(type)) { + return null; + } + return new ReturnValueWrapper( + interceptors + .get(type) + .doIntercept( + type, + origin, + arguments, + new StaticMethodCall(selfCallInfo, type, origin, arguments), + new LocationImpl(new Throwable(), true))); + } + @Override public boolean isMock(Object instance) { // We need to exclude 'interceptors.target' explicitly to avoid a recursive check on whether @@ -129,7 +153,16 @@ public boolean isMock(Object instance) { @Override public boolean isMocked(Object instance) { - return selfCallInfo.checkSuperCall(instance) && isMock(instance); + return selfCallInfo.checkSelfCall(instance) && isMock(instance); + } + + @Override + public boolean isMockedStatic(Class type) { + if (!selfCallInfo.checkSelfCall(type)) { + return false; + } + Map, ?> interceptors = mockedStatics.get(); + return interceptors != null && interceptors.containsKey(type); } @Override @@ -230,6 +263,39 @@ public Object invoke() throws Throwable { } } + private static class StaticMethodCall implements RealMethod { + + private final SelfCallInfo selfCallInfo; + + private final Class type; + + private final Method origin; + + private final Object[] arguments; + + private StaticMethodCall( + SelfCallInfo selfCallInfo, Class type, Method origin, Object[] arguments) { + this.selfCallInfo = selfCallInfo; + this.type = type; + this.origin = origin; + this.arguments = arguments; + } + + @Override + public boolean isInvokable() { + return true; + } + + @Override + public Object invoke() throws Throwable { + if (!Modifier.isPublic(type.getModifiers() & origin.getModifiers())) { + origin.setAccessible(true); + } + selfCallInfo.set(type); + return tryInvoke(origin, null, arguments); + } + } + private static Object tryInvoke(Method origin, Object instance, Object[] arguments) throws Throwable { try { @@ -268,7 +334,7 @@ Object replace(Object value) { return current; } - boolean checkSuperCall(Object value) { + boolean checkSelfCall(Object value) { if (value == get()) { set(null); return false; @@ -324,6 +390,36 @@ private static void enter( } } + static class ForStatic { + + @SuppressWarnings("unused") + @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class) + private static Callable enter( + @Identifier String identifier, + @Advice.Origin Class type, + @Advice.Origin Method origin, + @Advice.AllArguments Object[] arguments) + throws Throwable { + MockMethodDispatcher dispatcher = MockMethodDispatcher.getStatic(identifier, type); + if (dispatcher == null || !dispatcher.isMockedStatic(type)) { + return null; + } else { + return dispatcher.handleStatic(type, origin, arguments); + } + } + + @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 { + if (mocked != null) { + returned = mocked.call(); + } + } + } + public static class ForReadObject { @SuppressWarnings("unused") 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 f323f23d44..4a65643bc5 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java @@ -203,6 +203,11 @@ public Class mockClass(MockFeatures features) { .getLoaded(); } + @Override + public void mockClassStatic(Class type) { + throw new MockitoException("The subclass byte code generator cannot create static mocks"); + } + private Collection> getAllTypes(Class type) { Collection> supertypes = new LinkedList>(); supertypes.add(type); 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 18ca2423a6..76bf44dca8 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java @@ -57,6 +57,11 @@ public Class call() throws Exception { } } + @Override + public void mockClassStatic(Class type) { + bytecodeGenerator.mockClassStatic(type); + } + private static class MockitoMockKey extends TypeCache.SimpleKey { private final SerializableMode serializableMode; 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 6c077cfd9e..f1b49051e0 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,29 +11,42 @@ public abstract class MockMethodDispatcher { - private static final ConcurrentMap INSTANCE = - new ConcurrentHashMap(); + private static final ConcurrentMap DISPATCHERS = + 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 == DISPATCHERS) { + // Avoid endless loop if ConcurrentHashMap was redefined to check for being a mock. return null; } else { - return INSTANCE.get(identifier); + return DISPATCHERS.get(identifier); + } + } + + public static MockMethodDispatcher getStatic(String identifier, Class type) { + if (MockMethodDispatcher.class.isAssignableFrom(type) || type == ConcurrentHashMap.class) { + // Avoid endless loop for lookups of self. + return null; + } else { + return DISPATCHERS.get(identifier); } } public static void set(String identifier, MockMethodDispatcher dispatcher) { - INSTANCE.putIfAbsent(identifier, dispatcher); + DISPATCHERS.putIfAbsent(identifier, dispatcher); } public abstract Callable handle(Object instance, Method origin, Object[] arguments) throws Throwable; + public abstract Callable handleStatic(Class type, Method origin, Object[] arguments) + throws Throwable; + public abstract boolean isMock(Object instance); public abstract boolean isMocked(Object instance); + public abstract boolean isMockedStatic(Class type); + public abstract boolean isOverridden(Object instance, Method origin); } diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java index b491a7fd3a..0a182178d3 100644 --- a/src/main/java/org/mockito/internal/exceptions/Reporter.java +++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java @@ -147,7 +147,7 @@ public static MockitoException nullPassedToVerify() { " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();", " not: verify(mock.someMethod());", - "Also, if you use @Mock annotation don't miss initMocks()")); + "Also, if you use @Mock annotation don't miss openMocks()")); } public static MockitoException notAMockPassedToWhenMethod() { @@ -164,7 +164,7 @@ public static MockitoException nullPassedToWhenMethod() { "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()")); + "Also, if you use @Mock annotation don't miss openMocks()")); } public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() { @@ -740,7 +740,7 @@ public static MockitoException cannotInitializeForSpyAnnotation( "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();", + " //also, don't forget about MockitoAnnotations.openMocks();", ""), details); } diff --git a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java index 5e60099726..dfd5acce9c 100644 --- a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java +++ b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java @@ -4,11 +4,10 @@ */ package org.mockito.internal.framework; -import java.util.List; - import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.MockitoSession; +import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.RedundantListenerException; import org.mockito.internal.exceptions.Reporter; import org.mockito.internal.junit.TestFinishedEvent; @@ -16,11 +15,16 @@ import org.mockito.plugins.MockitoLogger; import org.mockito.quality.Strictness; +import java.util.ArrayList; +import java.util.List; + public class DefaultMockitoSession implements MockitoSession { private final String name; private final UniversalTestListener listener; + private final List closeables = new ArrayList<>(); + public DefaultMockitoSession( List testClassInstances, String name, @@ -36,10 +40,12 @@ public DefaultMockitoSession( } try { for (Object testClassInstance : testClassInstances) { - MockitoAnnotations.initMocks(testClassInstance); + closeables.add(MockitoAnnotations.openMocks(testClassInstance)); } } catch (RuntimeException e) { - // clean up in case 'initMocks' fails + release(); + + // clean up in case 'openMocks' fails listener.setListenerDirty(); throw e; } @@ -52,11 +58,15 @@ public void setStrictness(Strictness strictness) { @Override public void finishMocking() { + release(); + finishMocking(null); } @Override public void finishMocking(final Throwable failure) { + release(); + // 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 @@ -82,4 +92,14 @@ public String getTestName() { Mockito.validateMockitoUsage(); } } + + private void release() { + for (AutoCloseable closeable : closeables) { + try { + closeable.close(); + } catch (Exception e) { + throw new MockitoException("Failed to release mocks", e); + } + } + } } diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java index 4ef871dce5..57bb4b71e7 100644 --- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java +++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java @@ -123,18 +123,6 @@ public T getArgument(int index) { return (T) arguments[index]; } - public MockReference getMockRef() { - return mockRef; - } - - public MockitoMethod getMockitoMethod() { - return mockitoMethod; - } - - public RealMethod getRealMethod() { - return realMethod; - } - @Override public List getArgumentsAsMatchers() { return argumentsToMatchers(getArguments()); diff --git a/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java b/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java index fa065acd9c..a5c7687657 100644 --- a/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java +++ b/src/main/java/org/mockito/internal/junit/JUnitSessionStore.java @@ -26,6 +26,7 @@ class JUnitSessionStore { Statement createStatement(final Statement base, final String methodName, final Object target) { return new Statement() { public void evaluate() throws Throwable { + AutoCloseable closeable; if (session == null) { session = Mockito.mockitoSession() @@ -34,11 +35,15 @@ public void evaluate() throws Throwable { .logger(new MockitoSessionLoggerAdapter(logger)) .initMocks(target) .startMocking(); + closeable = null; } else { - MockitoAnnotations.initMocks(target); + closeable = MockitoAnnotations.openMocks(target); } Throwable testFailure = evaluateSafely(base); session.finishMocking(testFailure); + if (closeable != null) { + closeable.close(); + } if (testFailure != null) { throw testFailure; } diff --git a/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java b/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java index f81b01560b..d233cbe45d 100644 --- a/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java +++ b/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java @@ -40,14 +40,23 @@ protected Statement withBefores( return new Statement() { @Override public void evaluate() throws Throwable { + AutoCloseable closeable; 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); + closeable = MockitoAnnotations.openMocks(target); + } else { + closeable = null; + } + try { + base.evaluate(); + } finally { + if (closeable != null) { + closeable.close(); + } } - base.evaluate(); } }; } diff --git a/src/main/java/org/mockito/internal/util/MockNameImpl.java b/src/main/java/org/mockito/internal/util/MockNameImpl.java index a06975871d..ef0307fc11 100644 --- a/src/main/java/org/mockito/internal/util/MockNameImpl.java +++ b/src/main/java/org/mockito/internal/util/MockNameImpl.java @@ -15,9 +15,9 @@ public class MockNameImpl implements MockName, Serializable { private boolean defaultName; @SuppressWarnings("unchecked") - public MockNameImpl(String mockName, Class classToMock) { + public MockNameImpl(String mockName, Class type, boolean mockedStatic) { if (mockName == null) { - this.mockName = toInstanceName(classToMock); + this.mockName = mockedStatic ? toClassName(type) : toInstanceName(type); this.defaultName = true; } else { this.mockName = mockName; @@ -38,6 +38,15 @@ private static String toInstanceName(Class clazz) { return className.substring(0, 1).toLowerCase() + className.substring(1); } + private static String toClassName(Class clazz) { + String className = clazz.getSimpleName(); + if (className.length() == 0) { + // it's an anonymous class, let's get name from the parent + className = clazz.getSuperclass().getSimpleName() + "$"; + } + return className + ".class"; + } + public boolean isDefault() { return defaultName; } diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java index 7dec584f4e..4767ef9445 100644 --- a/src/main/java/org/mockito/internal/util/MockUtil.java +++ b/src/main/java/org/mockito/internal/util/MockUtil.java @@ -102,4 +102,10 @@ public static void maybeRedefineMockName(Object mock, String newName) { public static MockCreationSettings getMockSettings(Object mock) { return getMockHandler(mock).getMockSettings(); } + + public static MockMaker.StaticMockControl createStaticMock( + Class type, MockCreationSettings settings) { + MockHandler handler = createMockHandler(settings); + return mockMaker.createStaticMock(type, settings, handler); + } } 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 e9bc1cea2d..f3417c020e 100644 --- a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java +++ b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java @@ -53,7 +53,7 @@ public boolean contains(V value) { * @return {@code true} if the value is contained in the set. */ public boolean remove(V value) { - return target.remove(value); + return target.remove(value) != null; } /** diff --git a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java index 2c86bd0f15..3d2e8675e5 100644 --- a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java +++ b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java @@ -37,7 +37,7 @@ * To opt-out from this feature, use {@code}@RunWith(MockitoJUnitRunner.Silent.class){@code} *
  • * Initializes mocks annotated with {@link Mock}, - * so that explicit usage of {@link MockitoAnnotations#initMocks(Object)} is not necessary. + * so that explicit usage of {@link MockitoAnnotations#openMocks(Object)} is not necessary. * Mocks are initialized before each test method. *
  • * Validates framework usage after each test method. See javadoc for {@link Mockito#validateMockitoUsage()}. diff --git a/src/main/java/org/mockito/junit/MockitoRule.java b/src/main/java/org/mockito/junit/MockitoRule.java index 98de12ed10..276d7ce7e9 100644 --- a/src/main/java/org/mockito/junit/MockitoRule.java +++ b/src/main/java/org/mockito/junit/MockitoRule.java @@ -37,7 +37,7 @@ * See also {@link MockitoHint}. *
  • * Initializes mocks annotated with {@link org.mockito.Mock}, - * so that explicit usage of {@link MockitoAnnotations#initMocks(Object)} is not necessary. + * so that explicit usage of {@link MockitoAnnotations#openMocks(Object)} is not necessary. * Mocks are initialized before each test method. *
  • * Validates framework usage after each test method. See javadoc for {@link org.mockito.Mockito#validateMockitoUsage()}. diff --git a/src/main/java/org/mockito/plugins/AnnotationEngine.java b/src/main/java/org/mockito/plugins/AnnotationEngine.java index c60f477b9f..c6365e9f18 100644 --- a/src/main/java/org/mockito/plugins/AnnotationEngine.java +++ b/src/main/java/org/mockito/plugins/AnnotationEngine.java @@ -13,7 +13,7 @@ * or replace mockito default engine. * *

    - * If you are interested then see implementations or source code of {@link org.mockito.MockitoAnnotations#initMocks(Object)} + * If you are interested then see implementations or source code of {@link org.mockito.MockitoAnnotations#openMocks(Object)} * *

    This plugin mechanism supersedes the {@link org.mockito.configuration.IMockitoConfiguration} * in regard of switching mockito components. @@ -25,5 +25,11 @@ public interface AnnotationEngine { * @param clazz Class where to extract field information, check implementation for details * @param testInstance Test instance */ - void process(Class clazz, Object testInstance); + AutoCloseable process(Class clazz, Object testInstance); + + class NoAction implements AutoCloseable { + + @Override + public void close() {} + } } diff --git a/src/main/java/org/mockito/plugins/MockMaker.java b/src/main/java/org/mockito/plugins/MockMaker.java index f2798ed8bf..df3ff4210d 100644 --- a/src/main/java/org/mockito/plugins/MockMaker.java +++ b/src/main/java/org/mockito/plugins/MockMaker.java @@ -5,9 +5,12 @@ package org.mockito.plugins; import org.mockito.Incubating; +import org.mockito.exceptions.base.MockitoException; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; +import static org.mockito.internal.util.StringUtil.*; + /** * The facility to create mocks. * @@ -108,6 +111,36 @@ public interface MockMaker { @Incubating TypeMockability isTypeMockable(Class type); + /** + * If you want to provide your own implementation of {@code MockMaker} this method should: + *

      + *
    • Alter the supplied class to only change its behavior in the current thread.
    • + *
    • Only alters the static method's behavior after being enabled.
    • + *
    • Stops the altered behavior when disabled.
    • + *
    + * + * @param settings Mock creation settings like type to mock, extra interfaces and so on. + * @param handler See {@link org.mockito.invocation.MockHandler}. + * Do not provide your own implementation at this time. Make sure your implementation of + * {@link #getHandler(Object)} will return this instance. + * @param Type of the mock to return, actually the settings.getTypeToMock. + * @return A control for the static mock. + * @since 3.4.0 + */ + @Incubating + default StaticMockControl createStaticMock( + Class type, MockCreationSettings settings, MockHandler handler) { + throw new MockitoException( + join( + "The used MockMaker " + + getClass().getSimpleName() + + " does not support the creation of static mocks", + "", + "Mockito's inline mock maker supports static mocks based on the Instrumentation API.", + "You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.", + "Note that Mockito's inline mock maker is not supported on Android.")); + } + /** * Carries the mockability information * @@ -125,4 +158,14 @@ interface TypeMockability { */ String nonMockableReason(); } + + @Incubating + interface StaticMockControl { + + Class getType(); + + void enable(); + + void disable(); + } } diff --git a/src/main/java/org/mockito/session/MockitoSessionBuilder.java b/src/main/java/org/mockito/session/MockitoSessionBuilder.java index b17cfe77d6..648ca9d41e 100644 --- a/src/main/java/org/mockito/session/MockitoSessionBuilder.java +++ b/src/main/java/org/mockito/session/MockitoSessionBuilder.java @@ -26,10 +26,10 @@ public interface MockitoSessionBuilder { * like {@link org.mockito.Mock}. * When this method is invoked it does not perform initialization of mocks on the spot! * Only when {@link #startMocking()} is invoked then annotated fields will be initialized. - * Traditional API to initialize mocks, the {@link MockitoAnnotations#initMocks(Object)} method + * Traditional API to initialize mocks, the {@link MockitoAnnotations#openMocks(Object)} method * has limited support for driving cleaner tests because it does not support configuring {@link Strictness}. * Want cleaner tests and better productivity? - * Migrate from {@link MockitoAnnotations#initMocks(Object)} + * Migrate from {@link MockitoAnnotations#openMocks(Object)} * to {@link MockitoSession}! *

    * This method may be called multiple times to add multiple, e.g. nested, test class instances. diff --git a/src/test/java/org/mockito/MockitoTest.java b/src/test/java/org/mockito/MockitoTest.java index 008bf7f579..23df60e08e 100644 --- a/src/test/java/org/mockito/MockitoTest.java +++ b/src/test/java/org/mockito/MockitoTest.java @@ -11,6 +11,7 @@ import java.util.List; import org.junit.Test; +import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.exceptions.misusing.NullInsteadOfMockException; import org.mockito.internal.creation.MockSettingsImpl; @@ -64,6 +65,12 @@ public void shouldValidateMockWhenCreatingInOrderObject() { Mockito.inOrder("notMock"); } + @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) + @Test(expected = MockitoException.class) + public void shouldGiveExplantionOnStaticMockingWithoutInlineMockMaker() { + Mockito.mockStatic(Object.class); + } + @Test public void shouldStartingMockSettingsContainDefaultBehavior() { // when diff --git a/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java b/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java index 79d4fedd21..d5590ccfa6 100644 --- a/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java +++ b/src/test/java/org/mockito/internal/configuration/GlobalConfigurationTest.java @@ -59,6 +59,8 @@ public void reset_annotation_engine() { private static class CustomAnnotationEngine implements AnnotationEngine { @Override - public void process(Class clazz, Object testInstance) {} + public AutoCloseable process(Class clazz, Object testInstance) { + return new NoAction(); + } } } diff --git a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java index f79818db41..b199054e3f 100644 --- a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java +++ b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java @@ -38,7 +38,7 @@ public class DefaultMockingDetailsTest { @Before public void before() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test diff --git a/src/test/java/org/mockito/internal/util/MockNameImplTest.java b/src/test/java/org/mockito/internal/util/MockNameImplTest.java index e0bc019dc4..583bd7ac06 100644 --- a/src/test/java/org/mockito/internal/util/MockNameImplTest.java +++ b/src/test/java/org/mockito/internal/util/MockNameImplTest.java @@ -14,25 +14,51 @@ public class MockNameImplTest extends TestBase { @Test public void shouldProvideTheNameForClass() throws Exception { // when - String name = new MockNameImpl(null, SomeClass.class).toString(); + String name = new MockNameImpl(null, SomeClass.class, false).toString(); // then assertEquals("someClass", name); } + @Test + public void shouldProvideTheNameForClassOnStaticMock() throws Exception { + // when + String name = new MockNameImpl(null, SomeClass.class, true).toString(); + // then + assertEquals("SomeClass.class", name); + } + @Test public void shouldProvideTheNameForAnonymousClass() throws Exception { // given SomeInterface anonymousInstance = new SomeInterface() {}; // when - String name = new MockNameImpl(null, anonymousInstance.getClass()).toString(); + String name = new MockNameImpl(null, anonymousInstance.getClass(), false).toString(); // then assertEquals("someInterface", name); } + @Test + public void shouldProvideTheNameForAnonymousClassOnStatic() throws Exception { + // given + SomeInterface anonymousInstance = new SomeInterface() {}; + // when + String name = new MockNameImpl(null, anonymousInstance.getClass(), true).toString(); + // then + assertEquals("SomeInterface$.class", name); + } + @Test public void shouldProvideTheGivenName() throws Exception { // when - String name = new MockNameImpl("The Hulk", SomeClass.class).toString(); + String name = new MockNameImpl("The Hulk", SomeClass.class, false).toString(); + // then + assertEquals("The Hulk", name); + } + + @Test + public void shouldProvideTheGivenNameOnStatic() throws Exception { + // when + String name = new MockNameImpl("The Hulk", SomeClass.class, true).toString(); // then assertEquals("The Hulk", name); } diff --git a/src/test/java/org/mockito/internal/verification/DescriptionTest.java b/src/test/java/org/mockito/internal/verification/DescriptionTest.java index 5444ca342f..67904cbbbd 100644 --- a/src/test/java/org/mockito/internal/verification/DescriptionTest.java +++ b/src/test/java/org/mockito/internal/verification/DescriptionTest.java @@ -8,7 +8,7 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.MockitoAnnotations.openMocks; import org.junit.Before; import org.junit.Test; @@ -25,7 +25,7 @@ public class DescriptionTest { @Before public void setUp() { - initMocks(this); + openMocks(this); } /** diff --git a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java index e8bf2f80be..4200462f45 100644 --- a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java +++ b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java @@ -7,7 +7,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.MockitoAnnotations.openMocks; import org.junit.Before; import org.junit.Rule; @@ -26,7 +26,7 @@ public class VerificationOverTimeImplTest { @Before public void setUp() { - initMocks(this); + openMocks(this); impl = new VerificationOverTimeImpl(10, 1000, delegate, true); } diff --git a/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java b/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java index b188e8ffd2..36c7aacee1 100644 --- a/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java +++ b/src/test/java/org/mockito/internal/verification/VerificationWithDescriptionTest.java @@ -23,7 +23,7 @@ public class VerificationWithDescriptionTest { @Before public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test diff --git a/src/test/java/org/mockitousage/annotation/AnnotationsTest.java b/src/test/java/org/mockitousage/annotation/AnnotationsTest.java index 8ec83c1523..1a33f933b2 100644 --- a/src/test/java/org/mockitousage/annotation/AnnotationsTest.java +++ b/src/test/java/org/mockitousage/annotation/AnnotationsTest.java @@ -38,7 +38,7 @@ public class AnnotationsTest extends TestBase { @Before public void setup() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test @@ -55,7 +55,7 @@ public void shouldInitMocks() throws Exception { @Test public void shouldScreamWhenInitializingMocksForNullClass() throws Exception { try { - MockitoAnnotations.initMocks(null); + MockitoAnnotations.openMocks(null); fail(); } catch (MockitoException e) { assertEquals( @@ -67,7 +67,7 @@ public void shouldScreamWhenInitializingMocksForNullClass() throws Exception { @Test public void shouldLookForAnnotatedMocksInSuperClasses() throws Exception { Sub sub = new Sub(); - MockitoAnnotations.initMocks(sub); + MockitoAnnotations.openMocks(sub); assertNotNull(sub.getMock()); assertNotNull(sub.getBaseMock()); diff --git a/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java b/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java index 08480c202d..f015f1b358 100644 --- a/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java +++ b/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java @@ -43,7 +43,7 @@ public interface MockInterface { @Test public void testNormalUsage() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); // check if assigned correctly assertNotNull(finalCaptor); @@ -70,7 +70,7 @@ public static class WrongType { @Test public void shouldScreamWhenWrongTypeForCaptor() { try { - MockitoAnnotations.initMocks(new WrongType()); + MockitoAnnotations.openMocks(new WrongType()); fail(); } catch (MockitoException e) { } @@ -83,7 +83,7 @@ public static class ToManyAnnotations { @Test public void shouldScreamWhenMoreThanOneMockitoAnnotation() { try { - MockitoAnnotations.initMocks(new ToManyAnnotations()); + MockitoAnnotations.openMocks(new ToManyAnnotations()); fail(); } catch (MockitoException e) { assertThat(e) @@ -95,7 +95,7 @@ public void shouldScreamWhenMoreThanOneMockitoAnnotation() { @Test public void shouldScreamWhenInitializingCaptorsForNullClass() throws Exception { try { - MockitoAnnotations.initMocks(null); + MockitoAnnotations.openMocks(null); fail(); } catch (MockitoException e) { } @@ -104,7 +104,7 @@ public void shouldScreamWhenInitializingCaptorsForNullClass() throws Exception { @Test public void shouldLookForAnnotatedCaptorsInSuperClasses() throws Exception { Sub sub = new Sub(); - MockitoAnnotations.initMocks(sub); + MockitoAnnotations.openMocks(sub); assertNotNull(sub.getCaptor()); assertNotNull(sub.getBaseCaptor()); diff --git a/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java b/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java index ccc6184b67..f49de96cb9 100644 --- a/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java +++ b/src/test/java/org/mockitousage/annotation/CaptorAnnotationUnhappyPathTest.java @@ -30,7 +30,7 @@ public void init() { public void shouldFailIfCaptorHasWrongType() throws Exception { try { // when - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); fail(); } catch (MockitoException e) { // then diff --git a/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java b/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java index eb0bd896c1..a02434cdaf 100644 --- a/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java +++ b/src/test/java/org/mockitousage/annotation/DeprecatedAnnotationEngineApiTest.java @@ -47,7 +47,7 @@ public void shouldInjectMocksIfThereIsNoUserDefinedEngine() throws Exception { SimpleTestCase test = new SimpleTestCase(); // when - MockitoAnnotations.initMocks(test); + MockitoAnnotations.openMocks(test); // then assertNotNull(test.mock); @@ -65,7 +65,7 @@ public void shouldRespectUsersEngine() throws Exception { SimpleTestCase test = new SimpleTestCase(); // when - MockitoAnnotations.initMocks(test); + MockitoAnnotations.openMocks(test); // then assertNotNull(test.mock); diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java index 6d60a321fd..3a89fd3c67 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java @@ -7,7 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.MockitoAnnotations.openMocks; import java.util.AbstractCollection; import java.util.List; @@ -46,7 +46,7 @@ public class MockInjectionUsingConstructorTest { @Before public void before() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test @@ -91,7 +91,7 @@ public void should_report_failure_only_when_object_initialization_throws_excepti throws Exception { try { - MockitoAnnotations.initMocks(new ATest()); + MockitoAnnotations.openMocks(new ATest()); fail(); } catch (MockitoException e) { assertThat(e.getMessage()) @@ -147,7 +147,7 @@ class TestCase { exception.expectMessage( "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'IMethods' is an interface"); - initMocks(new TestCase()); + openMocks(new TestCase()); } @Test @@ -160,7 +160,7 @@ class TestCase { exception.expectMessage( "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'TimeUnit' is an enum"); - initMocks(new TestCase()); + openMocks(new TestCase()); } @Test @@ -173,7 +173,7 @@ class TestCase { exception.expectMessage( "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'AbstractCollection' is an abstract class"); - initMocks(new TestCase()); + openMocks(new TestCase()); } @Test @@ -188,7 +188,7 @@ class InnerClass {} exception.expectMessage( "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'InnerClass' is an inner non static class"); - initMocks(new TestCase()); + openMocks(new TestCase()); } static class StaticInnerClass {} @@ -200,7 +200,7 @@ class TestCase { } TestCase testClass = new TestCase(); - initMocks(testClass); + openMocks(testClass); assertThat(testClass.f).isInstanceOf(StaticInnerClass.class); } @@ -213,7 +213,7 @@ class TestCase { TestCase testClass = new TestCase(); StaticInnerClass original = testClass.f; - initMocks(testClass); + openMocks(testClass); 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 88a74a697e..765c4b8d0a 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java @@ -53,7 +53,7 @@ public class MockInjectionUsingSetterOrPropertyTest extends TestBase { @Before public void enforces_new_instances() { // initMocks called in TestBase Before method, so instances are not the same - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test @@ -81,40 +81,40 @@ public void should_initialize_spy_if_null_and_inject_mocks() { @Test public void should_inject_mocks_if_annotated() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); assertSame(list, superUnderTest.getAList()); } @Test public void should_not_inject_if_not_annotated() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); assertNull(superUnderTestWithoutInjection.getAList()); } @Test public void should_inject_mocks_for_class_hierarchy_if_annotated() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); assertSame(list, baseUnderTest.getAList()); assertSame(map, baseUnderTest.getAMap()); } @Test public void should_inject_mocks_by_name() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); assertSame(histogram1, subUnderTest.getHistogram1()); assertSame(histogram2, subUnderTest.getHistogram2()); } @Test public void should_inject_spies() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); assertSame(searchTree, otherBaseUnderTest.getSearchTree()); } @Test public void should_insert_into_field_with_matching_name_when_multiple_fields_of_same_type_exists_in_injectee() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); assertNull("not injected, no mock named 'candidate1'", hasTwoFieldsWithSameType.candidate1); assertNotNull( "injected, there's a mock named 'candidate2'", hasTwoFieldsWithSameType.candidate2); @@ -137,7 +137,7 @@ public void should_report_nicely() throws Exception { @InjectMocks ThrowingConstructor failingConstructor; }; try { - MockitoAnnotations.initMocks(failing); + MockitoAnnotations.openMocks(failing); fail(); } catch (MockitoException e) { Assertions.assertThat(e.getMessage()) diff --git a/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java b/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java index bd3bde79ce..60f87913bf 100644 --- a/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java +++ b/src/test/java/org/mockitousage/annotation/SpyAnnotationInitializedInBaseClassTest.java @@ -32,7 +32,7 @@ public void shouldInitSpiesInBaseClass() throws Exception { // given SubClass subClass = new SubClass(); // when - MockitoAnnotations.initMocks(subClass); + MockitoAnnotations.openMocks(subClass); // then assertTrue(MockUtil.isMock(subClass.list)); } @@ -45,7 +45,7 @@ public void init() { @Before public void before() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Spy List spyInBaseclass = new LinkedList(); diff --git a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java index 647b7c49bd..8db8ef1d5a 100644 --- a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java +++ b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java @@ -66,7 +66,7 @@ class WithSpy { } WithSpy withSpy = new WithSpy(); - MockitoAnnotations.initMocks(withSpy); + MockitoAnnotations.openMocks(withSpy); when(withSpy.list.size()).thenReturn(3); assertEquals(3, withSpy.list.size()); } @@ -79,7 +79,7 @@ class WithSpy { WithSpy withSpy = new WithSpy(); // when - MockitoAnnotations.initMocks(withSpy); + MockitoAnnotations.openMocks(withSpy); // then verify(withSpy.list, never()).clear(); @@ -92,7 +92,7 @@ class FailingSpy { } try { - MockitoAnnotations.initMocks(new FailingSpy()); + MockitoAnnotations.openMocks(new FailingSpy()); fail(); } catch (MockitoException e) { assertThat(e.getMessage()) @@ -109,7 +109,7 @@ class FailingSpy { } try { - MockitoAnnotations.initMocks(new FailingSpy()); + MockitoAnnotations.openMocks(new FailingSpy()); fail(); } catch (MockitoException e) { assertThat(e.getMessage()).contains("Unable to create mock instance"); @@ -128,7 +128,7 @@ List asSingletonList(String s) { } } SpyAbstractClass withSpy = new SpyAbstractClass(); - MockitoAnnotations.initMocks(withSpy); + MockitoAnnotations.openMocks(withSpy); assertEquals(Arrays.asList("a"), withSpy.asSingletonList("a")); } @@ -157,7 +157,7 @@ String fullStrength() { } } WithMockAndSpy outer = new WithMockAndSpy(); - MockitoAnnotations.initMocks(outer); + MockitoAnnotations.openMocks(outer); when(outer.strength.strength()).thenReturn("strength"); assertEquals("inner strength", outer.strength.fullStrength()); } @@ -176,7 +176,7 @@ class WithSpy { @Spy private Outer.Inner inner; } try { - MockitoAnnotations.initMocks(new WithSpy()); + MockitoAnnotations.openMocks(new WithSpy()); fail(); } catch (MockitoException e) { assertThat(e).hasMessageContaining("@Spy annotation can only initialize inner classes"); @@ -186,7 +186,7 @@ class WithSpy { @Test public void should_report_private_inner_not_supported() throws Exception { try { - MockitoAnnotations.initMocks(new WithInnerPrivate()); + MockitoAnnotations.openMocks(new WithInnerPrivate()); fail(); } catch (MockitoException e) { // Currently fails at instantiation time, because the mock subclass don't have the @@ -201,7 +201,7 @@ public void should_report_private_inner_not_supported() throws Exception { @Test public void should_report_private_abstract_inner_not_supported() throws Exception { try { - MockitoAnnotations.initMocks(new WithInnerPrivateAbstract()); + MockitoAnnotations.openMocks(new WithInnerPrivateAbstract()); fail(); } catch (MockitoException e) { assertThat(e) @@ -217,7 +217,7 @@ public void should_report_private_abstract_inner_not_supported() throws Exceptio @Test public void should_report_private_static_abstract_inner_not_supported() throws Exception { try { - MockitoAnnotations.initMocks(new WithInnerPrivateStaticAbstract()); + MockitoAnnotations.openMocks(new WithInnerPrivateStaticAbstract()); fail(); } catch (MockitoException e) { assertThat(e) diff --git a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java index b89c29cae6..f5bf525249 100644 --- a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java +++ b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java @@ -18,7 +18,7 @@ public class WrongSetOfAnnotationsTest extends TestBase { @Test(expected = MockitoException.class) public void should_not_allow_Mock_and_Spy() throws Exception { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @Mock @Spy List mock; }); @@ -27,7 +27,7 @@ public void should_not_allow_Mock_and_Spy() throws Exception { @Test public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exception { try { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @InjectMocks @Spy List mock; }); @@ -39,7 +39,7 @@ public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exceptio @Test public void should_allow_Spy_and_InjectMocks() throws Exception { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @InjectMocks @Spy WithDependency mock; }); @@ -51,7 +51,7 @@ static class WithDependency { @Test(expected = MockitoException.class) public void should_not_allow_Mock_and_InjectMocks() throws Exception { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @InjectMocks @Mock List mock; }); @@ -59,7 +59,7 @@ public void should_not_allow_Mock_and_InjectMocks() throws Exception { @Test(expected = MockitoException.class) public void should_not_allow_Captor_and_Mock() throws Exception { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @Mock @Captor ArgumentCaptor captor; }); @@ -67,7 +67,7 @@ public void should_not_allow_Captor_and_Mock() throws Exception { @Test(expected = MockitoException.class) public void should_not_allow_Captor_and_Spy() throws Exception { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @Spy @Captor ArgumentCaptor captor; }); @@ -75,7 +75,7 @@ public void should_not_allow_Captor_and_Spy() throws Exception { @Test(expected = MockitoException.class) public void should_not_allow_Captor_and_InjectMocks() throws Exception { - MockitoAnnotations.initMocks( + MockitoAnnotations.openMocks( new Object() { @InjectMocks @Captor ArgumentCaptor captor; }); diff --git a/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java b/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java index c2d1caa35b..749beeb35b 100644 --- a/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java +++ b/src/test/java/org/mockitousage/basicapi/MocksSerializationForAnnotationTest.java @@ -354,7 +354,7 @@ public static class TestClassThatHoldValidField { 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); + MockitoAnnotations.openMocks(testClass); serializeAndBack(testClass.serializableAndNoDefaultConstructor); } diff --git a/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java b/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java index 6553b975c8..a2569ccd63 100644 --- a/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java +++ b/src/test/java/org/mockitousage/bugs/FinalHashCodeAndEqualsRaiseNPEInInitMocksTest.java @@ -19,7 +19,7 @@ public class FinalHashCodeAndEqualsRaiseNPEInInitMocksTest { @Test public void dont_raise_NullPointerException() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } private static class FieldCharsetHolder { diff --git a/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java b/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java index 8f7a18e036..7c3f17ebf2 100644 --- a/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java +++ b/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java @@ -5,7 +5,7 @@ package org.mockitousage.bugs; import static org.mockito.BDDMockito.given; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.MockitoAnnotations.openMocks; import java.util.ArrayList; import java.util.Collection; @@ -37,6 +37,6 @@ , E> T getCollection(T collection) { @Before public void setUp() throws Exception { - initMocks(this); + openMocks(this); } } diff --git a/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java b/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java index 54de41089a..ccd14d9b29 100644 --- a/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java +++ b/src/test/java/org/mockitousage/bugs/creation/ConstructorInvokingMethodShouldNotRaiseExceptionTest.java @@ -20,7 +20,7 @@ public static class WithDumbMethod { @Test public void should_be_able_to_create_spy() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } private static class HasConstructorInvokingMethod { @@ -37,7 +37,7 @@ public static class UsingMethodObjectReferenceResult { @Test public void should_be_able_to_create_spy() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } private static class HasConstructorInvokingMethod { @@ -58,7 +58,7 @@ public static class UsingMethodPrimitiveResult { @Test public void should_be_able_to_create_spy() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } private static class HasConstructorInvokingMethod { diff --git a/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java b/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java index cf22301ffc..6c118808aa 100644 --- a/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java +++ b/src/test/java/org/mockitousage/bugs/injection/ParentTestMockInjectionTest.java @@ -19,7 +19,7 @@ public class ParentTestMockInjectionTest { @Test public void injectMocksShouldInjectMocksFromTestSuperClasses() { ImplicitTest it = new ImplicitTest(); - MockitoAnnotations.initMocks(it); + MockitoAnnotations.openMocks(it); assertNotNull(it.daoFromParent); assertNotNull(it.daoFromSub); @@ -40,7 +40,7 @@ public static class ImplicitTest extends BaseTest { @Before public void setup() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test diff --git a/src/test/java/org/mockitoutil/TestBase.java b/src/test/java/org/mockitoutil/TestBase.java index e35ea5b5b0..2fe89504e4 100644 --- a/src/test/java/org/mockitoutil/TestBase.java +++ b/src/test/java/org/mockitoutil/TestBase.java @@ -58,7 +58,7 @@ public void cleanUpConfigInAnyCase() { @Before public void init() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } public static void makeStackTracesClean() { diff --git a/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveType.java b/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveType.java index a076f2a0e7..f99c7eeb1b 100644 --- a/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveType.java +++ b/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveType.java @@ -12,7 +12,7 @@ import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; -import com.google.errorprone.matchers.method.MethodMatchers.MethodNameMatcher; +import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; @@ -42,7 +42,7 @@ public class MockitoAnyClassWithPrimitiveType extends AbstractMockitoAnyForPrimi }; // Match against the any() or any(Class) methods. - private static final MethodNameMatcher GENERIC_ANY = + private static final Matcher GENERIC_ANY = Matchers.staticMethod().onClassAny(CLASS_NAMES).named("any"); @Override diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java new file mode 100644 index 0000000000..2dde8d4a9b --- /dev/null +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitoinline; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.fail; +import static org.mockito.Mockito.times; + +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.exceptions.verification.NoInteractionsWanted; +import org.mockito.exceptions.verification.WantedButNotInvoked; + +public final class StaticMockTest { + + @Test + public void testStaticMockSimple() { + assertEquals("foo", Dummy.foo()); + try (MockedStatic ignored = Mockito.mockStatic(Dummy.class)) { + assertNull(Dummy.foo()); + } + assertEquals("foo", Dummy.foo()); + } + + @Test + public void testStaticMockWithVerification() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(Dummy::foo); + } + } + + @Test(expected = WantedButNotInvoked.class) + public void testStaticMockWithVerificationFailed() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.verify(Dummy::foo); + } + } + + @Test + public void testStaticMockWithMoInteractions() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + dummy.verifyNoInteractions(); + } + } + + @Test(expected = NoInteractionsWanted.class) + public void testStaticMockWithMoInteractionsFailed() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verifyNoInteractions(); + } + } + + @Test + public void testStaticMockWithMoMoreInteractions() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(Dummy::foo); + dummy.verifyNoMoreInteractions(); + } + } + + @Test(expected = NoInteractionsWanted.class) + public void testStaticMockWithMoMoreInteractionsFailed() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verifyNoMoreInteractions(); + } + } + + @Test + public void testStaticMockWithDefaultAnswer() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class, invocation -> "bar")) { + assertEquals("bar", Dummy.foo()); + dummy.verify(Dummy::foo); + } + } + + @Test + public void testStaticMockWithRealMethodCall() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenCallRealMethod(); + assertEquals("foo", Dummy.foo()); + dummy.verify(Dummy::foo); + } + } + + @Test + public void testStaticMockReset() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + dummy.reset(); + assertNull(Dummy.foo()); + } + } + + @Test + public void testStaticMockClear() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.clearInvocations(); + dummy.verifyNoInteractions(); + } + } + + @Test + public void testStaticMockDoesNotAffectDifferentThread() throws InterruptedException { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(Dummy::foo); + AtomicReference reference = new AtomicReference<>(); + Thread thread = new Thread(() -> reference.set(Dummy.foo())); + thread.start(); + thread.join(); + assertEquals("foo", reference.get()); + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(times(2), Dummy::foo); + } + } + + @Test + public void testStaticMockCanCoexistWithMockInDifferentThread() throws InterruptedException { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(Dummy::foo); + AtomicReference reference = new AtomicReference<>(); + Thread thread = new Thread(() -> { + try (MockedStatic dummy2 = Mockito.mockStatic(Dummy.class)) { + dummy2.when(Dummy::foo).thenReturn("qux"); + reference.set(Dummy.foo()); + } + }); + thread.start(); + thread.join(); + assertEquals("qux", reference.get()); + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(times(2), Dummy::foo); + } + } + + @Test(expected = MockitoException.class) + public void testStaticMockMustBeExclusiveInScopeWithinThread() { + try ( + MockedStatic dummy = Mockito.mockStatic(Dummy.class); + MockedStatic duplicate = Mockito.mockStatic(Dummy.class) + ) { + fail("Not supposed to allow duplicates"); + } + } + + static class Dummy { + + static String foo() { + return "foo"; + } + } +} diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java index 32609c38b4..c2cf37d5fe 100644 --- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java +++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java @@ -4,13 +4,14 @@ */ package org.mockito.junit.jupiter; - import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create; import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation; import java.lang.reflect.Parameter; +import java.util.HashSet; import java.util.List; import java.util.Optional; +import java.util.Set; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; @@ -20,6 +21,7 @@ import org.junit.jupiter.api.extension.ParameterResolutionException; import org.junit.jupiter.api.extension.ParameterResolver; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoSession; import org.mockito.internal.configuration.MockAnnotationProcessor; @@ -117,7 +119,7 @@ public class MockitoExtension implements BeforeEachCallback, AfterEachCallback, private final static Namespace MOCKITO = create("org.mockito"); - private final static String SESSION = "session"; + private final static String SESSION = "session", MOCKS = "mocks"; private final Strictness strictness; @@ -150,6 +152,7 @@ public void beforeEach(final ExtensionContext context) { .logger(new MockitoSessionLoggerAdapter(Plugins.getMockitoLogger())) .startMocking(); + context.getStore(MOCKITO).put(MOCKS, new HashSet<>()); context.getStore(MOCKITO).put(SESSION, session); } @@ -176,19 +179,30 @@ private Optional retrieveAnnotationFromTestClasses(final Extens * @param context the current extension context; never {@code null} */ @Override + @SuppressWarnings("unchecked") public void afterEach(ExtensionContext context) { + context.getStore(MOCKITO).remove(MOCKS, Set.class).forEach(mock -> ((MockedStatic) mock).closeOnDemand()); context.getStore(MOCKITO).remove(SESSION, MockitoSession.class) .finishMocking(context.getExecutionException().orElse(null)); } @Override - public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext context) throws ParameterResolutionException { return parameterContext.isAnnotated(Mock.class); } @Override - public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + @SuppressWarnings("unchecked") + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext context) throws ParameterResolutionException { final Parameter parameter = parameterContext.getParameter(); - return MockAnnotationProcessor.processAnnotationForMock(parameterContext.findAnnotation(Mock.class).get(), parameter.getType(), parameter.getName()); + Object mock = MockAnnotationProcessor.processAnnotationForMock( + parameterContext.findAnnotation(Mock.class).get(), + parameter.getType(), + parameter::getParameterizedType, + parameter.getName()); + if (mock instanceof MockedStatic) { + context.getStore(MOCKITO).get(MOCKS, Set.class).add(mock); + } + return mock; } } diff --git a/version.properties b/version.properties index de331257ca..08cb82acfe 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.3.13 +version=3.4.0 #Previous version used to generate release notes delta previousVersion=3.3.12 From bdd2b10ed5b02397614324d31449d8a58f03cf72 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Fri, 10 Jul 2020 21:04:28 +0200 Subject: [PATCH 048/963] Update src/main/java/org/mockito/Captor.java Co-authored-by: Tim van der Lippe --- src/main/java/org/mockito/Captor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/Captor.java b/src/main/java/org/mockito/Captor.java index 358f37ef0a..c0a042c8cd 100644 --- a/src/main/java/org/mockito/Captor.java +++ b/src/main/java/org/mockito/Captor.java @@ -19,7 +19,7 @@ * * @Before * public void open() { - * MockitoAnnotations.openMocks(this); + * closeable = MockitoAnnotations.openMocks(this); * } * * @After From 05b39bfc5e4558f4c1c6853d5b454f534bdfefe0 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Fri, 10 Jul 2020 19:38:11 +0000 Subject: [PATCH 049/963] 3.4.0 release (previous 3.3.12) + release notes updated by CI build 4577 [ci skip-release] --- doc/release-notes/official.md | 25 +++++++++++++++++++++++++ version.properties | 4 ++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 10ffc95186..681af51011 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,30 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.0 + - 2020-07-10 - [19 commits](https://github.com/mockito/mockito/compare/v3.3.12...v3.4.0) by 9 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.0) + - Commits: [Tim van der Lippe](https://github.com/TimvdLippe) (5), [Erhard Pointl](https://github.com/epeee) (4), [Rafael Winterhalter](https://github.com/raphw) (3), [Eitan Adler](https://github.com/grimreaper) (2), adrianriley (1), akluball (1), [Artem Prigoda](https://github.com/arteam) (1), [Jamie Tanna](https://github.com/jamietanna) (1), [Naoki Takezoe](https://github.com/takezoe) (1) + - [Android support] Enable mocking static methods in Mockito [(#1013)](https://github.com/mockito/mockito/issues/1013) + - Document using `@Mock` with method parameters [(#1961)](https://github.com/mockito/mockito/pull/1961) + - Documentation: `@Mock` on method parameters [(#1960)](https://github.com/mockito/mockito/issues/1960) + - Update errorprone gradle plugin to v1.2.1 [(#1958)](https://github.com/mockito/mockito/pull/1958) + - Update spotless Travis job name to be more descriptive [(#1957)](https://github.com/mockito/mockito/pull/1957) + - Fix a confusing typo in subclassing error message [(#1953)](https://github.com/mockito/mockito/pull/1953) + - Update bnd gradle plugin to v5.1.1 [(#1952)](https://github.com/mockito/mockito/pull/1952) + - Use errorprone 2.4.0 [(#1951)](https://github.com/mockito/mockito/pull/1951) + - Use jacoco v0.8.5 [(#1950)](https://github.com/mockito/mockito/pull/1950) + - Fixes #1712 : prepend description to AssertionError thrown in verification [(#1949)](https://github.com/mockito/mockito/pull/1949) + - Update gradle 6 [(#1948)](https://github.com/mockito/mockito/pull/1948) + - Move spotless check to separate build task [(#1946)](https://github.com/mockito/mockito/pull/1946) + - [Travis] Replace JDK 9/10 with 14 [(#1945)](https://github.com/mockito/mockito/pull/1945) + - Fixes #1898 : Return mock name from toString method for deep stub mocks [(#1942)](https://github.com/mockito/mockito/pull/1942) + - [checkstyle] switch to new DTD [(#1940)](https://github.com/mockito/mockito/pull/1940) + - Use google-java-format in spotless [(#1934)](https://github.com/mockito/mockito/pull/1934) + - Update report message to use any() instead of anyObject() [(#1931)](https://github.com/mockito/mockito/pull/1931) + - [build] bump gradle to latest 5.x release [(#1923)](https://github.com/mockito/mockito/pull/1923) + - [build] update gradle-errorprone-plugin to 1.1.0 [(#1908)](https://github.com/mockito/mockito/pull/1908) + - RETURNS_DEEP_STUBS override a mock's toString to `null` [(#1898)](https://github.com/mockito/mockito/issues/1898) + - "description" not printing when verify args don't match [(#1712)](https://github.com/mockito/mockito/issues/1712) + #### 3.3.12 - 2020-05-25 - [1 commit](https://github.com/mockito/mockito/compare/v3.3.11...v3.3.12) by [Vinicius Scheidegger](https://github.com/vinischeidegger) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.3.12-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.3.12) - Update javadoc - remove deprecated class [(#1938)](https://github.com/mockito/mockito/pull/1938) diff --git a/version.properties b/version.properties index 08cb82acfe..7b175e1bbc 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.0 +version=3.4.1 #Previous version used to generate release notes delta -previousVersion=3.3.12 +previousVersion=3.4.0 From eda22b7c8b4e2d6611d87f3c8f72f18c51bb2ed8 Mon Sep 17 00:00:00 2001 From: mickroll <9883575+mickroll@users.noreply.github.com> Date: Wed, 15 Jul 2020 14:52:46 +0200 Subject: [PATCH 050/963] Update byte buddy to 1.10.13 (#1973) Fixes #1972 Co-authored-by: Michael Kroll --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index bda27edc28..2de0a0008d 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -4,7 +4,7 @@ ext { def versions = [:] -versions.bytebuddy = '1.10.10' +versions.bytebuddy = '1.10.13' versions.junitJupiter = '5.4.2' versions.errorprone = '2.4.0' From b0aa37965d8432f77663e76d0f5698cb6ffb4d89 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Wed, 15 Jul 2020 12:58:42 +0000 Subject: [PATCH 051/963] 3.4.1 release (previous 3.4.0) + release notes updated by CI build 4593 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 681af51011..d1b7160deb 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.1 + - 2020-07-15 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.0...v3.4.1) by [mickroll](https://github.com/mickroll) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.1-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.1) + - update dependency to byte buddy version 1.10.13 [(#1973)](https://github.com/mockito/mockito/pull/1973) + - Update dependency to byte buddy version 1.10.13 [(#1972)](https://github.com/mockito/mockito/issues/1972) + #### 3.4.0 - 2020-07-10 - [19 commits](https://github.com/mockito/mockito/compare/v3.3.12...v3.4.0) by 9 authors - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.0) - Commits: [Tim van der Lippe](https://github.com/TimvdLippe) (5), [Erhard Pointl](https://github.com/epeee) (4), [Rafael Winterhalter](https://github.com/raphw) (3), [Eitan Adler](https://github.com/grimreaper) (2), adrianriley (1), akluball (1), [Artem Prigoda](https://github.com/arteam) (1), [Jamie Tanna](https://github.com/jamietanna) (1), [Naoki Takezoe](https://github.com/takezoe) (1) diff --git a/version.properties b/version.properties index 7b175e1bbc..ffc1330ceb 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.1 +version=3.4.2 #Previous version used to generate release notes delta -previousVersion=3.4.0 +previousVersion=3.4.1 From 9123d1e837c6740d53af3507b28686d2910ebee3 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Sun, 12 Jul 2020 00:03:23 +0200 Subject: [PATCH 052/963] Fixed \#1967: Correctly handle mocks with limited life-cycle in listeners. --- settings.gradle.kts | 3 +- src/main/java/org/mockito/MockedStatic.java | 10 +++ src/main/java/org/mockito/Mockito.java | 24 +++++++ .../mockito/internal/MockedStaticImpl.java | 10 +++ .../MockAnnotationProcessor.java | 30 +++++---- .../bytebuddy/InlineByteBuddyMockMaker.java | 7 +++ .../framework/DefaultMockitoSession.java | 62 ++++++++++--------- .../finder/AllInvocationsFinder.java | 6 ++ .../MockAnnotationProcessorTest.java | 49 +++++++++++++++ .../org/mockitoinline/StaticMockTest.java | 6 ++ ...terInlineMockMakerExtensionTest.gradle.kts | 25 ++++++++ .../java/org/mockitousage/NoExtendsTest.java | 25 ++++++++ .../org.junit.jupiter.api.extension.Extension | 1 + .../test/resources/junit-platform.properties | 1 + .../org.mockito.plugins.MockMaker | 1 + 15 files changed, 217 insertions(+), 43 deletions(-) create mode 100644 src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java create mode 100644 subprojects/junitJupiterInlineMockMakerExtensionTest/junitJupiterInlineMockMakerExtensionTest.gradle.kts create mode 100644 subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java create mode 100644 subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension create mode 100644 subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/junit-platform.properties create mode 100644 subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker diff --git a/settings.gradle.kts b/settings.gradle.kts index 5ece24a4b3..faef1b8d6e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -10,6 +10,7 @@ include("deprecatedPluginsTest", "android", "junit-jupiter", "junitJupiterExtensionTest", + "junitJupiterInlineMockMakerExtensionTest", "module-test", "memory-test", "errorprone", @@ -18,7 +19,7 @@ include("deprecatedPluginsTest", rootProject.name = "mockito" -val koltinBuildScriptProject = hashSetOf("junitJupiterExtensionTest") +val koltinBuildScriptProject = hashSetOf("junitJupiterExtensionTest", "junitJupiterInlineMockMakerExtensionTest") fun buildFileExtensionFor(projectName: String) = if (projectName in koltinBuildScriptProject) ".gradle.kts" else ".gradle" diff --git a/src/main/java/org/mockito/MockedStatic.java b/src/main/java/org/mockito/MockedStatic.java index 19ed5e944c..fc23c90776 100644 --- a/src/main/java/org/mockito/MockedStatic.java +++ b/src/main/java/org/mockito/MockedStatic.java @@ -63,6 +63,16 @@ default void verify(Verification verification) { */ void verifyNoInteractions(); + /** + * Checks if this mock is closed. + * + * @return {@code true} if this mock is closed. + */ + boolean isClosed(); + + /** + * Releases this static mock and throws a {@link org.mockito.exceptions.base.MockitoException} if closed already. + */ @Override void close(); diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 6ec7a81be9..c212897d59 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -2058,6 +2058,12 @@ public static T spy(Class classToSpy) { * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. *

    + * Note: We recommend against mocking static methods of classes in the standard library or + * classes used by custom class loaders used to executed the block with the mocked class. A mock + * maker might forbid mocking static methods of know classes that are known to cause problems. + * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not + * explicitly forbidden. + *

    * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. @@ -2074,6 +2080,12 @@ public static MockedStatic mockStatic(Class classToMock) { * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. *

    + * Note: We recommend against mocking static methods of classes in the standard library or + * classes used by custom class loaders used to executed the block with the mocked class. A mock + * maker might forbid mocking static methods of know classes that are known to cause problems. + * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not + * explicitly forbidden. + *

    * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. @@ -2091,6 +2103,12 @@ public static MockedStatic mockStatic(Class classToMock, Answer defaul * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. *

    + * Note: We recommend against mocking static methods of classes in the standard library or + * classes used by custom class loaders used to executed the block with the mocked class. A mock + * maker might forbid mocking static methods of know classes that are known to cause problems. + * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not + * explicitly forbidden. + *

    * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. @@ -2108,6 +2126,12 @@ public static MockedStatic mockStatic(Class classToMock, String name) * The returned object's {@link MockedStatic#close()} method must be called upon completing the * test or the mock will remain active on the current thread. *

    + * Note: We recommend against mocking static methods of classes in the standard library or + * classes used by custom class loaders used to executed the block with the mocked class. A mock + * maker might forbid mocking static methods of know classes that are known to cause problems. + * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not + * explicitly forbidden. + *

    * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface of which static mocks should be mocked. diff --git a/src/main/java/org/mockito/internal/MockedStaticImpl.java b/src/main/java/org/mockito/internal/MockedStaticImpl.java index 908b810be0..25434769e2 100644 --- a/src/main/java/org/mockito/internal/MockedStaticImpl.java +++ b/src/main/java/org/mockito/internal/MockedStaticImpl.java @@ -157,6 +157,11 @@ public void verifyNoInteractions() { noInteractions().verify(data); } + @Override + public boolean isClosed() { + return closed; + } + @Override public void close() { assertNotClosed(); @@ -181,4 +186,9 @@ private void assertNotClosed() { "is already resolved and cannot longer be used")); } } + + @Override + public String toString() { + return "static mock for " + control.getType().getTypeName(); + } } diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java index c7f562a830..48f0515a4b 100644 --- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java +++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java @@ -58,21 +58,25 @@ public static Object processAnnotationForMock( } } - private static Class inferStaticMock(Type type, String name) { + static Class inferStaticMock(Type type, String name) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; - return (Class) parameterizedType.getRawType(); - } else { - throw new MockitoException( - join( - "Mockito cannot infer a static mock from a raw type for " + name, - "", - "Instead of @Mock MockedStatic you need to specify a parameterized type", - "For example, if you would like to mock static methods of Sample.class, specify", - "", - "@Mock MockedStatic", - "", - "as the type parameter")); + Type[] arguments = parameterizedType.getActualTypeArguments(); + if (arguments.length == 1) { + if (arguments[0] instanceof Class) { + return (Class) arguments[0]; + } + } } + throw new MockitoException( + join( + "Mockito cannot infer a static mock from a raw type for " + name, + "", + "Instead of @Mock MockedStatic you need to specify a parameterized type", + "For example, if you would like to mock static methods of Sample.class, specify", + "", + "@Mock MockedStatic", + "", + "as the type parameter. If the type is parameterized, it should be specified as raw type.")); } } 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 9bbe9ffee7..89c1ac8622 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -382,6 +382,13 @@ public StaticMockControl createStaticMock( throw new MockitoException( "It is not possible to mock static methods of ConcurrentHashMap " + "to avoid infinitive loops within Mockito's implementation of static mock handling"); + } else if (type == Thread.class + || type == System.class + || ClassLoader.class.isAssignableFrom(type)) { + throw new MockitoException( + "It is not possible to mock static methods of " + + type.getTypeName() + + "to avoid interfering with the class loading mechanism"); } bytecodeGenerator.mockClassStatic(type); diff --git a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java index dfd5acce9c..549019d135 100644 --- a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java +++ b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java @@ -43,7 +43,11 @@ public DefaultMockitoSession( closeables.add(MockitoAnnotations.openMocks(testClassInstance)); } } catch (RuntimeException e) { - release(); + try { + release(); + } catch (Throwable t) { + e.addSuppressed(t); + } // clean up in case 'openMocks' fails listener.setListenerDirty(); @@ -58,38 +62,38 @@ public void setStrictness(Strictness strictness) { @Override public void finishMocking() { - release(); - finishMocking(null); } @Override public void finishMocking(final Throwable failure) { - release(); - - // 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; - } - }); - - // Validate only when there is no test failure to avoid reporting multiple problems - if (failure == null) { - // Finally, validate user's misuse of Mockito framework. - Mockito.validateMockitoUsage(); + try { + // 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; + } + }); + + // Validate only when there is no test failure to avoid reporting multiple problems + if (failure == null) { + // Finally, validate user's misuse of Mockito framework. + Mockito.validateMockitoUsage(); + } + } finally { + release(); } } @@ -98,7 +102,7 @@ private void release() { try { closeable.close(); } catch (Exception e) { - throw new MockitoException("Failed to release mocks", e); + throw new MockitoException("Failed to release " + closeable, e); } } } 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 ea9c6d63f4..9b43bbfb1c 100644 --- a/src/main/java/org/mockito/internal/invocation/finder/AllInvocationsFinder.java +++ b/src/main/java/org/mockito/internal/invocation/finder/AllInvocationsFinder.java @@ -42,6 +42,12 @@ public static List find(Iterable mocks) { public static Set findStubbings(Iterable mocks) { Set stubbings = new TreeSet(new StubbingComparator()); for (Object mock : mocks) { + // TODO due to the limited scope of static mocks they cannot be processed + // it would rather be required to trigger this stubbing control upon releasing + // the static mock. + if (mock instanceof Class) { + continue; + } Collection fromSingleMock = new DefaultMockingDetails(mock).getStubbings(); stubbings.addAll(fromSingleMock); diff --git a/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java b/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java new file mode 100644 index 0000000000..906d134d61 --- /dev/null +++ b/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.configuration; + +import java.util.List; + +import org.junit.Test; +import org.mockito.MockedStatic; +import org.mockito.exceptions.base.MockitoException; + +import static org.assertj.core.api.Assertions.*; + +public class MockAnnotationProcessorTest { + + @SuppressWarnings("unused") + private MockedStatic nonGeneric; + + @SuppressWarnings("unused") + private MockedStatic> generic; + + @SuppressWarnings({"raw", "unused"}) + private MockedStatic raw; + + @Test + public void testNonGeneric() throws Exception { + Class type = + MockAnnotationProcessor.inferStaticMock( + MockAnnotationProcessorTest.class + .getDeclaredField("nonGeneric") + .getGenericType(), + "nonGeneric"); + assertThat(type).isEqualTo(Void.class); + } + + @Test(expected = MockitoException.class) + public void testGeneric() throws Exception { + MockAnnotationProcessor.inferStaticMock( + MockAnnotationProcessorTest.class.getDeclaredField("generic").getGenericType(), + "generic"); + } + + @Test(expected = MockitoException.class) + public void testRaw() throws Exception { + MockAnnotationProcessor.inferStaticMock( + MockAnnotationProcessorTest.class.getDeclaredField("raw").getGenericType(), "raw"); + } +} diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java index 2dde8d4a9b..230e6773c0 100644 --- a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java @@ -11,15 +11,21 @@ import java.util.concurrent.atomic.AtomicReference; +import org.junit.Rule; import org.junit.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.WantedButNotInvoked; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; public final class StaticMockTest { + @Rule // Adding rule to assert properly managed life-cycle for static mocks + public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Test public void testStaticMockSimple() { assertEquals("foo", Dummy.foo()); diff --git a/subprojects/junitJupiterInlineMockMakerExtensionTest/junitJupiterInlineMockMakerExtensionTest.gradle.kts b/subprojects/junitJupiterInlineMockMakerExtensionTest/junitJupiterInlineMockMakerExtensionTest.gradle.kts new file mode 100644 index 0000000000..4bf7e47ee9 --- /dev/null +++ b/subprojects/junitJupiterInlineMockMakerExtensionTest/junitJupiterInlineMockMakerExtensionTest.gradle.kts @@ -0,0 +1,25 @@ +apply(from = "$rootDir/gradle/dependencies.gradle") + +plugins { + java +} + +description = "End-to-end tests for automatic registration of MockitoExtension with the inline mock maker." + +dependencies { + testCompile(project(":junit-jupiter")) + testCompile(library("assertj")) + testCompile(library("junitPlatformLauncher")) + testCompile(library("junitJupiterApi")) + testRuntime(library("junitJupiterEngine")) +} + +tasks.named("test") { + useJUnitPlatform() +} + +val Project.libraries + get() = rootProject.extra["libraries"] as Map + +fun Project.library(name: String) = + libraries[name]!! diff --git a/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java new file mode 100644 index 0000000000..57115fa979 --- /dev/null +++ b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2018 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitousage; + +import java.util.UUID; + +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockedStatic; + +import static org.assertj.core.api.Assertions.*; + +class NoExtendsTest { + + @Mock + private MockedStatic mock; + + @Test + void runs() { + mock.when(UUID::randomUUID).thenReturn(new UUID(123, 456)); + assertThat(UUID.randomUUID()).isEqualTo(new UUID(123, 456)); + } +} diff --git a/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension new file mode 100644 index 0000000000..02593efe36 --- /dev/null +++ b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension @@ -0,0 +1 @@ +org.mockito.junit.jupiter.MockitoExtension diff --git a/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/junit-platform.properties b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/junit-platform.properties new file mode 100644 index 0000000000..25ce5c9844 --- /dev/null +++ b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/junit-platform.properties @@ -0,0 +1 @@ +junit.jupiter.extensions.autodetection.enabled = true diff --git a/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000..1f0955d450 --- /dev/null +++ b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline From 6635deec58a7931745874d5d8c6034a7375fa15a Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 16 Jul 2020 18:42:01 +0000 Subject: [PATCH 053/963] 3.4.2 release (previous 3.4.1) + release notes updated by CI build 4597 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index d1b7160deb..13d501f49c 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.2 + - 2020-07-16 - [2 commits](https://github.com/mockito/mockito/compare/v3.4.1...v3.4.2) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.2-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.2) + - Fixes #1967: Correctly handle mocks with limited life-cycle in listeners. [(#1968)](https://github.com/mockito/mockito/pull/1968) + - Static method mocks incompatible with MockitoExtension (NotAMockException) [(#1967)](https://github.com/mockito/mockito/issues/1967) + #### 3.4.1 - 2020-07-15 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.0...v3.4.1) by [mickroll](https://github.com/mickroll) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.1-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.1) - update dependency to byte buddy version 1.10.13 [(#1973)](https://github.com/mockito/mockito/pull/1973) diff --git a/version.properties b/version.properties index ffc1330ceb..fcc5730b15 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.2 +version=3.4.3 #Previous version used to generate release notes delta -previousVersion=3.4.1 +previousVersion=3.4.2 From 4ebf513eb649ec5d1452fcce62ae5c32f2a44d96 Mon Sep 17 00:00:00 2001 From: Robert Chmielowiec Date: Fri, 17 Jul 2020 13:43:31 +0200 Subject: [PATCH 054/963] Fix invalid Javadoc syntax (#1978) Fixes #1977 [ci maven-central-release] --- src/main/java/org/mockito/Mockito.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index c212897d59..118eb2624d 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -457,8 +457,8 @@ * * private ArticleManager manager; * - * @org.junit.jupiter.api.Test - * void testSomethingInJunit5(@Mock ArticleDatabase database) { + * @org.junit.jupiter.api.Test + * void testSomethingInJunit5(@Mock ArticleDatabase database) { * * * Important! This needs to be somewhere in the base class or a test From cbabc53c2202a8ecc93dfa86f1405463181c2bdf Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Fri, 17 Jul 2020 11:49:56 +0000 Subject: [PATCH 055/963] 3.4.3 release (previous 3.4.2) + release notes updated by CI build 4625 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 13d501f49c..f44c66ad31 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.3 + - 2020-07-17 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.2...v3.4.3) by [Robert Chmielowiec](https://github.com/chmielowiec) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.3-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.3) + - Fix Javadoc invalid syntax [(#1978)](https://github.com/mockito/mockito/pull/1978) + - Broken documentation [(#1977)](https://github.com/mockito/mockito/issues/1977) + #### 3.4.2 - 2020-07-16 - [2 commits](https://github.com/mockito/mockito/compare/v3.4.1...v3.4.2) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.2-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.2) - Fixes #1967: Correctly handle mocks with limited life-cycle in listeners. [(#1968)](https://github.com/mockito/mockito/pull/1968) diff --git a/version.properties b/version.properties index fcc5730b15..943ba3ad2a 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.3 +version=3.4.4 #Previous version used to generate release notes delta -previousVersion=3.4.2 +previousVersion=3.4.3 From 12ba5936b736a2886220f9ae4a6492558dba4e14 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 16 Jul 2020 20:44:22 +0200 Subject: [PATCH 056/963] Fixes #1855 and #939: improve error message when the inline mock maker cannot be used. --- .../InjectingAnnotationEngine.java | 18 +++++++- .../bytebuddy/InlineByteBuddyMockMaker.java | 42 ++++++++++++++----- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java index 2f6667015c..59239a4674 100644 --- a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java @@ -58,7 +58,7 @@ private List processInjectMocks( List closeables = new ArrayList<>(); Class classContext = clazz; while (classContext != Object.class) { - closeables.add(injectMocks(testInstance)); + closeables.add(injectCloseableMocks(testInstance)); classContext = classContext.getSuperclass(); } return closeables; @@ -79,6 +79,20 @@ private List processIndependentAnnotations( return closeables; } + /** + * Required by PowerMockito and retained to avoid API breakage despite being internal API. + * + * @deprecated Use {@link InjectingAnnotationEngine#injectCloseableMocks(Object)}. + */ + @Deprecated + public void injectMocks(Object testClassInstance) { + try { + injectCloseableMocks(testClassInstance).close(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + /** * Initializes mock/spies dependencies for objects annotated with * @InjectMocks for given testClassInstance. @@ -88,7 +102,7 @@ private List processIndependentAnnotations( * @param testClassInstance * Test class, usually this */ - private AutoCloseable injectMocks(final Object testClassInstance) { + private AutoCloseable injectCloseableMocks(final Object testClassInstance) { Class clazz = testClassInstance.getClass(); Set mockDependentFields = new HashSet(); Set mocks = newMockSafeHashSet(); 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 89c1ac8622..097b8c8aae 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -4,15 +4,13 @@ */ package org.mockito.internal.creation.bytebuddy; -import static org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.EXCLUDES; -import static org.mockito.internal.util.StringUtil.join; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.Instrumentation; import java.lang.reflect.Modifier; +import java.util.Arrays; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; @@ -20,8 +18,6 @@ import java.util.jar.JarFile; import java.util.jar.JarOutputStream; -import javax.tools.ToolProvider; - import net.bytebuddy.agent.ByteBuddyAgent; import org.mockito.Incubating; import org.mockito.creation.instance.Instantiator; @@ -35,6 +31,9 @@ import org.mockito.mock.MockCreationSettings; import org.mockito.plugins.InlineMockMaker; +import static org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.*; +import static org.mockito.internal.util.StringUtil.*; + /** * Agent and subclass based mock maker. *

    @@ -191,12 +190,34 @@ public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineM public InlineByteBuddyMockMaker() { if (INITIALIZATION_ERROR != null) { + String detail; + if (System.getProperty("java.specification.vendor", "") + .toLowerCase() + .contains("android")) { + detail = + "It appears as if you are trying to run this mock maker on Android which does not support the instrumentation API."; + } else { + try { + if (Class.forName("javax.tools.ToolProvider") + .getMethod("getSystemJavaCompiler") + .invoke(null) + == null) { + detail = + "It appears as if you are running on a JRE. Either install a JDK or add JNA to the class path."; + } else { + detail = + "It appears as if your JDK does not supply a working agent attachment mechanism."; + } + } catch (Throwable ignored) { + detail = + "It appears as if you are running an incomplete JVM installation that might not support all tooling APIs"; + } + } 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" - : "", + "Could not initialize inline Byte Buddy mock maker.", + "", + detail, Platform.describe()), INITIALIZATION_ERROR); } @@ -384,11 +405,12 @@ public StaticMockControl createStaticMock( + "to avoid infinitive loops within Mockito's implementation of static mock handling"); } else if (type == Thread.class || type == System.class + || type == Arrays.class || ClassLoader.class.isAssignableFrom(type)) { throw new MockitoException( "It is not possible to mock static methods of " + type.getTypeName() - + "to avoid interfering with the class loading mechanism"); + + " to avoid interfering with class loading what leads to infinite loops"); } bytecodeGenerator.mockClassStatic(type); From 4019d86b4fb4078c53c7522dd41e5486ad560d35 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sat, 18 Jul 2020 18:54:50 +0000 Subject: [PATCH 057/963] 3.4.4 release (previous 3.4.3) + release notes updated by CI build 4637 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index f44c66ad31..65b4ab775d 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.4 + - 2020-07-18 - [2 commits](https://github.com/mockito/mockito/compare/v3.4.3...v3.4.4) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.4-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.4) + - Fixes #1855 and #939: improve error message when the inline mock maker cannot be used. [(#1974)](https://github.com/mockito/mockito/pull/1974) + - javax.tools.ToolProvider could not be found in InlineByteBuddyMockMaker [(#1855)](https://github.com/mockito/mockito/issues/1855) + #### 3.4.3 - 2020-07-17 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.2...v3.4.3) by [Robert Chmielowiec](https://github.com/chmielowiec) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.3-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.3) - Fix Javadoc invalid syntax [(#1978)](https://github.com/mockito/mockito/pull/1978) diff --git a/version.properties b/version.properties index 943ba3ad2a..b9ae327bd5 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.4 +version=3.4.5 #Previous version used to generate release notes delta -previousVersion=3.4.3 +previousVersion=3.4.4 From 361c39f82a7dad722bfb725bc12c581632a8f36c Mon Sep 17 00:00:00 2001 From: Erhard Pointl Date: Sun, 19 Jul 2020 12:09:55 +0200 Subject: [PATCH 058/963] Update assertj to 3.16.1 (#1982) see https://assertj.github.io/doc/#assertj-core-3-16-1-release-notes and https://assertj.github.io/doc/#assertj-core-3-16-0-release-notes for details --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 2de0a0008d..d089c4d73d 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -12,7 +12,7 @@ libraries.junit4 = 'junit:junit:4.12' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.1.0' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" -libraries.assertj = 'org.assertj:assertj-core:3.15.0' +libraries.assertj = 'org.assertj:assertj-core:3.16.1' libraries.hamcrest = 'org.hamcrest:hamcrest-core:1.3' libraries.opentest4j = 'org.opentest4j:opentest4j:1.1.1' From 98b0d901b5bb78d66bcd68b93d336be09a9ade00 Mon Sep 17 00:00:00 2001 From: Johnny Lim Date: Mon, 20 Jul 2020 15:47:40 +0900 Subject: [PATCH 059/963] Fix typo (#1984) --- src/main/java/org/mockito/AdditionalAnswers.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java index 684e5461ac..8df8d7188a 100644 --- a/src/main/java/org/mockito/AdditionalAnswers.java +++ b/src/main/java/org/mockito/AdditionalAnswers.java @@ -276,7 +276,7 @@ public static Answer returnsArgAt(int position) { * This feature suffers from the same drawback as the spy. * The mock will call the delegate if you use regular when().then() stubbing style. * Since the real implementation is called this might have some side effects. - * Therefore you should to use the doReturn|Throw|Answer|CallRealMethod stubbing style. Example: + * Therefore you should use the doReturn|Throw|Answer|CallRealMethod stubbing style. Example: * *

    
          *   List listWithDelegate = mock(List.class, AdditionalAnswers.delegatesTo(awesomeList));
    
    From c53f9b39243ac563cd40c774358fb0f7d4f2da83 Mon Sep 17 00:00:00 2001
    From: shipkit-org 
    Date: Mon, 20 Jul 2020 06:53:30 +0000
    Subject: [PATCH 060/963] 3.4.5 release (previous 3.4.4) + release notes
     updated by CI build 4647
    
    [ci skip-release]
    ---
     doc/release-notes/official.md | 5 +++++
     version.properties            | 4 ++--
     2 files changed, 7 insertions(+), 2 deletions(-)
    
    diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md
    index 65b4ab775d..c2fab42a75 100644
    --- a/doc/release-notes/official.md
    +++ b/doc/release-notes/official.md
    @@ -1,5 +1,10 @@
     *Release notes were automatically generated by [Shipkit](http://shipkit.org/)*
     
    +#### 3.4.5
    + - 2020-07-20 - [2 commits](https://github.com/mockito/mockito/compare/v3.4.4...v3.4.5) by [Erhard Pointl](https://github.com/epeee) (1), [Johnny Lim](https://github.com/izeye) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.5-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.5)
    + - Fix typo [(#1984)](https://github.com/mockito/mockito/pull/1984)
    + - Update assertj to 3.16.1 [(#1982)](https://github.com/mockito/mockito/pull/1982)
    +
     #### 3.4.4
      - 2020-07-18 - [2 commits](https://github.com/mockito/mockito/compare/v3.4.3...v3.4.4) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.4-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.4)
      - Fixes #1855 and #939: improve error message when the inline mock maker cannot be used. [(#1974)](https://github.com/mockito/mockito/pull/1974)
    diff --git a/version.properties b/version.properties
    index b9ae327bd5..d791b66192 100644
    --- a/version.properties
    +++ b/version.properties
    @@ -1,5 +1,5 @@
     #Currently building Mockito version
    -version=3.4.5
    +version=3.4.6
     
     #Previous version used to generate release notes delta
    -previousVersion=3.4.4
    +previousVersion=3.4.5
    
    From 0c56b3a8da97fa5ccfeef2adaa0a2314db3d6bd0 Mon Sep 17 00:00:00 2001
    From: Valery Yatsynovich 
    Date: Mon, 20 Jul 2020 16:08:21 +0300
    Subject: [PATCH 061/963] Fixes #1985 : update README to refer the latest
     documentation (#1986)
    
    ---
     README.md | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/README.md b/README.md
    index a69f94874a..12b36459aa 100644
    --- a/README.md
    +++ b/README.md
    @@ -27,7 +27,7 @@ The maintainers of org.mockito:mockito-core and thousands of other packages are
     
     ## Development
     
    -Mockito [continuously delivers](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview) improvements using Shipkit library (http://shipkit.org). See the [latest release notes](https://github.com/mockito/mockito/blob/release/3.x/doc/release-notes/official.md) and [latest documentation](http://javadoc.io/page/org.mockito/mockito-core/2/org/mockito/Mockito.html). Docs in javadoc.io are available 24h after release. Read also about [semantic versioning in Mockito](https://github.com/mockito/mockito/wiki/Semantic-Versioning). **Note: not every version is published to Maven Central.**
    +Mockito [continuously delivers](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview) improvements using Shipkit library (http://shipkit.org). See the [latest release notes](https://github.com/mockito/mockito/blob/release/3.x/doc/release-notes/official.md) and [latest documentation](http://javadoc.io/page/org.mockito/mockito-core/latest/org/mockito/Mockito.html). Docs in javadoc.io are available 24h after release. Read also about [semantic versioning in Mockito](https://github.com/mockito/mockito/wiki/Semantic-Versioning). **Note: not every version is published to Maven Central.**
     
     Older 1.x and 2.x releases are available in
     [Central Repository](http://search.maven.org/#artifactdetails|org.mockito|mockito-core|1.10.19|jar)
    
    From 724619b544096a5bdf488053865f5cccdba2fda1 Mon Sep 17 00:00:00 2001
    From: Rafael Winterhalter 
    Date: Tue, 28 Jul 2020 00:50:49 +0200
    Subject: [PATCH 062/963] Does not include static mocks in regular listener
     logic as it might distort existing mock collectors that do not expect scoped
     mocks. Fixes #1988.
    
    ---
     .../invocation/InterceptedInvocation.java     | 24 ++++++++++++++
     .../internal/progress/MockingProgress.java    |  2 ++
     .../progress/MockingProgressImpl.java         |  9 ++++++
     .../listeners/MockCreationListener.java       |  8 +++++
     .../org/mockitoinline/StaticMockTest.java     |  6 ----
     .../org/mockitoinline/StaticRuleTest.java     | 31 +++++++++++++++++++
     .../org/mockitoinline/StaticRunnerTest.java   | 28 +++++++++++++++++
     7 files changed, 102 insertions(+), 6 deletions(-)
     create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/StaticRuleTest.java
     create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/StaticRunnerTest.java
    
    diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
    index 57bb4b71e7..d0d842becc 100644
    --- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
    +++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
    @@ -141,6 +141,30 @@ public Object callRealMethod() throws Throwable {
             return realMethod.invoke();
         }
     
    +    /**
    +     * @deprecated Not used by Mockito but by mockito-scala
    +     */
    +    @Deprecated
    +    public MockReference getMockRef() {
    +        return mockRef;
    +    }
    +
    +    /**
    +     * @deprecated Not used by Mockito but by mockito-scala
    +     */
    +    @Deprecated
    +    public MockitoMethod getMockitoMethod() {
    +        return mockitoMethod;
    +    }
    +
    +    /**
    +     * @deprecated Not used by Mockito but by mockito-scala
    +     */
    +    @Deprecated
    +    public RealMethod getRealMethod() {
    +        return realMethod;
    +    }
    +
         @Override
         public int hashCode() {
             // TODO SF we need to provide hash code implementation so that there are no unexpected,
    diff --git a/src/main/java/org/mockito/internal/progress/MockingProgress.java b/src/main/java/org/mockito/internal/progress/MockingProgress.java
    index 9200c0845f..abdf68d83e 100644
    --- a/src/main/java/org/mockito/internal/progress/MockingProgress.java
    +++ b/src/main/java/org/mockito/internal/progress/MockingProgress.java
    @@ -43,6 +43,8 @@ public interface MockingProgress {
     
         void mockingStarted(Object mock, MockCreationSettings settings);
     
    +    void mockingStarted(Class mock, MockCreationSettings settings);
    +
         void addListener(MockitoListener listener);
     
         void removeListener(MockitoListener listener);
    diff --git a/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java b/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java
    index 58c126f842..07d411f046 100644
    --- a/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java
    +++ b/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java
    @@ -159,6 +159,15 @@ public void mockingStarted(Object mock, MockCreationSettings settings) {
             validateMostStuff();
         }
     
    +    public void mockingStarted(Class mock, MockCreationSettings settings) {
    +        for (MockitoListener listener : listeners) {
    +            if (listener instanceof MockCreationListener) {
    +                ((MockCreationListener) listener).onStaticMockCreated(mock, settings);
    +            }
    +        }
    +        validateMostStuff();
    +    }
    +
         public void addListener(MockitoListener listener) {
             addListener(listener, listeners);
         }
    diff --git a/src/main/java/org/mockito/listeners/MockCreationListener.java b/src/main/java/org/mockito/listeners/MockCreationListener.java
    index 24a1904aa7..7ab15f8236 100644
    --- a/src/main/java/org/mockito/listeners/MockCreationListener.java
    +++ b/src/main/java/org/mockito/listeners/MockCreationListener.java
    @@ -19,4 +19,12 @@ public interface MockCreationListener extends MockitoListener {
          * @param settings the settings used for creation
          */
         void onMockCreated(Object mock, MockCreationSettings settings);
    +
    +    /**
    +     * Static mock object was just created.
    +     *
    +     * @param mock the type being mocked
    +     * @param settings the settings used for creation
    +     */
    +    default void onStaticMockCreated(Class mock, MockCreationSettings settings) {}
     }
    diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java
    index 230e6773c0..2dde8d4a9b 100644
    --- a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java
    +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java
    @@ -11,21 +11,15 @@
     
     import java.util.concurrent.atomic.AtomicReference;
     
    -import org.junit.Rule;
     import org.junit.Test;
     import org.mockito.MockedStatic;
     import org.mockito.Mockito;
     import org.mockito.exceptions.base.MockitoException;
     import org.mockito.exceptions.verification.NoInteractionsWanted;
     import org.mockito.exceptions.verification.WantedButNotInvoked;
    -import org.mockito.junit.MockitoJUnit;
    -import org.mockito.junit.MockitoRule;
     
     public final class StaticMockTest {
     
    -    @Rule // Adding rule to assert properly managed life-cycle for static mocks
    -    public MockitoRule mockitoRule = MockitoJUnit.rule();
    -
         @Test
         public void testStaticMockSimple() {
             assertEquals("foo", Dummy.foo());
    diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticRuleTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticRuleTest.java
    new file mode 100644
    index 0000000000..68b9c6a616
    --- /dev/null
    +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticRuleTest.java
    @@ -0,0 +1,31 @@
    +/*
    + * Copyright (c) 2018 Mockito contributors
    + * This program is made available under the terms of the MIT License.
    + */
    +package org.mockitoinline;
    +
    +import org.junit.Rule;
    +import org.junit.Test;
    +import org.mockito.Mock;
    +import org.mockito.MockedStatic;
    +import org.mockito.junit.MockitoJUnit;
    +import org.mockito.junit.MockitoRule;
    +
    +import java.util.UUID;
    +
    +import static junit.framework.TestCase.assertEquals;
    +
    +public final class StaticRuleTest {
    +
    +    @Rule
    +    public MockitoRule mockitoRule = MockitoJUnit.rule();
    +
    +    @Mock
    +    private MockedStatic mock;
    +
    +    @Test
    +    public void runs() {
    +        mock.when(UUID::randomUUID).thenReturn(new UUID(123, 456));
    +        assertEquals(UUID.randomUUID(), new UUID(123, 456));
    +    }
    +}
    diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticRunnerTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticRunnerTest.java
    new file mode 100644
    index 0000000000..e0159597f7
    --- /dev/null
    +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticRunnerTest.java
    @@ -0,0 +1,28 @@
    +/*
    + * Copyright (c) 2018 Mockito contributors
    + * This program is made available under the terms of the MIT License.
    + */
    +package org.mockitoinline;
    +
    +import org.junit.Test;
    +import org.junit.runner.RunWith;
    +import org.mockito.Mock;
    +import org.mockito.MockedStatic;
    +import org.mockito.junit.MockitoJUnitRunner;
    +
    +import java.util.UUID;
    +
    +import static junit.framework.TestCase.assertEquals;
    +
    +@RunWith(MockitoJUnitRunner.class)
    +public final class StaticRunnerTest {
    +
    +    @Mock
    +    private MockedStatic mock;
    +
    +    @Test
    +    public void runs() {
    +        mock.when(UUID::randomUUID).thenReturn(new UUID(123, 456));
    +        assertEquals(UUID.randomUUID(), new UUID(123, 456));
    +    }
    +}
    
    From 019830665f97c8ba6159148e3b10086cfb894900 Mon Sep 17 00:00:00 2001
    From: shipkit-org 
    Date: Wed, 29 Jul 2020 15:28:28 +0000
    Subject: [PATCH 063/963] 3.4.6 release (previous 3.4.5) + release notes
     updated by CI build 4660
    
    [ci skip-release]
    ---
     doc/release-notes/official.md | 7 +++++++
     version.properties            | 4 ++--
     2 files changed, 9 insertions(+), 2 deletions(-)
    
    diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md
    index c2fab42a75..d77f5673d5 100644
    --- a/doc/release-notes/official.md
    +++ b/doc/release-notes/official.md
    @@ -1,5 +1,12 @@
     *Release notes were automatically generated by [Shipkit](http://shipkit.org/)*
     
    +#### 3.4.6
    + - 2020-07-29 - [3 commits](https://github.com/mockito/mockito/compare/v3.4.5...v3.4.6) by [Rafael Winterhalter](https://github.com/raphw) (2), [Valery Yatsynovich](https://github.com/valfirst) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.6-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.6)
    + - [Bugfixes] Do not pass static mocks to regular listener callback. [(#1989)](https://github.com/mockito/mockito/pull/1989)
    + - MockitoJUnitRunner causes NPE when using @Mock on MockedStatic fields [(#1988)](https://github.com/mockito/mockito/issues/1988)
    + - Fixes #1985 : Update README to refer the latest documentation [(#1986)](https://github.com/mockito/mockito/pull/1986)
    + - README should refer the latest available documentation [(#1985)](https://github.com/mockito/mockito/issues/1985)
    +
     #### 3.4.5
      - 2020-07-20 - [2 commits](https://github.com/mockito/mockito/compare/v3.4.4...v3.4.5) by [Erhard Pointl](https://github.com/epeee) (1), [Johnny Lim](https://github.com/izeye) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.5-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.5)
      - Fix typo [(#1984)](https://github.com/mockito/mockito/pull/1984)
    diff --git a/version.properties b/version.properties
    index d791b66192..cb6eb619b2 100644
    --- a/version.properties
    +++ b/version.properties
    @@ -1,5 +1,5 @@
     #Currently building Mockito version
    -version=3.4.6
    +version=3.4.7
     
     #Previous version used to generate release notes delta
    -previousVersion=3.4.5
    +previousVersion=3.4.6
    
    From 106ebcfac809c578b128cf909e7f3f344f87ee69 Mon Sep 17 00:00:00 2001
    From: Rafael Winterhalter 
    Date: Mon, 13 Jul 2020 22:52:12 +0200
    Subject: [PATCH 064/963] Add support for creating constructors without using
     Objenesis (and unsafe API)
    
    ---
     .../instance/InstantiationException.java      |   7 +
     .../bytebuddy/InlineByteBuddyMockMaker.java   |  80 +++++++++-
     .../bytebuddy/InlineBytecodeGenerator.java    |   8 +-
     .../creation/bytebuddy/MockMethodAdvice.java  | 151 +++++++++++++++++-
     .../inject/MockMethodDispatcher.java          |   7 +
     .../InlineByteBuddyMockMakerTest.java         |  21 +++
     6 files changed, 267 insertions(+), 7 deletions(-)
    
    diff --git a/src/main/java/org/mockito/creation/instance/InstantiationException.java b/src/main/java/org/mockito/creation/instance/InstantiationException.java
    index 1cfbaba23f..34548d5eb8 100644
    --- a/src/main/java/org/mockito/creation/instance/InstantiationException.java
    +++ b/src/main/java/org/mockito/creation/instance/InstantiationException.java
    @@ -13,6 +13,13 @@
      */
     public class InstantiationException extends MockitoException {
     
    +    /**
    +     * @since 3.5.0
    +     */
    +    public InstantiationException(String message) {
    +        super(message);
    +    }
    +
         /**
          * @since 2.15.4
          */
    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 097b8c8aae..4b679d194e 100644
    --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
    +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
    @@ -9,6 +9,7 @@
     import java.io.IOException;
     import java.io.InputStream;
     import java.lang.instrument.Instrumentation;
    +import java.lang.reflect.Constructor;
     import java.lang.reflect.Modifier;
     import java.util.Arrays;
     import java.util.Map;
    @@ -20,6 +21,7 @@
     
     import net.bytebuddy.agent.ByteBuddyAgent;
     import org.mockito.Incubating;
    +import org.mockito.creation.instance.InstantiationException;
     import org.mockito.creation.instance.Instantiator;
     import org.mockito.exceptions.base.MockitoException;
     import org.mockito.exceptions.base.MockitoInitializationException;
    @@ -93,7 +95,8 @@
      * support this feature.
      */
     @Incubating
    -public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineMockMaker {
    +public class InlineByteBuddyMockMaker
    +        implements ClassCreatingMockMaker, InlineMockMaker, Instantiator {
     
         private static final Instrumentation INSTRUMENTATION;
     
    @@ -188,6 +191,8 @@ public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineM
         private final DetachedThreadLocal, MockMethodInterceptor>> mockedStatics =
                 new DetachedThreadLocal<>(DetachedThreadLocal.Cleaner.INLINE);
     
    +    private final ThreadLocal mockConstruction = ThreadLocal.withInitial(() -> false);
    +
         public InlineByteBuddyMockMaker() {
             if (INITIALIZATION_ERROR != null) {
                 String detail;
    @@ -223,16 +228,25 @@ public InlineByteBuddyMockMaker() {
             }
             bytecodeGenerator =
                     new TypeCachingBytecodeGenerator(
    -                        new InlineBytecodeGenerator(INSTRUMENTATION, mocks, mockedStatics), true);
    +                        new InlineBytecodeGenerator(
    +                                INSTRUMENTATION, mocks, mockedStatics, mockConstruction::get),
    +                        true);
         }
     
         @Override
         public  T createMock(MockCreationSettings settings, MockHandler handler) {
             Class type = createMockType(settings);
     
    -        Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(settings);
             try {
    -            T instance = instantiator.newInstance(type);
    +            T instance;
    +            try {
    +                // We attempt to use the "native" mock maker first that avoids Objenesis and Unsafe
    +                instance = newInstance(type);
    +            } catch (InstantiationException ignored) {
    +                Instantiator instantiator =
    +                        Plugins.getInstantiatorProvider().getInstantiator(settings);
    +                instance = instantiator.newInstance(type);
    +            }
                 MockMethodInterceptor mockMethodInterceptor =
                         new MockMethodInterceptor(handler, settings);
                 mocks.put(instance, mockMethodInterceptor);
    @@ -424,6 +438,64 @@ public  StaticMockControl createStaticMock(
             return new InlineStaticMockControl<>(type, interceptors, settings, handler);
         }
     
    +    @Override
    +    @SuppressWarnings("unchecked")
    +    public  T newInstance(Class cls) throws InstantiationException {
    +        Constructor[] constructors = cls.getDeclaredConstructors();
    +        if (constructors.length == 0) {
    +            throw new InstantiationException(cls.getTypeName() + " does not define a constructor");
    +        }
    +        Constructor selected = constructors[0];
    +        for (Constructor constructor : constructors) {
    +            if (Modifier.isPublic(constructor.getModifiers())) {
    +                selected = constructor;
    +                break;
    +            }
    +        }
    +        Class[] types = selected.getParameterTypes();
    +        Object[] arguments = new Object[types.length];
    +        int index = 0;
    +        for (Class type : types) {
    +            arguments[index++] = makeStandardArgument(type);
    +        }
    +        try {
    +            if (!Modifier.isPublic(selected.getModifiers())
    +                    || !Modifier.isPublic(cls.getModifiers())) {
    +                selected.setAccessible(true);
    +            }
    +            mockConstruction.set(true);
    +            try {
    +                return (T) selected.newInstance(arguments);
    +            } finally {
    +                mockConstruction.set(false);
    +            }
    +        } catch (Exception e) {
    +            throw new InstantiationException("Could not instantiate " + cls.getTypeName(), e);
    +        }
    +    }
    +
    +    private Object makeStandardArgument(Class type) {
    +        if (type == boolean.class) {
    +            return false;
    +        } else if (type == byte.class) {
    +            return (byte) 0;
    +        } else if (type == short.class) {
    +            return (short) 0;
    +        } else if (type == char.class) {
    +            return (char) 0;
    +        } else if (type == int.class) {
    +            return 0;
    +        } else if (type == long.class) {
    +            return 0L;
    +        } else if (type == float.class) {
    +            return 0f;
    +        } else if (type == double.class) {
    +            return 0d;
    +        } else {
    +            return null;
    +        }
    +    }
    +
         private static class InlineStaticMockControl implements StaticMockControl {
     
             private final Class type;
    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 187f1ea945..47e1de07df 100644
    --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
    +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
    @@ -15,6 +15,7 @@
     import java.lang.reflect.Modifier;
     import java.security.ProtectionDomain;
     import java.util.*;
    +import java.util.function.BooleanSupplier;
     
     import net.bytebuddy.ByteBuddy;
     import net.bytebuddy.ClassFileVersion;
    @@ -75,7 +76,8 @@ public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTran
         public InlineBytecodeGenerator(
                 Instrumentation instrumentation,
                 WeakConcurrentMap mocks,
    -            DetachedThreadLocal, MockMethodInterceptor>> mockedStatics) {
    +            DetachedThreadLocal, MockMethodInterceptor>> mockedStatics,
    +            BooleanSupplier isMockConstruction) {
             preload();
             this.instrumentation = instrumentation;
             byteBuddy =
    @@ -118,6 +120,7 @@ public InlineBytecodeGenerator(
                                     Advice.withCustomMapping()
                                             .bind(MockMethodAdvice.Identifier.class, identifier)
                                             .to(MockMethodAdvice.ForStatic.class))
    +                        .constructor(any(), new MockMethodAdvice.ConstructorShortcut(identifier))
                             .method(
                                     isHashCode(),
                                     Advice.withCustomMapping()
    @@ -150,7 +153,8 @@ public InlineBytecodeGenerator(
             this.canRead = canRead;
             this.redefineModule = redefineModule;
             MockMethodDispatcher.set(
    -                identifier, new MockMethodAdvice(mocks, mockedStatics, identifier));
    +                identifier,
    +                new MockMethodAdvice(mocks, mockedStatics, identifier, isMockConstruction));
             instrumentation.addTransformer(this, true);
         }
     
    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 072a958577..1c37cc4243 100644
    --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
    +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
    @@ -15,14 +15,25 @@
     import java.lang.reflect.Modifier;
     import java.util.Map;
     import java.util.concurrent.Callable;
    +import java.util.function.BooleanSupplier;
     
    +import net.bytebuddy.ClassFileVersion;
     import net.bytebuddy.asm.Advice;
    +import net.bytebuddy.asm.AsmVisitorWrapper;
     import net.bytebuddy.description.method.MethodDescription;
    +import net.bytebuddy.description.method.MethodList;
     import net.bytebuddy.description.type.TypeDescription;
     import net.bytebuddy.dynamic.scaffold.MethodGraph;
    +import net.bytebuddy.implementation.Implementation;
     import net.bytebuddy.implementation.bind.annotation.Argument;
     import net.bytebuddy.implementation.bind.annotation.This;
     import net.bytebuddy.implementation.bytecode.assign.Assigner;
    +import net.bytebuddy.jar.asm.Label;
    +import net.bytebuddy.jar.asm.MethodVisitor;
    +import net.bytebuddy.jar.asm.Opcodes;
    +import net.bytebuddy.jar.asm.Type;
    +import net.bytebuddy.pool.TypePool;
    +import net.bytebuddy.utility.OpenedClassReader;
     import org.mockito.exceptions.base.MockitoException;
     import org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher;
     import org.mockito.internal.debugging.LocationImpl;
    @@ -34,6 +45,8 @@
     import org.mockito.internal.util.concurrent.DetachedThreadLocal;
     import org.mockito.internal.util.concurrent.WeakConcurrentMap;
     
    +import static net.bytebuddy.matcher.ElementMatchers.*;
    +
     public class MockMethodAdvice extends MockMethodDispatcher {
     
         private final WeakConcurrentMap interceptors;
    @@ -46,13 +59,17 @@ public class MockMethodAdvice extends MockMethodDispatcher {
         private final WeakConcurrentMap, SoftReference> graphs =
                 new WeakConcurrentMap.WithInlinedExpunction, SoftReference>();
     
    +    private final BooleanSupplier isMockConstruction;
    +
         public MockMethodAdvice(
                 WeakConcurrentMap interceptors,
                 DetachedThreadLocal, MockMethodInterceptor>> mockedStatics,
    -            String identifier) {
    +            String identifier,
    +            BooleanSupplier isMockConstruction) {
             this.interceptors = interceptors;
             this.mockedStatics = mockedStatics;
             this.identifier = identifier;
    +        this.isMockConstruction = isMockConstruction;
         }
     
         @SuppressWarnings("unused")
    @@ -183,6 +200,11 @@ public boolean isOverridden(Object instance, Method origin) {
                             .represents(origin.getDeclaringClass());
         }
     
    +    @Override
    +    public boolean isConstructorMock(Class type) {
    +        return isMockConstruction.getAsBoolean();
    +    }
    +
         private static class RealMethodCall implements RealMethod {
     
             private final SelfCallInfo selfCallInfo;
    @@ -344,6 +366,133 @@ boolean checkSelfCall(Object value) {
             }
         }
     
    +    static class ConstructorShortcut
    +            implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper {
    +
    +        private final String identifier;
    +
    +        ConstructorShortcut(String identifier) {
    +            this.identifier = identifier;
    +        }
    +
    +        @Override
    +        public MethodVisitor wrap(
    +                TypeDescription instrumentedType,
    +                MethodDescription instrumentedMethod,
    +                MethodVisitor methodVisitor,
    +                Implementation.Context implementationContext,
    +                TypePool typePool,
    +                int writerFlags,
    +                int readerFlags) {
    +            if (instrumentedMethod.isConstructor() && !instrumentedType.represents(Object.class)) {
    +                MethodList constructors =
    +                        instrumentedType
    +                                .getSuperClass()
    +                                .asErasure()
    +                                .getDeclaredMethods()
    +                                .filter(isConstructor().and(not(isPrivate())));
    +                int arguments = Integer.MAX_VALUE;
    +                boolean visible = false;
    +                MethodDescription.InDefinedShape current = null;
    +                for (MethodDescription.InDefinedShape constructor : constructors) {
    +                    if (constructor.getParameters().size() < arguments
    +                            && (!visible || constructor.isPackagePrivate())) {
    +                        current = constructor;
    +                        visible = constructor.isPackagePrivate();
    +                    }
    +                }
    +                if (current != null) {
    +                    final MethodDescription.InDefinedShape selected = current;
    +                    return new MethodVisitor(OpenedClassReader.ASM_API, methodVisitor) {
    +                        @Override
    +                        public void visitCode() {
    +                            super.visitCode();
    +                            /*
    +                             * The byte code that is added to the start of the method is roughly equivalent to:
    +                             *
    +                             * if (MockMethodDispatcher.isConstructorMock(, Current.class) {
    +                             *   super();
    +                             *   return;
    +                             * }
    +                             *
    +                             * This avoids the invocation of the original constructor chain but fullfils the
    +                             * verifier requirement to invoke a super constructor.
    +                             */
    +                            Label label = new Label();
    +                            super.visitLdcInsn(identifier);
    +                            if (implementationContext
    +                                    .getClassFileVersion()
    +                                    .isAtLeast(ClassFileVersion.JAVA_V5)) {
    +                                super.visitLdcInsn(Type.getType(instrumentedType.getDescriptor()));
    +                            } else {
    +                                super.visitLdcInsn(instrumentedType.getName());
    +                                super.visitMethodInsn(
    +                                        Opcodes.INVOKESTATIC,
    +                                        Type.getInternalName(Class.class),
    +                                        "forName",
    +                                        Type.getMethodDescriptor(
    +                                                Type.getType(Class.class),
    +                                                Type.getType(String.class)),
    +                                        false);
    +                            }
    +                            super.visitMethodInsn(
    +                                    Opcodes.INVOKESTATIC,
    +                                    Type.getInternalName(MockMethodDispatcher.class),
    +                                    "isConstructorMock",
    +                                    Type.getMethodDescriptor(
    +                                            Type.BOOLEAN_TYPE,
    +                                            Type.getType(String.class),
    +                                            Type.getType(Class.class)),
    +                                    false);
    +                            super.visitInsn(Opcodes.ICONST_0);
    +                            super.visitJumpInsn(Opcodes.IF_ICMPEQ, label);
    +                            super.visitVarInsn(Opcodes.ALOAD, 0);
    +                            for (TypeDescription type :
    +                                    selected.getParameters().asTypeList().asErasures()) {
    +                                if (type.represents(boolean.class)
    +                                        || type.represents(byte.class)
    +                                        || type.represents(short.class)
    +                                        || type.represents(char.class)
    +                                        || type.represents(int.class)) {
    +                                    super.visitInsn(Opcodes.ICONST_0);
    +                                } else if (type.represents(long.class)) {
    +                                    super.visitInsn(Opcodes.LCONST_0);
    +                                } else if (type.represents(float.class)) {
    +                                    super.visitInsn(Opcodes.FCONST_0);
    +                                } else if (type.represents(double.class)) {
    +                                    super.visitInsn(Opcodes.DCONST_0);
    +                                } else {
    +                                    super.visitInsn(Opcodes.ACONST_NULL);
    +                                }
    +                            }
    +                            super.visitMethodInsn(
    +                                    Opcodes.INVOKESPECIAL,
    +                                    selected.getDeclaringType().getInternalName(),
    +                                    selected.getInternalName(),
    +                                    selected.getDescriptor(),
    +                                    false);
    +                            super.visitInsn(Opcodes.RETURN);
    +                            super.visitLabel(label);
    +                            if (implementationContext
    +                                    .getClassFileVersion()
    +                                    .isAtLeast(ClassFileVersion.JAVA_V6)) {
    +                                super.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    +                            }
    +                        }
    +
    +                        @Override
    +                        public void visitMaxs(int maxStack, int maxLocals) {
    +                            super.visitMaxs(
    +                                    Math.max(maxStack, Math.max(3, selected.getStackSize())),
    +                                    maxLocals);
    +                        }
    +                    };
    +                }
    +            }
    +            return methodVisitor;
    +        }
    +    }
    +
         @Retention(RetentionPolicy.RUNTIME)
         @interface Identifier {}
     
    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 f1b49051e0..0ab2feda39 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
    @@ -36,6 +36,11 @@ public static void set(String identifier, MockMethodDispatcher dispatcher) {
             DISPATCHERS.putIfAbsent(identifier, dispatcher);
         }
     
    +    @SuppressWarnings("unused")
    +    public static boolean isConstructorMock(String identifier, Class type) {
    +        return DISPATCHERS.get(identifier).isConstructorMock(type);
    +    }
    +
         public abstract Callable handle(Object instance, Method origin, Object[] arguments)
                 throws Throwable;
     
    @@ -49,4 +54,6 @@ public abstract Callable handleStatic(Class type, Method origin, Object[]
         public abstract boolean isMockedStatic(Class type);
     
         public abstract boolean isOverridden(Object instance, Method origin);
    +
    +    public abstract boolean isConstructorMock(Class type);
     }
    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 8ec5318748..07208c8a4a 100644
    --- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
    +++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
    @@ -57,6 +57,16 @@ public void should_create_mock_from_final_class() throws Exception {
             assertThat(proxy.foo()).isEqualTo("bar");
         }
     
    +    @Test
    +    public void should_create_mock_from_non_constructable_class() throws Exception {
    +        MockCreationSettings settings =
    +                settingsFor(NonConstructableClass.class);
    +        NonConstructableClass proxy =
    +                mockMaker.createMock(
    +                        settings, new MockHandlerImpl(settings));
    +        assertThat(proxy.foo()).isEqualTo("bar");
    +    }
    +
         @Test
         public void should_create_mock_from_final_class_in_the_JDK() throws Exception {
             MockCreationSettings settings = settingsFor(Pattern.class);
    @@ -406,6 +416,17 @@ public String foo() {
             }
         }
     
    +    private static class NonConstructableClass {
    +
    +        private NonConstructableClass() {
    +            throw new AssertionError();
    +        }
    +
    +        public String foo() {
    +            return "foo";
    +        }
    +    }
    +
         private enum EnumClass {
             INSTANCE;
     
    
    From 7155af23bf298ee508de48abe7391825e30f8fa3 Mon Sep 17 00:00:00 2001
    From: Per Lundberg 
    Date: Wed, 5 Aug 2020 23:05:39 +0300
    Subject: [PATCH 065/963] Mockito.verify(): fix typo in Javadoc (#1991)
    
    ---
     src/main/java/org/mockito/Mockito.java | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
    index 118eb2624d..6f6560d2c2 100644
    --- a/src/main/java/org/mockito/Mockito.java
    +++ b/src/main/java/org/mockito/Mockito.java
    @@ -2227,7 +2227,7 @@ public static  OngoingStubbing when(T methodCall) {
          * Although it is possible to verify a stubbed invocation, usually it's just redundant.
          * Let's say you've stubbed foo.bar().
          * If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed).
    -     * If your code doesn't care what get(0) returns then it should not be stubbed.
    +     * If your code doesn't care what foo.bar() returns then it should not be stubbed.
          *
          * 

    * See examples in javadoc for {@link Mockito} class From b87fad310bf59b94035028dc478089ded2a9198a Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Wed, 5 Aug 2020 20:12:27 +0000 Subject: [PATCH 066/963] 3.4.7 release (previous 3.4.6) + release notes updated by CI build 4667 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index d77f5673d5..ba22aa4309 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.7 + - 2020-08-05 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.6...v3.4.7) by [Per Lundberg](https://github.com/perlun) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.7-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.7) + - Mockito.verify(): fix typo in Javadoc [(#1991)](https://github.com/mockito/mockito/pull/1991) + #### 3.4.6 - 2020-07-29 - [3 commits](https://github.com/mockito/mockito/compare/v3.4.5...v3.4.6) by [Rafael Winterhalter](https://github.com/raphw) (2), [Valery Yatsynovich](https://github.com/valfirst) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.6-green.svg)](https://bintray.com/mockito/maven/mockito/3.4.6) - [Bugfixes] Do not pass static mocks to regular listener callback. [(#1989)](https://github.com/mockito/mockito/pull/1989) diff --git a/version.properties b/version.properties index cb6eb619b2..ffaa369fd0 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.7 +version=3.4.8 #Previous version used to generate release notes delta -previousVersion=3.4.6 +previousVersion=3.4.7 From 32684d1acd6df8f1d143827a16ef5de5e4dc4d6a Mon Sep 17 00:00:00 2001 From: Erhard Pointl Date: Sun, 9 Aug 2020 13:35:33 +0200 Subject: [PATCH 067/963] Update objenesis to 3.1 (#1998) Release notes: http://objenesis.org/notes.html --- gradle/dependencies.gradle | 3 +-- gradle/mockito-core/osgi.gradle | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index d089c4d73d..9ae3679927 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -25,8 +25,7 @@ libraries.errorproneTestApi = "com.google.errorprone:error_prone_test_helpers:${ libraries.autoservice = "com.google.auto.service:auto-service:1.0-rc5" -// objenesis 3.x with full Java 11 support requires Java 8, bump version when Java 7 support is dropped -libraries.objenesis = 'org.objenesis:objenesis:2.6' +libraries.objenesis = 'org.objenesis:objenesis:3.1' libraries.asm = 'org.ow2.asm:asm:7.0' diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle index 41f1902b45..a18942589d 100644 --- a/gradle/mockito-core/osgi.gradle +++ b/gradle/mockito-core/osgi.gradle @@ -22,7 +22,7 @@ jar { 'junit.*;resolution:=optional', 'org.junit.*;resolution:=optional', 'org.hamcrest;resolution:=optional', - 'org.objenesis;version="[2.5,3.0)"', + 'org.objenesis;version="[3.1,4.0)"', 'org.opentest4j.*;resolution:=optional', 'org.mockito.*' ].join(','), From ce8cc9847a4c2a9f51da935ac31b491fb8f2d9c1 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sun, 9 Aug 2020 11:41:23 +0000 Subject: [PATCH 068/963] 3.4.8 release (previous 3.4.7) + release notes updated by CI build 4685 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index ba22aa4309..e5ca6a4ee9 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.4.8 + - 2020-08-09 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.7...v3.4.8) by [Erhard Pointl](https://github.com/epeee) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.8-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.8) + - Update objenesis to 3.1 [(#1998)](https://github.com/mockito/mockito/pull/1998) + #### 3.4.7 - 2020-08-05 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.6...v3.4.7) by [Per Lundberg](https://github.com/perlun) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.7-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.7) - Mockito.verify(): fix typo in Javadoc [(#1991)](https://github.com/mockito/mockito/pull/1991) diff --git a/version.properties b/version.properties index ffaa369fd0..3cb4008653 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.8 +version=3.4.9 #Previous version used to generate release notes delta -previousVersion=3.4.7 +previousVersion=3.4.8 From 12ce7ea57a721f146a2b7c8f69d45b8b7f349531 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 16 Jul 2020 22:43:04 +0200 Subject: [PATCH 069/963] Implements mocking for constructor invocations. --- .../java/org/mockito/MockedConstruction.java | 40 +++ src/main/java/org/mockito/MockedStatic.java | 20 +- src/main/java/org/mockito/Mockito.java | 188 ++++++++++++- src/main/java/org/mockito/ScopedMock.java | 31 +++ .../internal/MockedConstructionImpl.java | 64 +++++ .../mockito/internal/MockedStaticImpl.java | 17 -- .../org/mockito/internal/MockitoCore.java | 53 ++-- .../IndependentAnnotationEngine.java | 16 +- .../InjectingAnnotationEngine.java | 6 +- .../MockAnnotationProcessor.java | 21 +- .../bytebuddy/ByteBuddyMockMaker.java | 13 + .../creation/bytebuddy/BytecodeGenerator.java | 2 + .../bytebuddy/ConstructionCallback.java | 10 + .../bytebuddy/InlineByteBuddyMockMaker.java | 260 +++++++++++++++++- .../bytebuddy/InlineBytecodeGenerator.java | 31 ++- .../creation/bytebuddy/MockMethodAdvice.java | 108 +++++++- .../bytebuddy/SubclassBytecodeGenerator.java | 6 + .../TypeCachingBytecodeGenerator.java | 5 + .../inject/MockMethodDispatcher.java | 12 + .../org/mockito/internal/util/MockUtil.java | 17 +- .../java/org/mockito/plugins/MockMaker.java | 51 +++- src/test/java/org/mockito/MockitoTest.java | 6 + .../MockAnnotationProcessorTest.java | 16 +- .../ConstructionMockRuleTest.java | 43 +++ .../mockitoinline/ConstructionMockTest.java | 144 ++++++++++ .../org/mockitoinline/StaticMockRuleTest.java | 42 +++ .../java/org/mockitousage/NoExtendsTest.java | 29 +- version.properties | 2 +- 28 files changed, 1127 insertions(+), 126 deletions(-) create mode 100644 src/main/java/org/mockito/MockedConstruction.java create mode 100644 src/main/java/org/mockito/ScopedMock.java create mode 100644 src/main/java/org/mockito/internal/MockedConstructionImpl.java create mode 100644 src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockRuleTest.java create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/StaticMockRuleTest.java diff --git a/src/main/java/org/mockito/MockedConstruction.java b/src/main/java/org/mockito/MockedConstruction.java new file mode 100644 index 0000000000..c00fb021a2 --- /dev/null +++ b/src/main/java/org/mockito/MockedConstruction.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2007 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito; + +import java.lang.reflect.Constructor; +import java.util.List; + +/** + * Represents a mock of any object construction of the represented type. Within the scope of the + * mocked construction, the invocation of any interceptor will generate a mock which will be + * prepared as specified when generating this scope. The mock can also be received via this + * instance. + *

    + * If the {@link Mock} annotation is used on fields or method parameters of this type, a mocked + * construction is created instead of a regular mock. The mocked construction is activated and + * released upon completing any relevant test. + * + * @param The type for which the construction is being mocked. + */ +@Incubating +public interface MockedConstruction extends ScopedMock { + + List constructed(); + + interface Context { + + int getCount(); + + Constructor constructor(); + + List arguments(); + } + + interface MockInitializer { + + void prepare(T mock, Context context) throws Throwable; + } +} diff --git a/src/main/java/org/mockito/MockedStatic.java b/src/main/java/org/mockito/MockedStatic.java index fc23c90776..ac291ba33c 100644 --- a/src/main/java/org/mockito/MockedStatic.java +++ b/src/main/java/org/mockito/MockedStatic.java @@ -24,7 +24,7 @@ * @param The type being mocked. */ @Incubating -public interface MockedStatic extends AutoCloseable { +public interface MockedStatic extends ScopedMock { /** * See {@link Mockito#when(Object)}. @@ -63,24 +63,6 @@ default void verify(Verification verification) { */ void verifyNoInteractions(); - /** - * Checks if this mock is closed. - * - * @return {@code true} if this mock is closed. - */ - boolean isClosed(); - - /** - * Releases this static mock and throws a {@link org.mockito.exceptions.base.MockitoException} if closed already. - */ - @Override - void close(); - - /** - * Releases this static mock and is non-operational if already released. - */ - void closeOnDemand(); - interface Verification { void apply() throws Throwable; diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 118eb2624d..95bfd566fd 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -28,18 +28,10 @@ import org.mockito.quality.Strictness; import org.mockito.session.MockitoSessionBuilder; import org.mockito.session.MockitoSessionLogger; -import org.mockito.stubbing.Answer; -import org.mockito.stubbing.Answer1; -import org.mockito.stubbing.LenientStubber; -import org.mockito.stubbing.OngoingStubbing; -import org.mockito.stubbing.Stubber; -import org.mockito.stubbing.Stubbing; -import org.mockito.stubbing.VoidAnswer1; -import org.mockito.verification.After; -import org.mockito.verification.Timeout; -import org.mockito.verification.VerificationAfterDelay; -import org.mockito.verification.VerificationMode; -import org.mockito.verification.VerificationWithTimeout; +import org.mockito.stubbing.*; +import org.mockito.verification.*; + +import java.util.function.Function; /** *

    Mockito logo

    @@ -106,6 +98,7 @@ * 46. New Mockito.lenient() and MockSettings.lenient() methods (Since 2.20.0)
    * 47. New API for clearing mock state in inline mocking (Since 2.25.0)
    * 48. New API for mocking static methods (Since 3.4.0)
    + * 49. New API for mocking object construction (Since 3.5.0)
    * * *

    0. Migrating to Mockito 2

    @@ -1565,9 +1558,32 @@ * assertEquals("foo", Foo.method()); * * - * Due to the defined scope of the static mock, it returns to its original behvior once the scope is released. To define mock + * Due to the defined scope of the static mock, it returns to its original behavior once the scope is released. To define mock * behavior and to verify static method invocations, use the MockedStatic that is returned. *

    + * + *

    49. Mocking object construction (since 3.5.0)

    + * + * When using the inline mock maker, it is possible to generate mocks on constructor invocations within the current + * thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere. + * + * To make sure a constructor mocks remain temporary, it is recommended to define the scope within a try-with-resources construct. + * In the following example, the Foo type's construction would generate a mock: + * + *
    
    + * assertEquals("foo", Foo.method());
    + * try (MockedConstruction mocked = mockConstruction(Foo.class)) {
    + * Foo foo = new Foo();
    + * when(foo.method()).thenReturn("bar");
    + * assertEquals("bar", foo.method());
    + * verify(foo).method();
    + * }
    + * assertEquals("foo", foo.method());
    + * 
    + * + * Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is + * released. To define mock behavior and to verify static method invocations, use the MockedConstruction that is returned. + *

    */ @SuppressWarnings("unchecked") public class Mockito extends ArgumentMatchers { @@ -2144,6 +2160,152 @@ public static MockedStatic mockStatic(Class classToMock, MockSettings return MOCKITO_CORE.mockStatic(classToMock, mockSettings); } + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @param defaultAnswer the default answer for the first created mock. + * @param additionalAnswers the default answer for all additional mocks. For any access mocks, the + * last answer is used. If this array is empty, the {@code defaultAnswer} is used. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstructionWithAnswer( + Class classToMock, Answer defaultAnswer, Answer... additionalAnswers) { + return mockConstruction( + classToMock, + context -> { + if (context.getCount() == 1 || additionalAnswers.length == 0) { + return withSettings().defaultAnswer(defaultAnswer); + } else if (context.getCount() >= additionalAnswers.length) { + return withSettings() + .defaultAnswer(additionalAnswers[additionalAnswers.length - 1]); + } else { + return withSettings() + .defaultAnswer(additionalAnswers[context.getCount() - 2]); + } + }, + (mock, context) -> {}); + } + + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstruction(Class classToMock) { + return mockConstruction(classToMock, index -> withSettings(), (mock, context) -> {}); + } + + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @param mockInitializer a callback to prepare a mock's methods after its instantiation. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstruction( + Class classToMock, MockedConstruction.MockInitializer mockInitializer) { + return mockConstruction(classToMock, withSettings(), mockInitializer); + } + + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @param mockSettings the mock settings to use. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstruction( + Class classToMock, MockSettings mockSettings) { + return mockConstruction(classToMock, context -> mockSettings); + } + + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @param mockSettingsFactory the mock settings to use. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstruction( + Class classToMock, + Function mockSettingsFactory) { + return mockConstruction(classToMock, mockSettingsFactory, (mock, context) -> {}); + } + + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @param mockSettings the settings to use. + * @param mockInitializer a callback to prepare a mock's methods after its instantiation. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstruction( + Class classToMock, + MockSettings mockSettings, + MockedConstruction.MockInitializer mockInitializer) { + return mockConstruction(classToMock, index -> mockSettings, mockInitializer); + } + + /** + * Creates a thread-local mock controller for all constructions of the given class. + * The returned object's {@link MockedConstruction#close()} method must be called upon completing the + * test or the mock will remain active on the current thread. + *

    + * See examples in javadoc for {@link Mockito} class + * + * @param classToMock non-abstract class of which constructions should be mocked. + * @param mockSettingsFactory a function to create settings to use. + * @param mockInitializer a callback to prepare a mock's methods after its instantiation. + * @return mock controller + */ + @Incubating + @CheckReturnValue + public static MockedConstruction mockConstruction( + Class classToMock, + Function mockSettingsFactory, + MockedConstruction.MockInitializer mockInitializer) { + return MOCKITO_CORE.mockConstruction(classToMock, mockSettingsFactory, mockInitializer); + } + /** * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called. *

    diff --git a/src/main/java/org/mockito/ScopedMock.java b/src/main/java/org/mockito/ScopedMock.java new file mode 100644 index 0000000000..3ef0d9b3d3 --- /dev/null +++ b/src/main/java/org/mockito/ScopedMock.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2007 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito; + +/** + * Represents a mock with a thread-local explicit scope. Scoped mocks must be closed by the entity + * that activates the scoped mock. + */ +@Incubating +public interface ScopedMock extends AutoCloseable { + + /** + * Checks if this mock is closed. + * + * @return {@code true} if this mock is closed. + */ + boolean isClosed(); + + /** + * Closes this scoped mock and throws an exception if already closed. + */ + @Override + void close(); + + /** + * Releases this scoped mock and is non-operational if already released. + */ + void closeOnDemand(); +} diff --git a/src/main/java/org/mockito/internal/MockedConstructionImpl.java b/src/main/java/org/mockito/internal/MockedConstructionImpl.java new file mode 100644 index 0000000000..ee09f3ccde --- /dev/null +++ b/src/main/java/org/mockito/internal/MockedConstructionImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2007 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal; + +import java.util.Collections; +import java.util.List; + +import org.mockito.MockedConstruction; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.debugging.LocationImpl; +import org.mockito.invocation.Location; +import org.mockito.plugins.MockMaker; + +import static org.mockito.internal.util.StringUtil.*; + +public final class MockedConstructionImpl implements MockedConstruction { + + private final MockMaker.ConstructionMockControl control; + + private boolean closed; + + private final Location location = new LocationImpl(); + + protected MockedConstructionImpl(MockMaker.ConstructionMockControl control) { + this.control = control; + } + + @Override + public List constructed() { + return Collections.unmodifiableList(control.getMocks()); + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public void close() { + assertNotClosed(); + + closed = true; + control.disable(); + } + + @Override + public void closeOnDemand() { + if (!closed) { + close(); + } + } + + private void assertNotClosed() { + if (closed) { + throw new MockitoException( + join( + "The static mock created at", + location.toString(), + "is already resolved and cannot longer be used")); + } + } +} diff --git a/src/main/java/org/mockito/internal/MockedStaticImpl.java b/src/main/java/org/mockito/internal/MockedStaticImpl.java index 25434769e2..cb7794cc03 100644 --- a/src/main/java/org/mockito/internal/MockedStaticImpl.java +++ b/src/main/java/org/mockito/internal/MockedStaticImpl.java @@ -4,8 +4,6 @@ */ package org.mockito.internal; -import org.mockito.Incubating; -import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.MockingDetails; import org.mockito.Mockito; @@ -29,21 +27,6 @@ import static org.mockito.internal.util.StringUtil.*; import static org.mockito.internal.verification.VerificationModeFactory.*; -/** - * Represents an active mock of a type's static methods. The mocking only affects the thread - * on which this static mock was created and it is not safe to use this object from another - * thread. The static mock is released when this object's {@link MockedStaticImpl#close()} method - * is invoked. If this object is never closed, the static mock will remain active on the - * initiating thread. It is therefore recommended to create this object within a try-with-resources - * statement unless when managed explicitly, for example by using a JUnit rule or extension. - *

    - * If the {@link Mock} annotation is used on fields or method parameters of this type, a static mock - * is created instead of a regular mock. The static mock is activated and released upon completing any - * relevant test. - * - * @param The type being mocked. - */ -@Incubating public final class MockedStaticImpl implements MockedStatic { private final MockMaker.StaticMockControl control; diff --git a/src/main/java/org/mockito/internal/MockitoCore.java b/src/main/java/org/mockito/internal/MockitoCore.java index bccb045fe1..6901baef85 100644 --- a/src/main/java/org/mockito/internal/MockitoCore.java +++ b/src/main/java/org/mockito/internal/MockitoCore.java @@ -4,25 +4,7 @@ */ package org.mockito.internal; -import static org.mockito.internal.exceptions.Reporter.*; -import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; -import static org.mockito.internal.util.MockUtil.createMock; -import static org.mockito.internal.util.MockUtil.createStaticMock; -import static org.mockito.internal.util.MockUtil.getInvocationContainer; -import static org.mockito.internal.util.MockUtil.getMockHandler; -import static org.mockito.internal.util.MockUtil.isMock; -import static org.mockito.internal.util.MockUtil.resetMock; -import static org.mockito.internal.util.MockUtil.typeMockabilityOf; -import static org.mockito.internal.verification.VerificationModeFactory.noInteractions; -import static org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions; - -import java.util.Arrays; -import java.util.List; - -import org.mockito.InOrder; -import org.mockito.MockSettings; -import org.mockito.MockedStatic; -import org.mockito.MockingDetails; +import org.mockito.*; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.internal.creation.MockSettingsImpl; import org.mockito.internal.invocation.finder.VerifiableInvocationsFinder; @@ -49,6 +31,16 @@ import org.mockito.stubbing.Stubber; import org.mockito.verification.VerificationMode; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +import static org.mockito.internal.exceptions.Reporter.*; +import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; +import static org.mockito.internal.util.MockUtil.*; +import static org.mockito.internal.verification.VerificationModeFactory.noInteractions; +import static org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions; + @SuppressWarnings("unchecked") public class MockitoCore { @@ -87,6 +79,29 @@ public MockedStatic mockStatic(Class classToMock, MockSettings setting return new MockedStaticImpl<>(control); } + public MockedConstruction mockConstruction( + Class typeToMock, + Function settingsFactory, + MockedConstruction.MockInitializer mockInitializer) { + Function> creationSettings = + context -> { + MockSettings value = settingsFactory.apply(context); + if (!MockSettingsImpl.class.isInstance(value)) { + throw new IllegalArgumentException( + "Unexpected implementation of '" + + value.getClass().getCanonicalName() + + "'\n" + + "At the moment, you cannot provide your own implementations of that class."); + } + MockSettingsImpl impl = MockSettingsImpl.class.cast(value); + return impl.build(typeToMock); + }; + MockMaker.ConstructionMockControl control = + createConstructionMock(typeToMock, creationSettings, mockInitializer); + control.enable(); + return new MockedConstructionImpl<>(control); + } + public OngoingStubbing when(T methodCall) { MockingProgress mockingProgress = mockingProgress(); mockingProgress.stubbingStarted(); diff --git a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java index 24cb7a1cb2..35e212b5d9 100644 --- a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java @@ -16,8 +16,8 @@ import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; +import org.mockito.ScopedMock; import org.mockito.exceptions.base.MockitoException; import org.mockito.plugins.AnnotationEngine; @@ -64,14 +64,14 @@ private void registerAnnotationProcessor( @Override public AutoCloseable process(Class clazz, Object testInstance) { - List> mockedStatics = new ArrayList<>(); + List scopedMocks = new ArrayList<>(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { boolean alreadyAssigned = false; for (Annotation annotation : field.getAnnotations()) { Object mock = createMockFor(annotation, field); - if (mock instanceof MockedStatic) { - mockedStatics.add((MockedStatic) mock); + if (mock instanceof ScopedMock) { + scopedMocks.add((ScopedMock) mock); } if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); @@ -79,8 +79,8 @@ public AutoCloseable process(Class clazz, Object testInstance) { try { setField(testInstance, field, mock); } catch (Exception e) { - for (MockedStatic mockedStatic : mockedStatics) { - mockedStatic.close(); + for (ScopedMock scopedMock : scopedMocks) { + scopedMock.close(); } throw new MockitoException( "Problems setting field " @@ -93,8 +93,8 @@ public AutoCloseable process(Class clazz, Object testInstance) { } } return () -> { - for (MockedStatic mockedStatic : mockedStatics) { - mockedStatic.closeOnDemand(); + for (ScopedMock scopedMock : scopedMocks) { + scopedMock.closeOnDemand(); } }; } diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java index 59239a4674..176d3e5006 100644 --- a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java @@ -12,8 +12,8 @@ import java.util.List; import java.util.Set; -import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; +import org.mockito.ScopedMock; import org.mockito.internal.configuration.injection.scanner.InjectMocksScanner; import org.mockito.internal.configuration.injection.scanner.MockScanner; import org.mockito.plugins.AnnotationEngine; @@ -119,8 +119,8 @@ private AutoCloseable injectCloseableMocks(final Object testClassInstance) { return () -> { for (Object mock : mocks) { - if (mock instanceof MockedStatic) { - ((MockedStatic) mock).closeOnDemand(); + if (mock instanceof ScopedMock) { + ((ScopedMock) mock).closeOnDemand(); } } }; diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java index 48f0515a4b..e48291e5d5 100644 --- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java +++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java @@ -12,6 +12,7 @@ import org.mockito.Mock; import org.mockito.MockSettings; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoException; @@ -52,13 +53,21 @@ public static Object processAnnotationForMock( mockSettings.defaultAnswer(annotation.answer()); if (type == MockedStatic.class) { - return Mockito.mockStatic(inferStaticMock(genericType.get(), name), mockSettings); + return Mockito.mockStatic( + inferParameterizedType( + genericType.get(), name, MockedStatic.class.getSimpleName()), + mockSettings); + } else if (type == MockedConstruction.class) { + return Mockito.mockConstruction( + inferParameterizedType( + genericType.get(), name, MockedConstruction.class.getSimpleName()), + mockSettings); } else { return Mockito.mock(type, mockSettings); } } - static Class inferStaticMock(Type type, String name) { + static Class inferParameterizedType(Type type, String name, String sort) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] arguments = parameterizedType.getActualTypeArguments(); @@ -72,11 +81,11 @@ static Class inferStaticMock(Type type, String name) { join( "Mockito cannot infer a static mock from a raw type for " + name, "", - "Instead of @Mock MockedStatic you need to specify a parameterized type", - "For example, if you would like to mock static methods of Sample.class, specify", + "Instead of @Mock " + sort + " you need to specify a parameterized type", + "For example, if you would like to mock Sample.class, specify", "", - "@Mock MockedStatic", + "@Mock " + sort + "", "", - "as the type parameter. If the type is parameterized, it should be specified as raw type.")); + "as the type parameter. If the type is itself parameterized, it should be specified as raw type.")); } } diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java index 8ea513e2c6..e11c866ed1 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java @@ -5,9 +5,12 @@ package org.mockito.internal.creation.bytebuddy; import org.mockito.Incubating; +import org.mockito.MockedConstruction; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; +import java.util.function.Function; + /** * ByteBuddy MockMaker. * @@ -51,4 +54,14 @@ public StaticMockControl createStaticMock( Class type, MockCreationSettings settings, MockHandler handler) { return defaultByteBuddyMockMaker.createStaticMock(type, settings, handler); } + + @Override + public ConstructionMockControl createConstructionMock( + Class type, + Function> settingsFactory, + Function> handlerFactory, + MockedConstruction.MockInitializer mockInitializer) { + return defaultByteBuddyMockMaker.createConstructionMock( + type, settingsFactory, handlerFactory, mockInitializer); + } } diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java index b87d7cb6b7..b27b9727a1 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/BytecodeGenerator.java @@ -8,5 +8,7 @@ public interface BytecodeGenerator { Class mockClass(MockFeatures features); + void mockClassConstruction(Class type); + void mockClassStatic(Class type); } diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java new file mode 100644 index 0000000000..8d5abe75bd --- /dev/null +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java @@ -0,0 +1,10 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.creation.bytebuddy; + +public interface ConstructionCallback { + + void accept(Class type, Object object, Object[] arguments, String[] parameterTypeNames); +} 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 4b679d194e..4afbb827db 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -11,20 +11,23 @@ import java.lang.instrument.Instrumentation; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.Map; -import java.util.WeakHashMap; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import net.bytebuddy.agent.ByteBuddyAgent; import org.mockito.Incubating; +import org.mockito.MockedConstruction; import org.mockito.creation.instance.InstantiationException; import org.mockito.creation.instance.Instantiator; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.base.MockitoInitializationException; +import org.mockito.exceptions.misusing.MockitoConfigurationException; import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.Platform; import org.mockito.internal.util.concurrent.DetachedThreadLocal; @@ -191,7 +194,10 @@ public class InlineByteBuddyMockMaker private final DetachedThreadLocal, MockMethodInterceptor>> mockedStatics = new DetachedThreadLocal<>(DetachedThreadLocal.Cleaner.INLINE); - private final ThreadLocal mockConstruction = ThreadLocal.withInitial(() -> false); + private final DetachedThreadLocal, BiConsumer>> + mockedConstruction = new DetachedThreadLocal<>(DetachedThreadLocal.Cleaner.INLINE); + + private final ThreadLocal mockitoConstruction = ThreadLocal.withInitial(() -> false); public InlineByteBuddyMockMaker() { if (INITIALIZATION_ERROR != null) { @@ -226,10 +232,57 @@ public InlineByteBuddyMockMaker() { Platform.describe()), INITIALIZATION_ERROR); } + + ThreadLocal> currentConstruction = new ThreadLocal<>(); + ThreadLocal isSuspended = ThreadLocal.withInitial(() -> false); + Predicate> isMockConstruction = + type -> { + if (isSuspended.get()) { + return false; + } else if (mockitoConstruction.get() || currentConstruction.get() != null) { + return true; + } + Map, ?> interceptors = mockedConstruction.get(); + if (interceptors != null && interceptors.containsKey(type)) { + currentConstruction.set(type); + return true; + } else { + return false; + } + }; + ConstructionCallback onConstruction = + (type, object, arguments, parameterTypeNames) -> { + if (mockitoConstruction.get() || currentConstruction.get() != type) { + return; + } + currentConstruction.remove(); + isSuspended.set(true); + try { + Map, BiConsumer> interceptors = + mockedConstruction.get(); + if (interceptors != null) { + BiConsumer interceptor = + interceptors.get(type); + if (interceptor != null) { + interceptor.accept( + object, + new InlineConstructionMockContext( + arguments, object.getClass(), parameterTypeNames)); + } + } + } finally { + isSuspended.set(false); + } + }; + bytecodeGenerator = new TypeCachingBytecodeGenerator( new InlineBytecodeGenerator( - INSTRUMENTATION, mocks, mockedStatics, mockConstruction::get), + INSTRUMENTATION, + mocks, + mockedStatics, + isMockConstruction, + onConstruction), true); } @@ -438,6 +491,35 @@ public StaticMockControl createStaticMock( return new InlineStaticMockControl<>(type, interceptors, settings, handler); } + @Override + public ConstructionMockControl createConstructionMock( + Class type, + Function> settingsFactory, + Function> handlerFactory, + MockedConstruction.MockInitializer mockInitializer) { + if (type == Object.class) { + throw new MockitoException( + "It is not possible to mock construction of the Object class " + + "to avoid inference with default object constructor chains"); + } else if (type.isPrimitive() || Modifier.isAbstract(type.getModifiers())) { + throw new MockitoException( + "It is not possible to construct primitive types or abstract types: " + + type.getTypeName()); + } + + bytecodeGenerator.mockClassConstruction(type); + + Map, BiConsumer> interceptors = + mockedConstruction.get(); + if (interceptors == null) { + interceptors = new WeakHashMap<>(); + mockedConstruction.set(interceptors); + } + + return new InlineConstructionMockControl<>( + type, settingsFactory, handlerFactory, mockInitializer, interceptors); + } + @Override @SuppressWarnings("unchecked") public T newInstance(Class cls) throws InstantiationException { @@ -463,11 +545,11 @@ public T newInstance(Class cls) throws InstantiationException { || !Modifier.isPublic(cls.getModifiers())) { selected.setAccessible(true); } - mockConstruction.set(true); + mockitoConstruction.set(true); try { return (T) selected.newInstance(arguments); } finally { - mockConstruction.set(false); + mockitoConstruction.set(false); } } catch (Exception e) { throw new InstantiationException("Could not instantiate " + cls.getTypeName(), e); @@ -503,6 +585,7 @@ private static class InlineStaticMockControl implements StaticMockControl private final Map, MockMethodInterceptor> interceptors; private final MockCreationSettings settings; + private final MockHandler handler; private InlineStaticMockControl( @@ -550,4 +633,167 @@ public void disable() { } } } + + private class InlineConstructionMockControl implements ConstructionMockControl { + + private final Class type; + + private final Function> settingsFactory; + private final Function> handlerFactory; + + private final MockedConstruction.MockInitializer mockInitializer; + + private final Map, BiConsumer> interceptors; + + private final List all = new ArrayList<>(); + private int count; + + private InlineConstructionMockControl( + Class type, + Function> settingsFactory, + Function> handlerFactory, + MockedConstruction.MockInitializer mockInitializer, + Map, BiConsumer> interceptors) { + this.type = type; + this.settingsFactory = settingsFactory; + this.handlerFactory = handlerFactory; + this.mockInitializer = mockInitializer; + this.interceptors = interceptors; + } + + @Override + public Class getType() { + return type; + } + + @Override + public void enable() { + if (interceptors.putIfAbsent( + type, + (object, context) -> { + ((InlineConstructionMockContext) context).count = ++count; + MockMethodInterceptor interceptor = + new MockMethodInterceptor( + handlerFactory.apply(context), + settingsFactory.apply(context)); + mocks.put(object, interceptor); + try { + @SuppressWarnings("unchecked") + T cast = (T) object; + mockInitializer.prepare(cast, context); + } catch (Throwable t) { + mocks.remove(object); // TODO: filter stack trace? + throw new MockitoException( + "Could not initialize mocked construction", t); + } + all.add(object); + }) + != null) { + throw new MockitoException( + join( + "For " + + type.getName() + + ", static mocking is already registered in the current thread", + "", + "To create a new mock, the existing static mock registration must be deregistered")); + } + } + + @Override + public void disable() { + if (interceptors.remove(type) == null) { + throw new MockitoException( + join( + "Could not deregister " + + type.getName() + + " as a static mock since it is not currently registered", + "", + "To register a static mock, use Mockito.mockStatic(" + + type.getSimpleName() + + ".class)")); + } + all.clear(); + } + + @Override + @SuppressWarnings("unchecked") + public List getMocks() { + return (List) all; + } + } + + private static class InlineConstructionMockContext implements MockedConstruction.Context { + + private static final Map> PRIMITIVES = new HashMap<>(); + + static { + PRIMITIVES.put(boolean.class.getTypeName(), boolean.class); + PRIMITIVES.put(byte.class.getTypeName(), byte.class); + PRIMITIVES.put(short.class.getTypeName(), short.class); + PRIMITIVES.put(char.class.getTypeName(), char.class); + PRIMITIVES.put(int.class.getTypeName(), int.class); + PRIMITIVES.put(long.class.getTypeName(), long.class); + PRIMITIVES.put(float.class.getTypeName(), float.class); + PRIMITIVES.put(double.class.getTypeName(), double.class); + } + + private int count; + + private final Object[] arguments; + private final Class type; + private final String[] parameterTypeNames; + + private InlineConstructionMockContext( + Object[] arguments, Class type, String[] parameterTypeNames) { + this.arguments = arguments; + this.type = type; + this.parameterTypeNames = parameterTypeNames; + } + + @Override + public int getCount() { + if (count == 0) { + throw new MockitoConfigurationException( + "mocked construction context is not initialized"); + } + return count; + } + + @Override + public Constructor constructor() { + Class[] parameterTypes = new Class[parameterTypeNames.length]; + int index = 0; + for (String parameterTypeName : parameterTypeNames) { + if (PRIMITIVES.containsKey(parameterTypeName)) { + parameterTypes[index++] = PRIMITIVES.get(parameterTypeName); + } else { + try { + parameterTypes[index++] = + Class.forName(parameterTypeName, false, type.getClassLoader()); + } catch (ClassNotFoundException e) { + throw new MockitoException( + "Could not find parameter of type " + parameterTypeName, e); + } + } + } + try { + return type.getDeclaredConstructor(parameterTypes); + } catch (NoSuchMethodException e) { + throw new MockitoException( + join( + "Could not resolve constructor of type", + "", + type.getTypeName(), + "", + "with arguments of types", + Arrays.toString(parameterTypes)), + e); + } + } + + @Override + public List arguments() { + return Collections.unmodifiableList(Arrays.asList(arguments)); + } + } } 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 47e1de07df..95776e6893 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -4,18 +4,17 @@ */ package org.mockito.internal.creation.bytebuddy; -import static net.bytebuddy.implementation.MethodDelegation.withDefaultConfiguration; -import static net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of; -import static net.bytebuddy.matcher.ElementMatchers.*; -import static org.mockito.internal.util.StringUtil.join; - import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; -import java.util.*; -import java.util.function.BooleanSupplier; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; import net.bytebuddy.ByteBuddy; import net.bytebuddy.ClassFileVersion; @@ -44,6 +43,11 @@ import org.mockito.internal.util.concurrent.WeakConcurrentSet; import org.mockito.mock.SerializableMode; +import static net.bytebuddy.implementation.MethodDelegation.*; +import static net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.*; +import static net.bytebuddy.matcher.ElementMatchers.*; +import static org.mockito.internal.util.StringUtil.*; + public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTransformer { private static final String PRELOAD = "org.mockito.inline.preload"; @@ -77,7 +81,8 @@ public InlineBytecodeGenerator( Instrumentation instrumentation, WeakConcurrentMap mocks, DetachedThreadLocal, MockMethodInterceptor>> mockedStatics, - BooleanSupplier isMockConstruction) { + Predicate> isMockConstruction, + ConstructionCallback onConstruction) { preload(); this.instrumentation = instrumentation; byteBuddy = @@ -154,7 +159,8 @@ public InlineBytecodeGenerator( this.redefineModule = redefineModule; MockMethodDispatcher.set( identifier, - new MockMethodAdvice(mocks, mockedStatics, identifier, isMockConstruction)); + new MockMethodAdvice( + mocks, mockedStatics, identifier, isMockConstruction, onConstruction)); instrumentation.addTransformer(this, true); } @@ -206,10 +212,15 @@ public Class mockClass(MockFeatures features) { } @Override - public void mockClassStatic(Class type) { + public synchronized void mockClassStatic(Class type) { triggerRetransformation(Collections.singleton(type), true); } + @Override + public synchronized void mockClassConstruction(Class type) { + triggerRetransformation(Collections.singleton(type), false); + } + private void triggerRetransformation(Set> types, boolean flat) { Set> targets = new HashSet>(); 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 1c37cc4243..4d12ce108c 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -15,13 +15,14 @@ import java.lang.reflect.Modifier; import java.util.Map; import java.util.concurrent.Callable; -import java.util.function.BooleanSupplier; +import java.util.function.Predicate; import net.bytebuddy.ClassFileVersion; import net.bytebuddy.asm.Advice; import net.bytebuddy.asm.AsmVisitorWrapper; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.MethodList; +import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.scaffold.MethodGraph; import net.bytebuddy.implementation.Implementation; @@ -59,15 +60,18 @@ public class MockMethodAdvice extends MockMethodDispatcher { private final WeakConcurrentMap, SoftReference> graphs = new WeakConcurrentMap.WithInlinedExpunction, SoftReference>(); - private final BooleanSupplier isMockConstruction; + private final Predicate> isMockConstruction; + private final ConstructionCallback onConstruction; public MockMethodAdvice( WeakConcurrentMap interceptors, DetachedThreadLocal, MockMethodInterceptor>> mockedStatics, String identifier, - BooleanSupplier isMockConstruction) { + Predicate> isMockConstruction, + ConstructionCallback onConstruction) { this.interceptors = interceptors; this.mockedStatics = mockedStatics; + this.onConstruction = onConstruction; this.identifier = identifier; this.isMockConstruction = isMockConstruction; } @@ -161,6 +165,12 @@ public Callable handleStatic(Class type, Method origin, Object[] arguments new LocationImpl(new Throwable(), true))); } + @Override + public void handleConstruction( + Class type, Object object, Object[] arguments, String[] parameterTypeNames) { + onConstruction.accept(type, object, arguments, parameterTypeNames); + } + @Override public boolean isMock(Object instance) { // We need to exclude 'interceptors.target' explicitly to avoid a recursive check on whether @@ -202,7 +212,7 @@ public boolean isOverridden(Object instance, Method origin) { @Override public boolean isConstructorMock(Class type) { - return isMockConstruction.getAsBoolean(); + return isMockConstruction.test(type); } private static class RealMethodCall implements RealMethod { @@ -408,10 +418,15 @@ public MethodVisitor wrap( public void visitCode() { super.visitCode(); /* - * The byte code that is added to the start of the method is roughly equivalent to: + * The byte code that is added to the start of the method is roughly equivalent to + * the following byte code for a hypothetical constructor of class Current: * * if (MockMethodDispatcher.isConstructorMock(, Current.class) { * super(); + * MockMethodDispatcher.handleConstruction(Current.class, + * this, + * new Object[] {argument1, argument2, ...}, + * new String[] {argumentType1, argumentType2, ...}); * return; * } * @@ -471,6 +486,76 @@ public void visitCode() { selected.getInternalName(), selected.getDescriptor(), false); + super.visitLdcInsn(identifier); + if (implementationContext + .getClassFileVersion() + .isAtLeast(ClassFileVersion.JAVA_V5)) { + super.visitLdcInsn(Type.getType(instrumentedType.getDescriptor())); + } else { + super.visitLdcInsn(instrumentedType.getName()); + super.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(Class.class), + "forName", + Type.getMethodDescriptor( + Type.getType(Class.class), + Type.getType(String.class)), + false); + } + super.visitVarInsn(Opcodes.ALOAD, 0); + super.visitLdcInsn(instrumentedMethod.getParameters().size()); + super.visitTypeInsn( + Opcodes.ANEWARRAY, Type.getInternalName(Object.class)); + int index = 0; + for (ParameterDescription parameter : + instrumentedMethod.getParameters()) { + super.visitInsn(Opcodes.DUP); + super.visitLdcInsn(index++); + Type type = + Type.getType( + parameter.getType().asErasure().getDescriptor()); + super.visitVarInsn( + type.getOpcode(Opcodes.ILOAD), parameter.getOffset()); + if (parameter.getType().isPrimitive()) { + Type wrapper = + Type.getType( + parameter + .getType() + .asErasure() + .asBoxed() + .getDescriptor()); + super.visitMethodInsn( + Opcodes.INVOKESTATIC, + wrapper.getInternalName(), + "valueOf", + Type.getMethodDescriptor(wrapper, type), + false); + } + super.visitInsn(Opcodes.AASTORE); + } + index = 0; + super.visitLdcInsn(instrumentedMethod.getParameters().size()); + super.visitTypeInsn( + Opcodes.ANEWARRAY, Type.getInternalName(String.class)); + for (TypeDescription typeDescription : + instrumentedMethod.getParameters().asTypeList().asErasures()) { + super.visitInsn(Opcodes.DUP); + super.visitLdcInsn(index++); + super.visitLdcInsn(typeDescription.getName()); + super.visitInsn(Opcodes.AASTORE); + } + super.visitMethodInsn( + Opcodes.INVOKESTATIC, + Type.getInternalName(MockMethodDispatcher.class), + "handleConstruction", + Type.getMethodDescriptor( + Type.VOID_TYPE, + Type.getType(String.class), + Type.getType(Class.class), + Type.getType(Object.class), + Type.getType(Object[].class), + Type.getType(String[].class)), + false); super.visitInsn(Opcodes.RETURN); super.visitLabel(label); if (implementationContext @@ -482,9 +567,16 @@ public void visitCode() { @Override public void visitMaxs(int maxStack, int maxLocals) { - super.visitMaxs( - Math.max(maxStack, Math.max(3, selected.getStackSize())), - maxLocals); + int prequel = Math.max(5, selected.getStackSize()); + for (ParameterDescription parameter : + instrumentedMethod.getParameters()) { + prequel = + Math.max( + prequel, + 6 + parameter.getType().getStackSize().getSize()); + prequel = Math.max(prequel, 8); + } + super.visitMaxs(Math.max(maxStack, prequel), maxLocals); } }; } 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 4a65643bc5..cd2b177640 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java @@ -208,6 +208,12 @@ public void mockClassStatic(Class type) { throw new MockitoException("The subclass byte code generator cannot create static mocks"); } + @Override + public void mockClassConstruction(Class type) { + throw new MockitoException( + "The subclass byte code generator cannot create construction mocks"); + } + private Collection> getAllTypes(Class type) { Collection> supertypes = new LinkedList>(); supertypes.add(type); 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 76bf44dca8..b3e70c7da7 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java @@ -62,6 +62,11 @@ public void mockClassStatic(Class type) { bytecodeGenerator.mockClassStatic(type); } + @Override + public void mockClassConstruction(Class type) { + bytecodeGenerator.mockClassConstruction(type); + } + private static class MockitoMockKey extends TypeCache.SimpleKey { private final SerializableMode serializableMode; 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 0ab2feda39..bcd12d3c64 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 @@ -41,12 +41,24 @@ public static boolean isConstructorMock(String identifier, Class type) { return DISPATCHERS.get(identifier).isConstructorMock(type); } + public static void handleConstruction( + String identifier, + Class type, + Object object, + Object[] arguments, + String[] parameterTypeNames) { + DISPATCHERS.get(identifier).handleConstruction(type, object, arguments, parameterTypeNames); + } + public abstract Callable handle(Object instance, Method origin, Object[] arguments) throws Throwable; public abstract Callable handleStatic(Class type, Method origin, Object[] arguments) throws Throwable; + public abstract void handleConstruction( + Class type, Object object, Object[] arguments, String[] parameterTypeNames); + public abstract boolean isMock(Object instance); public abstract boolean isMocked(Object instance); diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java index 4767ef9445..352645236a 100644 --- a/src/main/java/org/mockito/internal/util/MockUtil.java +++ b/src/main/java/org/mockito/internal/util/MockUtil.java @@ -4,8 +4,7 @@ */ package org.mockito.internal.util; -import static org.mockito.internal.handler.MockHandlerFactory.createMockHandler; - +import org.mockito.MockedConstruction; import org.mockito.Mockito; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.internal.configuration.plugins.Plugins; @@ -18,6 +17,10 @@ import org.mockito.plugins.MockMaker; import org.mockito.plugins.MockMaker.TypeMockability; +import java.util.function.Function; + +import static org.mockito.internal.handler.MockHandlerFactory.createMockHandler; + @SuppressWarnings("unchecked") public class MockUtil { @@ -108,4 +111,14 @@ public static MockMaker.StaticMockControl createStaticMock( MockHandler handler = createMockHandler(settings); return mockMaker.createStaticMock(type, settings, handler); } + + public static MockMaker.ConstructionMockControl createConstructionMock( + Class type, + Function> settingsFactory, + MockedConstruction.MockInitializer mockInitializer) { + Function> handlerFactory = + context -> createMockHandler(settingsFactory.apply(context)); + return mockMaker.createConstructionMock( + type, settingsFactory, handlerFactory, mockInitializer); + } } diff --git a/src/main/java/org/mockito/plugins/MockMaker.java b/src/main/java/org/mockito/plugins/MockMaker.java index df3ff4210d..fc1a516606 100644 --- a/src/main/java/org/mockito/plugins/MockMaker.java +++ b/src/main/java/org/mockito/plugins/MockMaker.java @@ -5,11 +5,15 @@ package org.mockito.plugins; import org.mockito.Incubating; +import org.mockito.MockedConstruction; import org.mockito.exceptions.base.MockitoException; import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; -import static org.mockito.internal.util.StringUtil.*; +import java.util.List; +import java.util.function.Function; + +import static org.mockito.internal.util.StringUtil.join; /** * The facility to create mocks. @@ -141,6 +145,39 @@ default StaticMockControl createStaticMock( "Note that Mockito's inline mock maker is not supported on Android.")); } + /** + * If you want to provide your own implementation of {@code MockMaker} this method should: + *
      + *
    • Intercept all constructions of the specified type in the current thread
    • + *
    • Only intercept the construction after being enabled.
    • + *
    • Stops the interception when disabled.
    • + *
    + * + * @param settingsFactory Factory for mock creation settings like type to mock, extra interfaces and so on. + * @param handlerFactory Factory for settings. See {@link org.mockito.invocation.MockHandler}. + * Do not provide your own implementation at this time. Make sure your implementation of + * {@link #getHandler(Object)} will return this instance. + * @param Type of the mock to return, actually the settings.getTypeToMock. + * @return A control for the mocked construction. + * @since 3.5.0 + */ + @Incubating + default ConstructionMockControl createConstructionMock( + Class type, + Function> settingsFactory, + Function> handlerFactory, + MockedConstruction.MockInitializer mockInitializer) { + throw new MockitoException( + join( + "The used MockMaker " + + getClass().getSimpleName() + + " does not support the creation of construction mocks", + "", + "Mockito's inline mock maker supports construction mocks based on the Instrumentation API.", + "You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.", + "Note that Mockito's inline mock maker is not supported on Android.")); + } + /** * Carries the mockability information * @@ -168,4 +205,16 @@ interface StaticMockControl { void disable(); } + + @Incubating + interface ConstructionMockControl { + + Class getType(); + + void enable(); + + void disable(); + + List getMocks(); + } } diff --git a/src/test/java/org/mockito/MockitoTest.java b/src/test/java/org/mockito/MockitoTest.java index 23df60e08e..b41dd2091b 100644 --- a/src/test/java/org/mockito/MockitoTest.java +++ b/src/test/java/org/mockito/MockitoTest.java @@ -71,6 +71,12 @@ public void shouldGiveExplantionOnStaticMockingWithoutInlineMockMaker() { Mockito.mockStatic(Object.class); } + @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) + @Test(expected = MockitoException.class) + public void shouldGiveExplantionOnConstructionMockingWithoutInlineMockMaker() { + Mockito.mockConstruction(Object.class); + } + @Test public void shouldStartingMockSettingsContainDefaultBehavior() { // when diff --git a/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java b/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java index 906d134d61..9c4ef88d88 100644 --- a/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java +++ b/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java @@ -26,24 +26,28 @@ public class MockAnnotationProcessorTest { @Test public void testNonGeneric() throws Exception { Class type = - MockAnnotationProcessor.inferStaticMock( + MockAnnotationProcessor.inferParameterizedType( MockAnnotationProcessorTest.class .getDeclaredField("nonGeneric") .getGenericType(), - "nonGeneric"); + "nonGeneric", + "Sample"); assertThat(type).isEqualTo(Void.class); } @Test(expected = MockitoException.class) public void testGeneric() throws Exception { - MockAnnotationProcessor.inferStaticMock( + MockAnnotationProcessor.inferParameterizedType( MockAnnotationProcessorTest.class.getDeclaredField("generic").getGenericType(), - "generic"); + "generic", + "Sample"); } @Test(expected = MockitoException.class) public void testRaw() throws Exception { - MockAnnotationProcessor.inferStaticMock( - MockAnnotationProcessorTest.class.getDeclaredField("raw").getGenericType(), "raw"); + MockAnnotationProcessor.inferParameterizedType( + MockAnnotationProcessorTest.class.getDeclaredField("raw").getGenericType(), + "raw", + "Sample"); } } diff --git a/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockRuleTest.java b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockRuleTest.java new file mode 100644 index 0000000000..e53202eb33 --- /dev/null +++ b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockRuleTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitoinline; + +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockedConstruction; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +import static junit.framework.TestCase.*; + +public final class ConstructionMockRuleTest { + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private MockedConstruction dummy; + + @Test + public void testConstructionMockSimple() { + assertNull(new Dummy().foo()); + } + + @Test + public void testConstructionMockCollection() { + assertEquals(0, dummy.constructed().size()); + Dummy mock = new Dummy(); + assertEquals(1, dummy.constructed().size()); + assertTrue(dummy.constructed().contains(mock)); + } + + static class Dummy { + + String foo() { + return "foo"; + } + } +} diff --git a/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java new file mode 100644 index 0000000000..dd5e46d494 --- /dev/null +++ b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitoinline; + +import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; +import org.mockito.exceptions.base.MockitoException; + +import static junit.framework.TestCase.*; +import static org.mockito.Mockito.*; + +public final class ConstructionMockTest { + + @Test + public void testConstructionMockSimple() { + assertEquals("foo", new Dummy().foo()); + try (MockedConstruction ignored = Mockito.mockConstruction(Dummy.class)) { + assertNull(new Dummy().foo()); + } + assertEquals("foo", new Dummy().foo()); + } + + @Test + public void testConstructionMockCollection() { + try (MockedConstruction dummy = Mockito.mockConstruction(Dummy.class)) { + assertEquals(0, dummy.constructed().size()); + Dummy mock = new Dummy(); + assertEquals(1, dummy.constructed().size()); + assertTrue(dummy.constructed().contains(mock)); + } + } + + @Test + public void testConstructionMockDefaultAnswer() { + try (MockedConstruction ignored = Mockito.mockConstructionWithAnswer(Dummy.class, invocation -> "bar")) { + assertEquals("bar", new Dummy().foo()); + } + } + + @Test + public void testConstructionMockDefaultAnswerMultiple() { + try (MockedConstruction ignored = Mockito.mockConstructionWithAnswer(Dummy.class, invocation -> "bar", invocation -> "qux")) { + assertEquals("bar", new Dummy().foo()); + assertEquals("qux", new Dummy().foo()); + assertEquals("qux", new Dummy().foo()); + } + } + + @Test + public void testConstructionMockPrepared() { + try (MockedConstruction ignored = Mockito.mockConstruction(Dummy.class, (mock, context) -> when(mock.foo()).thenReturn("bar"))) { + assertEquals("bar", new Dummy().foo()); + } + } + + + @Test + public void testConstructionMockContext() { + try (MockedConstruction ignored = Mockito.mockConstruction(Dummy.class, (mock, context) -> { + assertEquals(1, context.getCount()); + assertEquals(Collections.singletonList("foobar"), context.arguments()); + assertEquals(mock.getClass().getDeclaredConstructor(String.class), context.constructor()); + when(mock.foo()).thenReturn("bar"); + })) { + assertEquals("bar", new Dummy("foobar").foo()); + } + } + + @Test + public void testConstructionMockDoesNotAffectDifferentThread() throws InterruptedException { + try (MockedConstruction ignored = Mockito.mockConstruction(Dummy.class)) { + Dummy dummy = new Dummy(); + when(dummy.foo()).thenReturn("bar"); + assertEquals("bar", dummy.foo()); + verify(dummy).foo(); + AtomicReference reference = new AtomicReference<>(); + Thread thread = new Thread(() -> reference.set(new Dummy().foo())); + thread.start(); + thread.join(); + assertEquals("foo", reference.get()); + when(dummy.foo()).thenReturn("bar"); + assertEquals("bar", dummy.foo()); + verify(dummy, times(2)).foo(); + } + } + + @Test + public void testConstructionMockCanCoexistWithMockInDifferentThread() throws InterruptedException { + try (MockedConstruction ignored = Mockito.mockConstruction(Dummy.class)) { + Dummy dummy = new Dummy(); + when(dummy.foo()).thenReturn("bar"); + assertEquals("bar", dummy.foo()); + verify(dummy).foo(); + AtomicReference reference = new AtomicReference<>(); + Thread thread = new Thread(() -> { + try (MockedConstruction ignored2 = Mockito.mockConstruction(Dummy.class)) { + Dummy other = new Dummy(); + when(other.foo()).thenReturn("qux"); + reference.set(other.foo()); + } + }); + thread.start(); + thread.join(); + assertEquals("qux", reference.get()); + assertEquals("bar", dummy.foo()); + verify(dummy, times(2)).foo(); + } + } + + @Test(expected = MockitoException.class) + public void testConstructionMockMustBeExclusiveInScopeWithinThread() { + try ( + MockedConstruction dummy = Mockito.mockConstruction(Dummy.class); + MockedConstruction duplicate = Mockito.mockConstruction(Dummy.class) + ) { + fail("Not supposed to allow duplicates"); + } + } + + @Test(expected = MockitoException.class) + public void testConstructionMockMustNotTargetAbstractClass() { + Mockito.mockConstruction(Runnable.class).close(); + } + + static class Dummy { + + + public Dummy() { + } + + public Dummy(String value) { + } + + String foo() { + return "foo"; + } + } +} diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockRuleTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockRuleTest.java new file mode 100644 index 0000000000..c54d6a6cf1 --- /dev/null +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockRuleTest.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitoinline; + +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +import static junit.framework.TestCase.*; + +public final class StaticMockRuleTest { + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Mock + private MockedStatic dummy; + + @Test + public void testStaticMockSimple() { + assertNull(Dummy.foo()); + } + + @Test + public void testStaticMockWithVerification() { + dummy.when(Dummy::foo).thenReturn("bar"); + assertEquals("bar", Dummy.foo()); + dummy.verify(Dummy::foo); + } + + static class Dummy { + + static String foo() { + return "foo"; + } + } +} diff --git a/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java index 57115fa979..06c14d2bb3 100644 --- a/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java +++ b/subprojects/junitJupiterInlineMockMakerExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java @@ -4,10 +4,9 @@ */ package org.mockitousage; -import java.util.UUID; - import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import static org.assertj.core.api.Assertions.*; @@ -15,11 +14,29 @@ class NoExtendsTest { @Mock - private MockedStatic mock; + private MockedStatic staticMethod; + + @Mock + private MockedConstruction construction; + + @Test + void runsStaticMethods() { + assertThat(Dummy.foo()).isNull(); + } @Test - void runs() { - mock.when(UUID::randomUUID).thenReturn(new UUID(123, 456)); - assertThat(UUID.randomUUID()).isEqualTo(new UUID(123, 456)); + void runsConstruction() { + assertThat(new Dummy().bar()).isNull(); + } + + static class Dummy { + + static String foo() { + return "foo"; + } + + String bar() { + return "foo"; + } } } diff --git a/version.properties b/version.properties index cb6eb619b2..ce5150c2b8 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.4.7 +version=3.5.0 #Previous version used to generate release notes delta previousVersion=3.4.6 From 19a7d84a04edfca501515b3f5cfc462f90e3ca6b Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 16 Jul 2020 22:43:04 +0200 Subject: [PATCH 070/963] Implements mocking for constructor invocations. --- .../creation/bytebuddy/InlineByteBuddyMockMaker.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 4afbb827db..66c61d59dd 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -753,8 +753,7 @@ private InlineConstructionMockContext( @Override public int getCount() { if (count == 0) { - throw new MockitoConfigurationException( - "mocked construction context is not initialized"); + throw new MockitoConfigurationException("mocked construction context is not initialized"); } return count; } @@ -768,8 +767,7 @@ public Constructor constructor() { parameterTypes[index++] = PRIMITIVES.get(parameterTypeName); } else { try { - parameterTypes[index++] = - Class.forName(parameterTypeName, false, type.getClassLoader()); + parameterTypes[index++] = Class.forName(parameterTypeName, false, type.getClassLoader()); } catch (ClassNotFoundException e) { throw new MockitoException( "Could not find parameter of type " + parameterTypeName, e); From 24c0e45d1ca7a11baef3b161ed7d615f68ffe5fb Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Fri, 7 Aug 2020 13:04:17 +0200 Subject: [PATCH 071/963] Add invoker API to allow for alternative invocation modes to better support the module system. --- .../IndependentAnnotationEngine.java | 6 +- .../configuration/SpyAnnotationEngine.java | 14 +- .../injection/SpyOnInjectedFieldsHandler.java | 7 +- .../filter/TerminalMockCandidateFilter.java | 22 +- .../plugins/DefaultMockitoPlugins.java | 15 +- .../configuration/plugins/PluginRegistry.java | 22 +- .../configuration/plugins/Plugins.java | 17 +- ...yCrossClassLoaderSerializationSupport.java | 10 +- .../creation/bytebuddy/MockMethodAdvice.java | 17 +- .../instance/ConstructorInstantiator.java | 8 +- .../junit/util/JUnitFailureHacker.java | 10 +- .../matchers/apachecommons/EqualsBuilder.java | 42 +- .../defaultanswers/ForwardsInvocations.java | 10 +- .../mockito/internal/util/JavaEightUtil.java | 2 +- .../util/reflection/AccessibilityChanger.java | 32 -- .../util/reflection/BeanPropertySetter.java | 13 +- .../internal/util/reflection/FieldCopier.java | 15 - .../util/reflection/FieldInitializer.java | 54 +-- .../internal/util/reflection/FieldReader.java | 7 +- .../internal/util/reflection/FieldSetter.java | 43 --- .../util/reflection/InstanceField.java | 13 +- .../InstrumentationMemberAccessor.java | 363 ++++++++++++++++++ .../util/reflection/LenientCopyTool.java | 13 +- .../util/reflection/ModuleMemberAccessor.java | 48 +++ .../reflection/ReflectionMemberAccessor.java | 82 ++++ .../org/mockito/plugins/MemberAccessor.java | 30 ++ .../java/org/mockito/plugins/MockMaker.java | 2 +- .../reflection/AccessibilityChangerTest.java | 35 -- .../util/reflection/LenientCopyToolTest.java | 12 +- .../util/reflection/MemberAccessorTest.java | 159 ++++++++ .../NoByteCodeDependenciesTest.java | 4 + ...ockInjectionUsingSetterOrPropertyTest.java | 14 +- .../java/org/mockitoutil/ClassLoaders.java | 7 +- .../org.mockito.plugins.MemberAccessor | 1 + .../mockito/moduletest/ModuleAccessTest.java | 71 ++++ .../moduletest/ModuleHandlingTest.java | 162 +------- .../org/mockito/moduletest/ModuleUtil.java | 147 +++++++ .../moduletest/ReplicatingClassLoader.java | 5 + 38 files changed, 1098 insertions(+), 436 deletions(-) delete mode 100644 src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java delete mode 100644 src/main/java/org/mockito/internal/util/reflection/FieldCopier.java delete mode 100644 src/main/java/org/mockito/internal/util/reflection/FieldSetter.java create mode 100644 src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java create mode 100644 src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java create mode 100644 src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java create mode 100644 src/main/java/org/mockito/plugins/MemberAccessor.java delete mode 100644 src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java create mode 100644 src/test/java/org/mockito/internal/util/reflection/MemberAccessorTest.java create mode 100644 subprojects/inline/src/main/resources/mockito-extensions/org.mockito.plugins.MemberAccessor create mode 100644 subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleAccessTest.java create mode 100644 subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleUtil.java diff --git a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java index 24cb7a1cb2..566dc1458f 100644 --- a/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/IndependentAnnotationEngine.java @@ -5,7 +5,6 @@ package org.mockito.internal.configuration; import static org.mockito.internal.exceptions.Reporter.moreThanOneAnnotationNotAllowed; -import static org.mockito.internal.util.reflection.FieldSetter.setField; import java.lang.annotation.Annotation; import java.lang.reflect.Field; @@ -19,7 +18,9 @@ import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.plugins.AnnotationEngine; +import org.mockito.plugins.MemberAccessor; /** * Initializes fields annotated with @{@link org.mockito.Mock} or @{@link org.mockito.Captor}. @@ -76,8 +77,9 @@ public AutoCloseable process(Class clazz, Object testInstance) { if (mock != null) { throwIfAlreadyAssigned(field, alreadyAssigned); alreadyAssigned = true; + final MemberAccessor accessor = Plugins.getMemberAccessor(); try { - setField(testInstance, field, mock); + accessor.set(field, testInstance, mock); } catch (Exception e) { for (MockedStatic mockedStatic : mockedStatics) { mockedStatic.close(); diff --git a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java index b4686b30d8..b7a4a2cef9 100644 --- a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java +++ b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java @@ -22,8 +22,10 @@ import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.MockUtil; import org.mockito.plugins.AnnotationEngine; +import org.mockito.plugins.MemberAccessor; /** * Process fields annotated with @Spy. @@ -50,23 +52,23 @@ public class SpyAnnotationEngine @Override public AutoCloseable process(Class context, Object testInstance) { Field[] fields = context.getDeclaredFields(); + MemberAccessor accessor = Plugins.getMemberAccessor(); for (Field field : fields) { if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) { assertNoIncompatibleAnnotations(Spy.class, field, Mock.class, Captor.class); - field.setAccessible(true); Object instance; try { - instance = field.get(testInstance); + instance = accessor.get(field, testInstance); if (MockUtil.isMock(instance)) { // instance has been spied earlier // for example happens when MockitoAnnotations.openMocks is called two // times. Mockito.reset(instance); } else if (instance != null) { - field.set(testInstance, spyInstance(field, instance)); + accessor.set(field, testInstance, spyInstance(field, instance)); } else { - field.set(testInstance, spyNewInstance(testInstance, field)); + accessor.set(field, testInstance, spyNewInstance(testInstance, field)); } } catch (Exception e) { throw new MockitoException( @@ -123,8 +125,8 @@ private static Object spyNewInstance(Object testInstance, Field field) Constructor constructor = noArgConstructorOf(type); if (Modifier.isPrivate(constructor.getModifiers())) { - constructor.setAccessible(true); - return Mockito.mock(type, settings.spiedInstance(constructor.newInstance())); + MemberAccessor accessor = Plugins.getMemberAccessor(); + return Mockito.mock(type, settings.spiedInstance(accessor.newInstance(constructor))); } else { return Mockito.mock(type, settings.useConstructor()); } 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 cd8fcc5e3a..6230e1b86f 100644 --- a/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java +++ b/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java @@ -5,7 +5,6 @@ package org.mockito.internal.configuration.injection; import static org.mockito.Mockito.withSettings; -import static org.mockito.internal.util.reflection.FieldSetter.setField; import java.lang.reflect.Field; import java.util.Set; @@ -13,8 +12,10 @@ import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.MockUtil; import org.mockito.internal.util.reflection.FieldReader; +import org.mockito.plugins.MemberAccessor; /** * Handler for field annotated with @InjectMocks and @Spy. @@ -26,6 +27,8 @@ */ public class SpyOnInjectedFieldsHandler extends MockInjectionStrategy { + private final MemberAccessor accessor = Plugins.getMemberAccessor(); + @Override protected boolean processInjection(Field field, Object fieldOwner, Set mockCandidates) { FieldReader fieldReader = new FieldReader(fieldOwner, field); @@ -46,7 +49,7 @@ protected boolean processInjection(Field field, Object fieldOwner, Set m .spiedInstance(instance) .defaultAnswer(Mockito.CALLS_REAL_METHODS) .name(field.getName())); - setField(fieldOwner, field, mock); + accessor.set(field, fieldOwner, mock); } } catch (Exception e) { throw new MockitoException("Problems initiating spied field " + field.getName(), e); 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 a682d92320..6c3c329b67 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 @@ -5,13 +5,14 @@ package org.mockito.internal.configuration.injection.filter; import static org.mockito.internal.exceptions.Reporter.cannotInjectDependency; -import static org.mockito.internal.util.reflection.FieldSetter.setField; import java.lang.reflect.Field; import java.util.Collection; import java.util.List; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.reflection.BeanPropertySetter; +import org.mockito.plugins.MemberAccessor; /** * This node returns an actual injecter which will be either : @@ -30,18 +31,17 @@ public OngoingInjector filterCandidate( 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); - } - } catch (RuntimeException e) { - throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e); + MemberAccessor accessor = Plugins.getMemberAccessor(); + return () -> { + try { + if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected) + .set(matchingMock)) { + accessor.set(candidateFieldToBeInjected, injectee, matchingMock); } - return matchingMock; + } catch (RuntimeException | IllegalAccessException e) { + throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e); } + return matchingMock; }; } 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 46bf3a7c0e..f3192cba5a 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java @@ -8,19 +8,13 @@ import java.util.Map; import org.mockito.internal.creation.instance.InstantiatorProvider2Adapter; -import org.mockito.plugins.AnnotationEngine; -import org.mockito.plugins.InstantiatorProvider; -import org.mockito.plugins.InstantiatorProvider2; -import org.mockito.plugins.MockMaker; -import org.mockito.plugins.MockitoLogger; -import org.mockito.plugins.MockitoPlugins; -import org.mockito.plugins.PluginSwitch; -import org.mockito.plugins.StackTraceCleanerProvider; +import org.mockito.plugins.*; class DefaultMockitoPlugins implements MockitoPlugins { private static final Map DEFAULT_PLUGINS = new HashMap(); static final String INLINE_ALIAS = "mock-maker-inline"; + static final String MODULE_ALIAS = "member-accessor-module"; static { // Keep the mapping: plugin interface name -> plugin implementation class name @@ -41,6 +35,11 @@ class DefaultMockitoPlugins implements MockitoPlugins { INLINE_ALIAS, "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker"); DEFAULT_PLUGINS.put( MockitoLogger.class.getName(), "org.mockito.internal.util.ConsoleMockitoLogger"); + DEFAULT_PLUGINS.put( + MemberAccessor.class.getName(), + "org.mockito.internal.util.reflection.ReflectionMemberAccessor"); + DEFAULT_PLUGINS.put( + MODULE_ALIAS, "org.mockito.internal.util.reflection.ModuleMemberAccessor"); } @Override 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 0419001285..ba7aae1728 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java @@ -5,13 +5,7 @@ package org.mockito.internal.configuration.plugins; import org.mockito.internal.creation.instance.InstantiatorProviderAdapter; -import org.mockito.plugins.AnnotationEngine; -import org.mockito.plugins.InstantiatorProvider; -import org.mockito.plugins.InstantiatorProvider2; -import org.mockito.plugins.MockMaker; -import org.mockito.plugins.MockitoLogger; -import org.mockito.plugins.PluginSwitch; -import org.mockito.plugins.StackTraceCleanerProvider; +import org.mockito.plugins.*; class PluginRegistry { @@ -22,6 +16,10 @@ class PluginRegistry { new PluginLoader(pluginSwitch, DefaultMockitoPlugins.INLINE_ALIAS) .loadPlugin(MockMaker.class); + private final MemberAccessor memberAccessor = + new PluginLoader(pluginSwitch, DefaultMockitoPlugins.MODULE_ALIAS) + .loadPlugin(MemberAccessor.class); + private final StackTraceCleanerProvider stackTraceCleanerProvider = new PluginLoader(pluginSwitch).loadPlugin(StackTraceCleanerProvider.class); @@ -62,6 +60,16 @@ MockMaker getMockMaker() { return mockMaker; } + /** + * Returns the implementation of the member accessor available for the current runtime. + * + *

    Returns {@link org.mockito.internal.util.reflection.ReflectionMemberAccessor} if no + * {@link org.mockito.plugins.MockMaker} extension exists or is visible in the current classpath.

    + */ + MemberAccessor getMemberAccessor() { + return memberAccessor; + } + /** * Returns the instantiator provider available for the current runtime. * 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 8469981202..603a03008a 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java @@ -4,12 +4,7 @@ */ package org.mockito.internal.configuration.plugins; -import org.mockito.plugins.AnnotationEngine; -import org.mockito.plugins.InstantiatorProvider2; -import org.mockito.plugins.MockMaker; -import org.mockito.plugins.MockitoLogger; -import org.mockito.plugins.MockitoPlugins; -import org.mockito.plugins.StackTraceCleanerProvider; +import org.mockito.plugins.*; /** * Access to Mockito behavior that can be reconfigured by plugins @@ -35,6 +30,16 @@ public static MockMaker getMockMaker() { return registry.getMockMaker(); } + /** + * Returns the implementation of the member accessor available for the current runtime. + * + *

    Returns default member accessor if no + * {@link org.mockito.plugins.MemberAccessor} extension exists or is visible in the current classpath.

    + */ + public static MemberAccessor getMemberAccessor() { + return registry.getMemberAccessor(); + } + /** * Returns the instantiator provider available for the current runtime. * 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 4bb4405e73..90ccee882c 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java @@ -6,7 +6,6 @@ import static org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.ForWriteReplace; import static org.mockito.internal.util.StringUtil.join; -import static org.mockito.internal.util.reflection.FieldSetter.setField; import java.io.*; import java.lang.reflect.Field; @@ -22,6 +21,7 @@ import org.mockito.mock.MockCreationSettings; import org.mockito.mock.MockName; import org.mockito.mock.SerializableMode; +import org.mockito.plugins.MemberAccessor; /** * This is responsible for serializing a mock, it is enabled if the mock is implementing {@link Serializable}. @@ -318,8 +318,14 @@ protected Class resolveClass(ObjectStreamClass desc) private void hackClassNameToMatchNewlyCreatedClass( ObjectStreamClass descInstance, Class proxyClass) throws ObjectStreamException { try { + MemberAccessor accessor = Plugins.getMemberAccessor(); Field classNameField = descInstance.getClass().getDeclaredField("name"); - setField(descInstance, classNameField, proxyClass.getCanonicalName()); + try { + accessor.set(classNameField, descInstance, proxyClass.getCanonicalName()); + } catch (IllegalAccessException e) { + throw new MockitoSerializationIssue( + "Access to " + classNameField + " was denied", e); + } } catch (NoSuchFieldException nsfe) { throw new MockitoSerializationIssue( join( 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 072a958577..01f64563a2 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -12,7 +12,6 @@ import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.Map; import java.util.concurrent.Callable; @@ -24,6 +23,7 @@ import net.bytebuddy.implementation.bind.annotation.This; import net.bytebuddy.implementation.bytecode.assign.Assigner; import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher; import org.mockito.internal.debugging.LocationImpl; import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter; @@ -33,6 +33,7 @@ import org.mockito.internal.invocation.mockref.MockWeakReference; import org.mockito.internal.util.concurrent.DetachedThreadLocal; import org.mockito.internal.util.concurrent.WeakConcurrentMap; +import org.mockito.plugins.MemberAccessor; public class MockMethodAdvice extends MockMethodDispatcher { @@ -208,10 +209,6 @@ public boolean isInvokable() { @Override public Object invoke() throws Throwable { - if (!Modifier.isPublic( - origin.getDeclaringClass().getModifiers() & origin.getModifiers())) { - origin.setAccessible(true); - } selfCallInfo.set(instanceRef.get()); return tryInvoke(origin, instanceRef.get(), arguments); } @@ -243,10 +240,6 @@ public boolean isInvokable() { @Override public Object invoke() throws Throwable { Method method = origin.getJavaMethod(); - if (!Modifier.isPublic( - method.getDeclaringClass().getModifiers() & method.getModifiers())) { - method.setAccessible(true); - } MockMethodDispatcher mockMethodDispatcher = MockMethodDispatcher.get(identifier, instanceRef.get()); if (!(mockMethodDispatcher instanceof MockMethodAdvice)) { @@ -288,9 +281,6 @@ public boolean isInvokable() { @Override public Object invoke() throws Throwable { - if (!Modifier.isPublic(type.getModifiers() & origin.getModifiers())) { - origin.setAccessible(true); - } selfCallInfo.set(type); return tryInvoke(origin, null, arguments); } @@ -298,8 +288,9 @@ public Object invoke() throws Throwable { private static Object tryInvoke(Method origin, Object instance, Object[] arguments) throws Throwable { + MemberAccessor accessor = Plugins.getMemberAccessor(); try { - return origin.invoke(instance, arguments); + return accessor.invoke(origin, instance, arguments); } catch (InvocationTargetException exception) { Throwable cause = exception.getCause(); new ConditionalStackTraceFilter() 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 94e12fa86a..13f11d7419 100644 --- a/src/main/java/org/mockito/internal/creation/instance/ConstructorInstantiator.java +++ b/src/main/java/org/mockito/internal/creation/instance/ConstructorInstantiator.java @@ -14,8 +14,9 @@ import org.mockito.creation.instance.InstantiationException; import org.mockito.creation.instance.Instantiator; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.Primitives; -import org.mockito.internal.util.reflection.AccessibilityChanger; +import org.mockito.plugins.MemberAccessor; public class ConstructorInstantiator implements Instantiator { @@ -64,9 +65,8 @@ private T withParams(Class cls, Object... params) { 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); + MemberAccessor accessor = Plugins.getMemberAccessor(); + return (T) accessor.newInstance(constructor, params); } private InstantiationException paramsException(Class cls, Exception e) { 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 89bd4f1f4b..d6e784c647 100644 --- a/src/main/java/org/mockito/internal/junit/util/JUnitFailureHacker.java +++ b/src/main/java/org/mockito/internal/junit/util/JUnitFailureHacker.java @@ -7,7 +7,9 @@ import java.lang.reflect.Field; import org.junit.runner.notification.Failure; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.exceptions.ExceptionIncludingMockitoWarnings; +import org.mockito.plugins.MemberAccessor; @Deprecated public class JUnitFailureHacker { @@ -36,11 +38,11 @@ private boolean isEmpty(String warnings) { } private static Object getInternalState(Object target, String field) { + MemberAccessor accessor = Plugins.getMemberAccessor(); Class c = target.getClass(); try { Field f = getFieldFromHierarchy(c, field); - f.setAccessible(true); - return f.get(target); + return accessor.get(f, target); } catch (Exception e) { throw new RuntimeException( "Unable to get internal state on a private field. Please report to mockito mailing list.", @@ -49,11 +51,11 @@ private static Object getInternalState(Object target, String field) { } private static void setInternalState(Object target, String field, Object value) { + MemberAccessor accessor = Plugins.getMemberAccessor(); Class c = target.getClass(); try { Field f = getFieldFromHierarchy(c, field); - f.setAccessible(true); - f.set(target, value); + accessor.set(f, target, value); } catch (Exception e) { throw new RuntimeException( "Unable to set internal state on a private field. Please report to mockito mailing list.", 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 9a43040e34..1789a5d7a3 100644 --- a/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java +++ b/src/main/java/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java @@ -4,7 +4,9 @@ */ package org.mockito.internal.matchers.apachecommons; -import java.lang.reflect.AccessibleObject; +import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.plugins.MemberAccessor; + import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; @@ -253,20 +255,16 @@ public static boolean reflectionEquals( return false; } EqualsBuilder equalsBuilder = new EqualsBuilder(); - try { - reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); - while (testClass.getSuperclass() != null && testClass != reflectUpToClass) { - testClass = testClass.getSuperclass(); - reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); - } - } catch (IllegalArgumentException e) { - // In this case, we tried to test a subclass vs. a superclass and - // the subclass has ivars or the ivars are transient and - // we are testing transients. - // If a subclass has ivars that we are trying to test them, we get an - // exception and we know that the objects are not equal. + if (reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields)) { return false; } + while (testClass.getSuperclass() != null && testClass != reflectUpToClass) { + testClass = testClass.getSuperclass(); + if (reflectionAppend( + lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields)) { + return false; + } + } return equalsBuilder.isEquals(); } @@ -281,7 +279,7 @@ public static boolean reflectionEquals( * @param useTransients whether to test transient fields * @param excludeFields array of field names to exclude from testing */ - private static void reflectionAppend( + private static boolean reflectionAppend( Object lhs, Object rhs, Class clazz, @@ -293,7 +291,7 @@ private static void reflectionAppend( excludeFields != null ? Arrays.asList(excludeFields) : Collections.emptyList(); - AccessibleObject.setAccessible(fields, true); + MemberAccessor accessor = Plugins.getMemberAccessor(); for (int i = 0; i < fields.length && builder.isEquals; i++) { Field f = fields[i]; if (!excludedFieldList.contains(f.getName()) @@ -301,14 +299,18 @@ private static void reflectionAppend( && (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. - throw new InternalError("Unexpected IllegalAccessException"); + builder.append(accessor.get(f, lhs), accessor.get(f, rhs)); + } catch (RuntimeException | IllegalAccessException ignored) { + // In this case, we tried to test a subclass vs. a superclass and + // the subclass has ivars or the ivars are transient and we are + // testing transients. If a subclass has ivars that we are trying + // to test them, we get an exception and we know that the objects + // are not equal. + return true; } } } + return false; } // ------------------------------------------------------------------------- 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 0df0f6c3ef..0f2aaa3975 100644 --- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java +++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java @@ -11,8 +11,10 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.invocation.Invocation; import org.mockito.invocation.InvocationOnMock; +import org.mockito.plugins.MemberAccessor; import org.mockito.stubbing.Answer; /** @@ -41,13 +43,9 @@ public Object answer(InvocationOnMock invocation) throws Throwable { mockMethod, delegateMethod, invocation.getMock(), delegatedObject); } + MemberAccessor accessor = Plugins.getMemberAccessor(); Object[] rawArguments = ((Invocation) invocation).getRawArguments(); - try { - delegateMethod.setAccessible(true); - } catch (SecurityException ignore) { - // try to invoke anyway - } - return delegateMethod.invoke(delegatedObject, rawArguments); + return accessor.invoke(delegateMethod, delegatedObject, rawArguments); } catch (NoSuchMethodException e) { throw delegatedMethodDoesNotExistOnDelegate( mockMethod, invocation.getMock(), delegatedObject); diff --git a/src/main/java/org/mockito/internal/util/JavaEightUtil.java b/src/main/java/org/mockito/internal/util/JavaEightUtil.java index bc39d44b68..20c6e80c3b 100644 --- a/src/main/java/org/mockito/internal/util/JavaEightUtil.java +++ b/src/main/java/org/mockito/internal/util/JavaEightUtil.java @@ -181,7 +181,7 @@ private static Object invokeNullaryFactoryMethod(final String fqcn, final String private static Object getStaticFieldValue(final String fqcn, final String fieldName) { try { final Class type = getClass(fqcn); - final Field field = type.getDeclaredField(fieldName); + final Field field = type.getField(fieldName); return field.get(null); // any exception is really unexpected since the type name has // already been verified diff --git a/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java b/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java deleted file mode 100644 index 33725e0137..0000000000 --- a/src/main/java/org/mockito/internal/util/reflection/AccessibilityChanger.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2007 Mockito contributors - * This program is made available under the terms of the MIT License. - */ -package org.mockito.internal.util.reflection; - -import java.lang.reflect.AccessibleObject; - -public class AccessibilityChanger { - - private Boolean wasAccessible = null; - - /** - * safely disables access - */ - public void safelyDisableAccess(AccessibleObject accessibleObject) { - assert wasAccessible != null : "accessibility info shall not be null"; - try { - accessibleObject.setAccessible(wasAccessible); - } catch (Throwable t) { - // ignore - } - } - - /** - * changes the accessibleObject accessibility and returns true if accessibility was changed - */ - public void enableAccess(AccessibleObject accessibleObject) { - wasAccessible = accessibleObject.isAccessible(); - accessibleObject.setAccessible(true); - } -} 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 f91a35c202..7a33dcec7b 100644 --- a/src/main/java/org/mockito/internal/util/reflection/BeanPropertySetter.java +++ b/src/main/java/org/mockito/internal/util/reflection/BeanPropertySetter.java @@ -4,6 +4,9 @@ */ package org.mockito.internal.util.reflection; +import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.plugins.MemberAccessor; + import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -51,13 +54,11 @@ public BeanPropertySetter(final Object target, final Field propertyField) { */ public boolean set(final Object value) { - AccessibilityChanger changer = new AccessibilityChanger(); + MemberAccessor accessor = Plugins.getMemberAccessor(); Method writeMethod = null; try { writeMethod = target.getClass().getMethod(setterName(field.getName()), field.getType()); - - changer.enableAccess(writeMethod); - writeMethod.invoke(target, value); + accessor.invoke(writeMethod, target, value); return true; } catch (InvocationTargetException e) { throw new RuntimeException( @@ -83,10 +84,6 @@ public boolean set(final Object value) { e); } catch (NoSuchMethodException e) { reportNoSetterFound(); - } finally { - if (writeMethod != null) { - changer.safelyDisableAccess(writeMethod); - } } reportNoSetterFound(); diff --git a/src/main/java/org/mockito/internal/util/reflection/FieldCopier.java b/src/main/java/org/mockito/internal/util/reflection/FieldCopier.java deleted file mode 100644 index 67f7203944..0000000000 --- a/src/main/java/org/mockito/internal/util/reflection/FieldCopier.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2007 Mockito contributors - * This program is made available under the terms of the MIT License. - */ -package org.mockito.internal.util.reflection; - -import java.lang.reflect.Field; - -public class FieldCopier { - - public void copyValue(T from, T to, Field field) throws IllegalAccessException { - Object value = field.get(from); - field.set(to, value); - } -} 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 a5c5d708b5..53bc8a1f6a 100644 --- a/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java +++ b/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java @@ -4,9 +4,10 @@ */ package org.mockito.internal.util.reflection; -import static java.lang.reflect.Modifier.isStatic; - -import static org.mockito.internal.util.reflection.FieldSetter.setField; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.internal.util.MockUtil; +import org.mockito.plugins.MemberAccessor; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -17,8 +18,7 @@ import java.util.Comparator; import java.util.List; -import org.mockito.exceptions.base.MockitoException; -import org.mockito.internal.util.MockUtil; +import static java.lang.reflect.Modifier.isStatic; /** * Initialize a field with type instance if a default constructor can be found. @@ -87,9 +87,6 @@ private FieldInitializer(Object fieldOwner, Field field, ConstructorInstantiator * @return Actual field instance. */ public FieldInitializationReport initialize() { - final AccessibilityChanger changer = new AccessibilityChanger(); - changer.enableAccess(field); - try { return acquireFieldInstance(); } catch (IllegalAccessException e) { @@ -100,8 +97,6 @@ public FieldInitializationReport initialize() { + field.getType().getSimpleName() + "'", e); - } finally { - changer.safelyDisableAccess(field); } } @@ -142,7 +137,8 @@ private void checkNotEnum(Field field) { } private FieldInitializationReport acquireFieldInstance() throws IllegalAccessException { - Object fieldInstance = field.get(fieldOwner); + final MemberAccessor accessor = Plugins.getMemberAccessor(); + Object fieldInstance = accessor.get(field, fieldOwner); if (fieldInstance != null) { return new FieldInitializationReport(fieldInstance, false, false); } @@ -198,17 +194,15 @@ static class NoArgConstructorInstantiator implements ConstructorInstantiator { } public FieldInitializationReport instantiate() { - final AccessibilityChanger changer = new AccessibilityChanger(); - Constructor constructor = null; + final MemberAccessor invoker = Plugins.getMemberAccessor(); try { - constructor = field.getType().getDeclaredConstructor(); - changer.enableAccess(constructor); + Constructor constructor = field.getType().getDeclaredConstructor(); final Object[] noArg = new Object[0]; - Object newFieldInstance = constructor.newInstance(noArg); - setField(testClass, field, newFieldInstance); + Object newFieldInstance = invoker.newInstance(constructor, noArg); + invoker.set(field, testClass, newFieldInstance); - return new FieldInitializationReport(field.get(testClass), true, false); + return new FieldInitializationReport(invoker.get(field, testClass), true, false); } catch (NoSuchMethodException e) { throw new MockitoException( "the type '" @@ -230,10 +224,6 @@ public FieldInitializationReport instantiate() { throw new MockitoException( "IllegalAccessException (see the stack trace for cause): " + e.toString(), e); - } finally { - if (constructor != null) { - changer.safelyDisableAccess(constructor); - } } } } @@ -289,18 +279,14 @@ private int countMockableParams(Constructor constructor) { } public FieldInitializationReport instantiate() { - final AccessibilityChanger changer = new AccessibilityChanger(); - Constructor constructor = null; + final MemberAccessor accessor = Plugins.getMemberAccessor(); + Constructor constructor = biggestConstructor(field.getType()); + final Object[] args = argResolver.resolveTypeInstances(constructor.getParameterTypes()); try { - constructor = biggestConstructor(field.getType()); - changer.enableAccess(constructor); - - final Object[] args = - argResolver.resolveTypeInstances(constructor.getParameterTypes()); - Object newFieldInstance = constructor.newInstance(args); - setField(testClass, field, newFieldInstance); + Object newFieldInstance = accessor.newInstance(constructor, args); + accessor.set(field, testClass, newFieldInstance); - return new FieldInitializationReport(field.get(testClass), false, true); + return new FieldInitializationReport(accessor.get(field, testClass), false, true); } catch (IllegalArgumentException e) { throw new MockitoException( "internal error : argResolver provided incorrect types for constructor " @@ -323,10 +309,6 @@ public FieldInitializationReport instantiate() { throw new MockitoException( "IllegalAccessException (see the stack trace for cause): " + e.toString(), e); - } finally { - if (constructor != null) { - changer.safelyDisableAccess(constructor); - } } } 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 707eee6515..e202c714a0 100644 --- a/src/main/java/org/mockito/internal/util/reflection/FieldReader.java +++ b/src/main/java/org/mockito/internal/util/reflection/FieldReader.java @@ -7,17 +7,18 @@ import java.lang.reflect.Field; import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.plugins.MemberAccessor; public class FieldReader { final Object target; final Field field; - final AccessibilityChanger changer = new AccessibilityChanger(); + final MemberAccessor accessor = Plugins.getMemberAccessor(); public FieldReader(Object target, Field field) { this.target = target; this.field = field; - changer.enableAccess(field); } public boolean isNull() { @@ -26,7 +27,7 @@ public boolean isNull() { public Object read() { try { - return field.get(target); + return accessor.get(field, target); } catch (Exception e) { 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 deleted file mode 100644 index 46f906d9bf..0000000000 --- a/src/main/java/org/mockito/internal/util/reflection/FieldSetter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2007 Mockito contributors - * This program is made available under the terms of the MIT License. - */ -package org.mockito.internal.util.reflection; - -import java.lang.reflect.Field; - -public class FieldSetter { - - private FieldSetter() {} - - 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); - } catch (IllegalArgumentException 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/InstanceField.java b/src/main/java/org/mockito/internal/util/reflection/InstanceField.java index 5585874f46..03cd02c051 100644 --- a/src/main/java/org/mockito/internal/util/reflection/InstanceField.java +++ b/src/main/java/org/mockito/internal/util/reflection/InstanceField.java @@ -4,12 +4,13 @@ */ package org.mockito.internal.util.reflection; -import static org.mockito.internal.util.reflection.FieldSetter.setField; - import java.lang.annotation.Annotation; import java.lang.reflect.Field; +import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.Checks; +import org.mockito.plugins.MemberAccessor; /** * Represents an accessible instance field. @@ -47,10 +48,14 @@ public Object read() { * Set the given value to the field of this instance. * * @param value The value that should be written to the field. - * @see FieldSetter */ public void set(Object value) { - setField(instance, field, value); + MemberAccessor accessor = Plugins.getMemberAccessor(); + try { + accessor.set(field, instance, value); + } catch (IllegalAccessException e) { + throw new MockitoException("Access to " + field + " was denied", e); + } } /** diff --git a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java new file mode 100644 index 0000000000..c74c79efa6 --- /dev/null +++ b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.util.reflection; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.agent.ByteBuddyAgent; +import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; +import net.bytebuddy.implementation.MethodCall; +import org.mockito.exceptions.base.MockitoInitializationException; +import org.mockito.plugins.MemberAccessor; + +import java.lang.instrument.Instrumentation; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.*; +import java.util.*; + +import static net.bytebuddy.matcher.ElementMatchers.named; +import static org.mockito.internal.util.StringUtil.join; + +class InstrumentationMemberAccessor implements MemberAccessor { + + private static final Map, Class> WRAPPERS = new HashMap<>(); + + private static final Instrumentation INSTRUMENTATION; + private static final Dispatcher DISPATCHER; + + private static final Throwable INITIALIZATION_ERROR; + + static { + WRAPPERS.put(boolean.class, Boolean.class); + WRAPPERS.put(byte.class, Byte.class); + WRAPPERS.put(short.class, Short.class); + WRAPPERS.put(char.class, Character.class); + WRAPPERS.put(int.class, Integer.class); + WRAPPERS.put(long.class, Long.class); + WRAPPERS.put(float.class, Float.class); + WRAPPERS.put(double.class, Double.class); + Instrumentation instrumentation; + Dispatcher dispatcher; + Throwable throwable; + try { + instrumentation = ByteBuddyAgent.install(); + // We need to generate a dispatcher instance that is located in a distinguished class + // loader to create a unique (unnamed) module to which we can open other packages to. + // This way, we assure that classes within Mockito's module (which might be a shared, + // unnamed module) do not face escalated privileges where tests might pass that would + // otherwise fail without Mockito's opening. + dispatcher = + new ByteBuddy() + .subclass(Dispatcher.class) + .method(named("getLookup")) + .intercept(MethodCall.invoke(MethodHandles.class.getMethod("lookup"))) + .method(named("getModule")) + .intercept( + MethodCall.invoke(Class.class.getMethod("getModule")) + .onMethodCall( + MethodCall.invoke( + Object.class.getMethod("getClass")))) + .method(named("setAccessible")) + .intercept( + MethodCall.invoke( + AccessibleObject.class.getMethod( + "setAccessible", boolean.class)) + .onArgument(0) + .withArgument(1)) + .make() + .load( + InstrumentationMemberAccessor.class.getClassLoader(), + ClassLoadingStrategy.Default.WRAPPER) + .getLoaded() + .getConstructor() + .newInstance(); + throwable = null; + } catch (Throwable t) { + instrumentation = null; + dispatcher = null; + throwable = t; + } + INSTRUMENTATION = instrumentation; + DISPATCHER = dispatcher; + INITIALIZATION_ERROR = throwable; + } + + private final MethodHandle getModule, isOpen, redefineModule, privateLookupIn; + + InstrumentationMemberAccessor() { + if (INITIALIZATION_ERROR != null) { + throw new MockitoInitializationException( + join( + "Could not initialize the Mockito instrumentation member accessor", + "", + "This is unexpected on JVMs from Java 9 or later - possibly, the instrumentation API could not be resolved"), + INITIALIZATION_ERROR); + } + try { + Class module = Class.forName("java.lang.Module"); + getModule = + MethodHandles.publicLookup() + .findVirtual(Class.class, "getModule", MethodType.methodType(module)); + isOpen = + MethodHandles.publicLookup() + .findVirtual( + module, + "isOpen", + MethodType.methodType(boolean.class, String.class, module)); + redefineModule = + MethodHandles.publicLookup() + .findVirtual( + Instrumentation.class, + "redefineModule", + MethodType.methodType( + void.class, + module, + Set.class, + Map.class, + Map.class, + Set.class, + Map.class)); + privateLookupIn = + MethodHandles.publicLookup() + .findStatic( + MethodHandles.class, + "privateLookupIn", + MethodType.methodType( + MethodHandles.Lookup.class, + Class.class, + MethodHandles.Lookup.class)); + } catch (Throwable t) { + throw new MockitoInitializationException( + "Could not resolve instrumentation invoker", t); + } + } + + @Override + public Object newInstance(Constructor constructor, Object... arguments) + throws InstantiationException, InvocationTargetException { + if (Modifier.isAbstract(constructor.getDeclaringClass().getModifiers())) { + throw new InstantiationException( + "Cannot instantiate abstract " + constructor.getDeclaringClass().getTypeName()); + } + assureArguments(constructor, null, null, arguments, constructor.getParameterTypes()); + try { + Object module = getModule.bindTo(constructor.getDeclaringClass()).invokeWithArguments(); + String packageName = constructor.getDeclaringClass().getPackage().getName(); + assureOpen(module, packageName); + MethodHandle handle = + ((MethodHandles.Lookup) + privateLookupIn.invokeExact( + constructor.getDeclaringClass(), + DISPATCHER.getLookup())) + .unreflectConstructor(constructor); + try { + return handle.invokeWithArguments(arguments); + } catch (Throwable t) { + throw new InvocationTargetException(t); + } + } catch (InvocationTargetException e) { + throw e; + } catch (Throwable t) { + throw new IllegalStateException( + "Could not construct " + + constructor + + " with arguments " + + Arrays.toString(arguments), + t); + } + } + + @Override + public Object invoke(Method method, Object target, Object... arguments) + throws InvocationTargetException { + assureArguments( + method, + Modifier.isStatic(method.getModifiers()) ? null : target, + method.getDeclaringClass(), + arguments, + method.getParameterTypes()); + try { + Object module = getModule.bindTo(method.getDeclaringClass()).invokeWithArguments(); + String packageName = method.getDeclaringClass().getPackage().getName(); + assureOpen(module, packageName); + MethodHandle handle = + ((MethodHandles.Lookup) + privateLookupIn.invokeExact( + method.getDeclaringClass(), DISPATCHER.getLookup())) + .unreflect(method); + if (!Modifier.isStatic(method.getModifiers())) { + handle = handle.bindTo(target); + } + try { + return handle.invokeWithArguments(arguments); + } catch (Throwable t) { + throw new InvocationTargetException(t); + } + } catch (InvocationTargetException e) { + throw e; + } catch (Throwable t) { + throw new IllegalStateException( + "Could not invoke " + + method + + " on " + + target + + " with arguments " + + Arrays.toString(arguments), + t); + } + } + + @Override + public Object get(Field field, Object target) { + assureArguments( + field, + Modifier.isStatic(field.getModifiers()) ? null : target, + field.getDeclaringClass(), + new Object[0], + new Class[0]); + try { + Object module = getModule.bindTo(field.getDeclaringClass()).invokeWithArguments(); + String packageName = field.getDeclaringClass().getPackage().getName(); + assureOpen(module, packageName); + MethodHandle handle = + ((MethodHandles.Lookup) + privateLookupIn.invokeExact( + field.getDeclaringClass(), DISPATCHER.getLookup())) + .unreflectGetter(field); + if (!Modifier.isStatic(field.getModifiers())) { + handle = handle.bindTo(target); + } + return handle.invokeWithArguments(); + } catch (Throwable t) { + throw new IllegalStateException("Could not read " + field + " on " + target, t); + } + } + + @Override + public void set(Field field, Object target, Object value) throws IllegalAccessException { + assureArguments( + field, + Modifier.isStatic(field.getModifiers()) ? null : target, + field.getDeclaringClass(), + new Object[] {value}, + new Class[] {field.getType()}); + boolean illegalAccess = false; + try { + Object module = getModule.bindTo(field.getDeclaringClass()).invokeWithArguments(); + String packageName = field.getDeclaringClass().getPackage().getName(); + assureOpen(module, packageName); + // Method handles do not allow setting final fields where setAccessible(true) + // is required before unreflecting. + boolean isFinal; + if (Modifier.isFinal(field.getModifiers())) { + isFinal = true; + try { + DISPATCHER.setAccessible(field, true); + } catch (Throwable ignored) { + illegalAccess = + true; // To distinguish from propagated illegal access exception. + throw new IllegalAccessException( + "Could not make final field " + field + " accessible"); + } + } else { + isFinal = false; + } + try { + MethodHandle handle = + ((MethodHandles.Lookup) + privateLookupIn.invokeExact( + field.getDeclaringClass(), DISPATCHER.getLookup())) + .unreflectSetter(field); + if (!Modifier.isStatic(field.getModifiers())) { + handle = handle.bindTo(target); + } + handle.invokeWithArguments(value); + } finally { + if (isFinal) { + DISPATCHER.setAccessible(field, false); + } + } + } catch (Throwable t) { + if (illegalAccess) { + throw (IllegalAccessException) t; + } else { + throw new IllegalStateException("Could not read " + field + " on " + target, t); + } + } + } + + private void assureOpen(Object module, String packageName) throws Throwable { + if (!(Boolean) isOpen.invokeWithArguments(module, packageName, DISPATCHER.getModule())) { + redefineModule + .bindTo(INSTRUMENTATION) + .invokeWithArguments( + module, + Collections.emptySet(), + Collections.emptyMap(), + Collections.singletonMap( + packageName, Collections.singleton(DISPATCHER.getModule())), + Collections.emptySet(), + Collections.emptyMap()); + } + } + + private static void assureArguments( + AccessibleObject target, + Object owner, + Class type, + Object[] values, + Class[] types) { + if (owner != null) { + if (!type.isAssignableFrom(owner.getClass())) { + throw new IllegalArgumentException("Cannot access " + target + " on " + owner); + } + } + if (types.length != values.length) { + throw new IllegalArgumentException( + "Incorrect number of arguments for " + + target + + ": expected " + + types.length + + " but recevied " + + values.length); + } + for (int index = 0; index < values.length; index++) { + if (values[index] == null) { + if (types[index].isPrimitive()) { + throw new IllegalArgumentException( + "Cannot assign null to primitive type " + + types[index].getTypeName() + + " for " + + index + + " parameter of " + + target); + } + } else { + Class resolved = WRAPPERS.getOrDefault(types[index], types[index]); + if (!resolved.isAssignableFrom(values[index].getClass())) { + throw new IllegalArgumentException( + "Cannot assign value of type " + + values[index].getClass() + + " to " + + resolved + + " for " + + index + + " parameter of " + + target); + } + } + } + } + + public interface Dispatcher { + + MethodHandles.Lookup getLookup(); + + Object getModule(); + + void setAccessible(AccessibleObject target, boolean 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 ccdd923835..95b30198db 100644 --- a/src/main/java/org/mockito/internal/util/reflection/LenientCopyTool.java +++ b/src/main/java/org/mockito/internal/util/reflection/LenientCopyTool.java @@ -4,13 +4,15 @@ */ package org.mockito.internal.util.reflection; +import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.plugins.MemberAccessor; + import java.lang.reflect.Field; import java.lang.reflect.Modifier; -@SuppressWarnings("unchecked") public class LenientCopyTool { - FieldCopier fieldCopier = new FieldCopier(); + MemberAccessor accessor = Plugins.getMemberAccessor(); public void copyToMock(T from, T mock) { copy(from, mock, from.getClass()); @@ -35,14 +37,11 @@ private void copyValues(T from, T mock, Class classFrom) { if (Modifier.isStatic(field.getModifiers())) { continue; } - AccessibilityChanger accessibilityChanger = new AccessibilityChanger(); try { - accessibilityChanger.enableAccess(field); - fieldCopier.copyValue(from, mock, field); + Object value = accessor.get(field, from); + accessor.set(field, mock, value); } catch (Throwable t) { // 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/ModuleMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java new file mode 100644 index 0000000000..8be77860ad --- /dev/null +++ b/src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.util.reflection; + +import net.bytebuddy.ClassFileVersion; +import org.mockito.plugins.MemberAccessor; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class ModuleMemberAccessor implements MemberAccessor { + + private final MemberAccessor delegate; + + public ModuleMemberAccessor() { + if (ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V9)) { + delegate = new InstrumentationMemberAccessor(); + } else { + delegate = new ReflectionMemberAccessor(); + } + } + + @Override + public Object newInstance(Constructor constructor, Object... arguments) + throws InstantiationException, InvocationTargetException, IllegalAccessException { + return delegate.newInstance(constructor, arguments); + } + + @Override + public Object invoke(Method method, Object target, Object... arguments) + throws InvocationTargetException, IllegalAccessException { + return delegate.invoke(method, target, arguments); + } + + @Override + public Object get(Field field, Object target) throws IllegalAccessException { + return delegate.get(field, target); + } + + @Override + public void set(Field field, Object target, Object value) throws IllegalAccessException { + delegate.set(field, target, value); + } +} diff --git a/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java new file mode 100644 index 0000000000..e61a5bcc02 --- /dev/null +++ b/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2007 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.util.reflection; + +import org.mockito.plugins.MemberAccessor; + +import java.lang.reflect.*; +import java.util.Arrays; + +public class ReflectionMemberAccessor implements MemberAccessor { + + @Override + public Object newInstance(Constructor constructor, Object... arguments) + throws InstantiationException, InvocationTargetException, IllegalAccessException { + silentSetAccessible(constructor, true); + try { + return constructor.newInstance(arguments); + } catch (InvocationTargetException + | IllegalAccessException + | InstantiationException + | IllegalArgumentException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException( + "Failed to invoke " + constructor + " with " + Arrays.toString(arguments), e); + } finally { + silentSetAccessible(constructor, false); + } + } + + @Override + public Object invoke(Method method, Object target, Object... arguments) + throws InvocationTargetException, IllegalAccessException { + silentSetAccessible(method, true); + try { + return method.invoke(target, arguments); + } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException("Could not invoke " + method + " on " + target, e); + } finally { + silentSetAccessible(method, false); + } + } + + @Override + public Object get(Field field, Object target) throws IllegalAccessException { + silentSetAccessible(field, true); + try { + return field.get(target); + } catch (IllegalAccessException | IllegalArgumentException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException("Could not read " + field + " from " + target); + } finally { + silentSetAccessible(field, false); + } + } + + @Override + public void set(Field field, Object target, Object value) throws IllegalAccessException { + silentSetAccessible(field, true); + try { + field.set(target, value); + } catch (IllegalAccessException | IllegalArgumentException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException("Could not write " + field + " to " + target, e); + } finally { + silentSetAccessible(field, false); + } + } + + private static void silentSetAccessible(AccessibleObject object, boolean value) { + try { + object.setAccessible(value); + } catch (Exception ignored) { + } + } +} diff --git a/src/main/java/org/mockito/plugins/MemberAccessor.java b/src/main/java/org/mockito/plugins/MemberAccessor.java new file mode 100644 index 0000000000..081814e1db --- /dev/null +++ b/src/main/java/org/mockito/plugins/MemberAccessor.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.plugins; + +import org.mockito.Incubating; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * A member accessor is responsible for invoking methods, constructors and for setting + * and reading field values. + */ +@Incubating +public interface MemberAccessor { + + Object newInstance(Constructor constructor, Object... arguments) + throws InstantiationException, InvocationTargetException, IllegalAccessException; + + Object invoke(Method method, Object target, Object... arguments) + throws InvocationTargetException, IllegalAccessException; + + Object get(Field field, Object target) throws IllegalAccessException; + + void set(Field field, Object target, Object value) throws IllegalAccessException; +} diff --git a/src/main/java/org/mockito/plugins/MockMaker.java b/src/main/java/org/mockito/plugins/MockMaker.java index df3ff4210d..dfc852bcbf 100644 --- a/src/main/java/org/mockito/plugins/MockMaker.java +++ b/src/main/java/org/mockito/plugins/MockMaker.java @@ -9,7 +9,7 @@ import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; -import static org.mockito.internal.util.StringUtil.*; +import static org.mockito.internal.util.StringUtil.join; /** * The facility to create mocks. diff --git a/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java b/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java deleted file mode 100644 index 032cb53770..0000000000 --- a/src/test/java/org/mockito/internal/util/reflection/AccessibilityChangerTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2007 Mockito contributors - * This program is made available under the terms of the MIT License. - */ -package org.mockito.internal.util.reflection; - -import static org.mockitoutil.VmArgAssumptions.assumeVmArgPresent; - -import java.lang.reflect.Field; -import java.util.Observable; - -import org.junit.Test; - -public class AccessibilityChangerTest { - - @SuppressWarnings("unused") - private Observable whatever; - - @Test - public void should_enable_and_safely_disable() throws Exception { - AccessibilityChanger changer = new AccessibilityChanger(); - changer.enableAccess(field("whatever")); - changer.safelyDisableAccess(field("whatever")); - } - - @Test(expected = java.lang.AssertionError.class) - public void safelyDisableAccess_should_fail_when_enableAccess_not_called() throws Exception { - assumeVmArgPresent("-ea"); - 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/LenientCopyToolTest.java b/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java index 76ebd337b9..b8c742aff7 100644 --- a/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java @@ -13,6 +13,7 @@ import java.util.LinkedList; import org.junit.Test; +import org.mockito.plugins.MemberAccessor; import org.mockitoutil.TestBase; @SuppressWarnings("unchecked") @@ -144,19 +145,20 @@ public void shouldEnableAndThenDisableAccessibility() throws Exception { @Test public void shouldContinueEvenIfThereAreProblemsCopyingSingleFieldValue() throws Exception { // given - tool.fieldCopier = mock(FieldCopier.class); + tool.accessor = mock(MemberAccessor.class); doNothing() - .doThrow(new IllegalAccessException()) + .doThrow(new IllegalStateException()) .doNothing() - .when(tool.fieldCopier) - .copyValue(anyObject(), anyObject(), any(Field.class)); + .when(tool.accessor) + .set(any(Field.class), anyObject(), anyObject()); // when tool.copyToMock(from, to); // then - verify(tool.fieldCopier, atLeast(3)).copyValue(any(), any(), any(Field.class)); + verify(tool.accessor, atLeast(3)).get(any(Field.class), any()); + verify(tool.accessor, atLeast(3)).set(any(Field.class), any(), any()); } @Test diff --git a/src/test/java/org/mockito/internal/util/reflection/MemberAccessorTest.java b/src/test/java/org/mockito/internal/util/reflection/MemberAccessorTest.java new file mode 100644 index 0000000000..ee390312ed --- /dev/null +++ b/src/test/java/org/mockito/internal/util/reflection/MemberAccessorTest.java @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal.util.reflection; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.plugins.MemberAccessor; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@RunWith(Parameterized.class) +public class MemberAccessorTest { + + @Parameterized.Parameters + public static Collection data() { + List data = new ArrayList<>(); + data.add(new Object[] {new ReflectionMemberAccessor()}); + data.add(new Object[] {new ModuleMemberAccessor()}); + return data; + } + + private final MemberAccessor accessor; + + public MemberAccessorTest(MemberAccessor accessor) { + this.accessor = accessor; + } + + @Test + public void test_read_field() throws Exception { + assertThat(accessor.get(Sample.class.getDeclaredField("field"), new Sample("foo"))) + .isEqualTo("foo"); + } + + @Test + public void test_read_static_field() throws Exception { + Sample.staticField = "foo"; + assertThat(accessor.get(Sample.class.getDeclaredField("staticField"), null)) + .isEqualTo("foo"); + } + + @Test + public void test_write_field() throws Exception { + Sample sample = new Sample("foo"); + accessor.set(Sample.class.getDeclaredField("field"), sample, "bar"); + assertThat(sample.field).isEqualTo("bar"); + } + + @Test + public void test_write_static_field() throws Exception { + Sample.staticField = "foo"; + accessor.set(Sample.class.getDeclaredField("staticField"), null, "bar"); + assertThat(Sample.staticField).isEqualTo("bar"); + } + + @Test + public void test_invoke() throws Exception { + assertThat( + accessor.invoke( + Sample.class.getDeclaredMethod("test", String.class), + new Sample(null), + "foo")) + .isEqualTo("foo"); + } + + @Test + public void test_invoke_invocation_exception() { + assertThatThrownBy( + () -> + accessor.invoke( + Sample.class.getDeclaredMethod("test", String.class), + new Sample(null), + "exception")) + .isInstanceOf(InvocationTargetException.class); + } + + @Test + public void test_invoke_illegal_arguments() { + assertThatThrownBy( + () -> + accessor.invoke( + Sample.class.getDeclaredMethod("test", String.class), + new Sample(null), + 42)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void test_new_instance() throws Exception { + assertThat(accessor.newInstance(Sample.class.getDeclaredConstructor(String.class), "foo")) + .isInstanceOf(Sample.class); + } + + @Test + public void test_new_instance_illegal_arguments() { + assertThatThrownBy( + () -> + accessor.newInstance( + Sample.class.getDeclaredConstructor(String.class), 42)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void test_new_instance_invocation_exception() { + assertThatThrownBy( + () -> + accessor.newInstance( + Sample.class.getDeclaredConstructor(String.class), + "exception")) + .isInstanceOf(InvocationTargetException.class); + } + + @Test + public void test_new_instance_instantiation_exception() { + assertThatThrownBy( + () -> accessor.newInstance(AbstractSample.class.getDeclaredConstructor())) + .isInstanceOf(InstantiationException.class); + } + + @Test + public void test_set_final_field() throws Exception { + Sample sample = new Sample("foo"); + accessor.set(Sample.class.getDeclaredField("finalField"), sample, "foo"); + assertThat(sample.finalField).isEqualTo("foo"); + } + + private static class Sample { + + private String field; + + private final String finalField = null; + + private static String staticField = "foo"; + + public Sample(String field) { + if ("exception".equals(field)) { + throw new RuntimeException(); + } + this.field = field; + } + + private String test(String value) { + if ("exception".equals(value)) { + throw new RuntimeException(); + } + return value; + } + } + + private abstract static class AbstractSample {} +} diff --git a/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java b/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java index 342007122c..2363fe6f35 100644 --- a/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java +++ b/src/test/java/org/mockitointegration/NoByteCodeDependenciesTest.java @@ -41,6 +41,10 @@ public void pure_mockito_should_not_depend_bytecode_libraries() throws Exception pureMockitoAPIClasses.remove("org.mockito.internal.exceptions.stacktrace.StackTraceFilter"); pureMockitoAPIClasses.remove("org.mockito.internal.util.MockUtil"); + // Remove instrumentation-based member accessor which is optional. + pureMockitoAPIClasses.remove( + "org.mockito.internal.util.reflection.InstrumentationMemberAccessor"); + for (String pureMockitoAPIClass : pureMockitoAPIClasses) { checkDependency(classLoader_without_bytecode_libraries, pureMockitoAPIClass); } diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java index 765c4b8d0a..0d2af98d67 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingSetterOrPropertyTest.java @@ -12,6 +12,7 @@ import java.util.TreeSet; import org.assertj.core.api.Assertions; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; @@ -50,10 +51,19 @@ public class MockInjectionUsingSetterOrPropertyTest extends TestBase { @Spy private TreeSet searchTree = new TreeSet(); + private AutoCloseable session; + @Before public void enforces_new_instances() { - // initMocks called in TestBase Before method, so instances are not the same - MockitoAnnotations.openMocks(this); + // openMocks called in TestBase Before method, so instances are not the same + session = MockitoAnnotations.openMocks(this); + } + + @After + public void close_new_instances() throws Exception { + if (session != null) { + session.close(); + } } @Test diff --git a/src/test/java/org/mockitoutil/ClassLoaders.java b/src/test/java/org/mockitoutil/ClassLoaders.java index 2b3f51051d..308b309ec8 100644 --- a/src/test/java/org/mockitoutil/ClassLoaders.java +++ b/src/test/java/org/mockitoutil/ClassLoaders.java @@ -36,6 +36,8 @@ import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; +import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.plugins.MemberAccessor; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import org.objenesis.instantiator.ObjectInstantiator; @@ -167,9 +169,8 @@ Runnable reloadTaskInClassLoader(Runnable task) { continue; } if (declaredField.getType() == field.getType()) { // don't copy this - field.setAccessible(true); - declaredField.setAccessible(true); - declaredField.set(reloaded, field.get(task)); + MemberAccessor accessor = Plugins.getMemberAccessor(); + accessor.set(declaredField, reloaded, accessor.get(field, task)); } } diff --git a/subprojects/inline/src/main/resources/mockito-extensions/org.mockito.plugins.MemberAccessor b/subprojects/inline/src/main/resources/mockito-extensions/org.mockito.plugins.MemberAccessor new file mode 100644 index 0000000000..1422f9900b --- /dev/null +++ b/subprojects/inline/src/main/resources/mockito-extensions/org.mockito.plugins.MemberAccessor @@ -0,0 +1 @@ +member-accessor-module diff --git a/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleAccessTest.java b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleAccessTest.java new file mode 100644 index 0000000000..6382a253b8 --- /dev/null +++ b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleAccessTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.moduletest; + +import org.junit.Test; +import org.mockito.internal.util.reflection.ModuleMemberAccessor; +import org.mockito.internal.util.reflection.ReflectionMemberAccessor; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Path; +import java.util.concurrent.Callable; + +import static junit.framework.TestCase.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.moduletest.ModuleUtil.layer; +import static org.mockito.moduletest.ModuleUtil.modularJar; + +public class ModuleAccessTest { + + @Test + public void can_access_non_opened_module_with_module_member_accessor() throws Exception { + Path jar = modularJar(false, false, false); + ModuleLayer layer = layer(jar, false, true); + + ClassLoader loader = layer.findLoader("mockito.test"); + Class type = loader.loadClass("sample.MyCallable"); + + ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(loader); + try { + Class moduleMemberAccessor = loader.loadClass(ModuleMemberAccessor.class.getName()); + Object instance = moduleMemberAccessor.getConstructor().newInstance(); + @SuppressWarnings("unchecked") + Callable mock = (Callable) moduleMemberAccessor + .getMethod("newInstance", Constructor.class, Object[].class) + .invoke(instance, type.getConstructor(), new Object[0]); + assertThat(mock.call()).isEqualTo("foo"); + } finally { + Thread.currentThread().setContextClassLoader(contextLoader); + } + } + + @Test + public void cannot_access_non_opened_module_with_reflection_member_accessor() throws Exception { + Path jar = modularJar(false, false, false); + ModuleLayer layer = layer(jar, false, true); + + ClassLoader loader = layer.findLoader("mockito.test"); + Class type = loader.loadClass("sample.MyCallable"); + + ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(loader); + try { + Class moduleMemberAccessor = loader.loadClass(ReflectionMemberAccessor.class.getName()); + try { + Object instance = moduleMemberAccessor.getConstructor().newInstance(); + moduleMemberAccessor + .getMethod("newInstance", Constructor.class, Object[].class) + .invoke(instance, type.getConstructor(), new Object[0]); + fail(); + } catch (InvocationTargetException e) { + assertThat(e.getCause()).isInstanceOf(IllegalAccessException.class); + } + } finally { + Thread.currentThread().setContextClassLoader(contextLoader); + } + } +} diff --git a/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java index ed732c8089..fec5e9a841 100644 --- a/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java +++ b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java @@ -4,15 +4,7 @@ */ package org.mockito.moduletest; -import java.util.concurrent.locks.Lock; -import net.bytebuddy.ByteBuddy; -import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.dynamic.loading.ClassInjector; -import net.bytebuddy.implementation.FixedValue; -import net.bytebuddy.jar.asm.ClassWriter; -import net.bytebuddy.jar.asm.ModuleVisitor; -import net.bytebuddy.jar.asm.Opcodes; -import net.bytebuddy.utility.OpenedClassReader; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -22,33 +14,19 @@ import org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker; import org.mockito.stubbing.OngoingStubbing; -import java.io.IOException; -import java.lang.module.Configuration; -import java.lang.module.ModuleDescriptor; -import java.lang.module.ModuleFinder; -import java.lang.module.ModuleReader; -import java.lang.module.ModuleReference; import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URI; -import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; import java.util.concurrent.Callable; -import java.util.jar.JarEntry; -import java.util.jar.JarOutputStream; -import java.util.stream.Stream; +import java.util.concurrent.locks.Lock; -import static net.bytebuddy.matcher.ElementMatchers.named; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.hamcrest.core.Is.is; import static org.junit.Assume.assumeThat; +import static org.mockito.moduletest.ModuleUtil.layer; +import static org.mockito.moduletest.ModuleUtil.modularJar; @RunWith(Parameterized.class) public class ModuleHandlingTest { @@ -71,7 +49,7 @@ public void can_define_class_in_open_reading_module() throws Exception { assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false)); Path jar = modularJar(true, true, true); - ModuleLayer layer = layer(jar, true); + ModuleLayer layer = layer(jar, true, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -97,7 +75,7 @@ public void can_define_class_in_open_java_util_module() throws Exception { assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false)); Path jar = modularJar(true, true, true); - ModuleLayer layer = layer(jar, true); + ModuleLayer layer = layer(jar, true, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("java.util.concurrent.locks.Lock"); @@ -125,7 +103,7 @@ public void inline_mock_maker_can_mock_closed_modules() throws Exception { assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(true)); Path jar = modularJar(false, false, false); - ModuleLayer layer = layer(jar, false); + ModuleLayer layer = layer(jar, false, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -145,7 +123,7 @@ public void can_define_class_in_open_reading_private_module() throws Exception { assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false)); Path jar = modularJar(false, true, true); - ModuleLayer layer = layer(jar, true); + ModuleLayer layer = layer(jar, true, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -171,7 +149,7 @@ public void can_define_class_in_open_non_reading_module() throws Exception { assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false)); Path jar = modularJar(true, true, true); - ModuleLayer layer = layer(jar, false); + ModuleLayer layer = layer(jar, false, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -197,7 +175,7 @@ public void can_define_class_in_open_non_reading_non_exporting_module() throws E assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false)); Path jar = modularJar(true, false, true); - ModuleLayer layer = layer(jar, false); + ModuleLayer layer = layer(jar, false, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -223,7 +201,7 @@ public void can_define_class_in_closed_module() throws Exception { assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false)); Path jar = modularJar(true, true, false); - ModuleLayer layer = layer(jar, false); + ModuleLayer layer = layer(jar, false, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -252,7 +230,7 @@ public void cannot_define_class_in_non_opened_non_exported_module_if_lookup_inje assumeThat(!Boolean.getBoolean("org.mockito.internal.noUnsafeInjection") && ClassInjector.UsingReflection.isAvailable(), is(true)); Path jar = modularJar(false, false, false); - ModuleLayer layer = layer(jar, false); + ModuleLayer layer = layer(jar, false, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -279,7 +257,7 @@ public void can_define_class_in_non_opened_non_exported_module_if_unsafe_injecti assumeThat(!Boolean.getBoolean("org.mockito.internal.noUnsafeInjection") && ClassInjector.UsingReflection.isAvailable(), is(false)); Path jar = modularJar(false, false, false); - ModuleLayer layer = layer(jar, false); + ModuleLayer layer = layer(jar, false, namedModules); ClassLoader loader = layer.findLoader("mockito.test"); Class type = loader.loadClass("sample.MyCallable"); @@ -298,120 +276,4 @@ public void can_define_class_in_non_opened_non_exported_module_if_unsafe_injecti Thread.currentThread().setContextClassLoader(contextLoader); } } - - private static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened) throws IOException { - Path jar = Files.createTempFile("sample-module", ".jar"); - try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) { - out.putNextEntry(new JarEntry("module-info.class")); - out.write(moduleInfo(isExported, isOpened)); - out.closeEntry(); - out.putNextEntry(new JarEntry("sample/MyCallable.class")); - out.write(type(isPublic)); - out.closeEntry(); - } - return jar; - } - - private static byte[] type(boolean isPublic) { - return new ByteBuddy() - .subclass(Callable.class) - .name("sample.MyCallable") - .merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE) - .method(named("call")) - .intercept(FixedValue.value("foo")) - .make() - .getBytes(); - } - - private static byte[] moduleInfo(boolean isExported, boolean isOpened) { - ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API); - classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null); - ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null); - mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null); - mv.visitPackage("sample"); - if (isExported) { - mv.visitExport("sample", 0); - } - if (isOpened) { - mv.visitOpen("sample", 0); - } - mv.visitEnd(); - classWriter.visitEnd(); - return classWriter.toByteArray(); - } - - private ModuleLayer layer(Path jar, boolean canRead) throws MalformedURLException { - Set modules = new HashSet<>(); - modules.add("mockito.test"); - ModuleFinder moduleFinder = ModuleFinder.of(jar); - if (namedModules) { - modules.add("org.mockito"); - modules.add("net.bytebuddy"); - modules.add("net.bytebuddy.agent"); - // We do not list all packages but only roots and packages that interact with the mock where - // we attempt to validate an interaction of two modules. This is of course a bit hacky as those - // libraries would normally be entirely encapsulated in an automatic module with all their classes - // but it is sufficient for the test and saves us a significant amount of code. - moduleFinder = ModuleFinder.compose(moduleFinder, - automaticModule("org.mockito", "org.mockito", "org.mockito.internal.creation.bytebuddy"), - automaticModule("net.bytebuddy", "net.bytebuddy"), - automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent")); - } - Configuration configuration = Configuration.resolve( - moduleFinder, - Collections.singletonList(ModuleLayer.boot().configuration()), - ModuleFinder.of(), - modules - ); - ClassLoader classLoader = new ReplicatingClassLoader(jar); - ModuleLayer.Controller controller = ModuleLayer.defineModules( - configuration, - Collections.singletonList(ModuleLayer.boot()), - module -> classLoader - ); - if (canRead) { - controller.addReads( - controller.layer().findModule("mockito.test").orElseThrow(IllegalStateException::new), - Mockito.class.getModule() - ); - } - return controller.layer(); - } - - private static ModuleFinder automaticModule(String moduleName, String... packages) { - ModuleDescriptor descriptor = ModuleDescriptor.newAutomaticModule(moduleName) - .packages(new HashSet<>(Arrays.asList(packages))) - .build(); - ModuleReference reference = new ModuleReference(descriptor, null) { - @Override - public ModuleReader open() { - return new ModuleReader() { - @Override - public Optional find(String name) { - return Optional.empty(); - } - - @Override - public Stream list() { - return Stream.empty(); - } - - @Override - public void close() { - } - }; - } - }; - return new ModuleFinder() { - @Override - public Optional find(String name) { - return name.equals(moduleName) ? Optional.of(reference) : Optional.empty(); - } - - @Override - public Set findAll() { - return Collections.singleton(reference); - } - }; - } } diff --git a/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleUtil.java b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleUtil.java new file mode 100644 index 0000000000..49632fd71d --- /dev/null +++ b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleUtil.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.moduletest; + +import net.bytebuddy.ByteBuddy; +import net.bytebuddy.description.modifier.Visibility; +import net.bytebuddy.implementation.FixedValue; +import net.bytebuddy.jar.asm.ClassWriter; +import net.bytebuddy.jar.asm.ModuleVisitor; +import net.bytebuddy.jar.asm.Opcodes; +import net.bytebuddy.utility.OpenedClassReader; +import org.mockito.Mockito; + +import java.io.IOException; +import java.lang.module.*; +import java.net.MalformedURLException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.stream.Stream; + +import static net.bytebuddy.matcher.ElementMatchers.named; + +public class ModuleUtil { + + public static Path modularJar(boolean isPublic, boolean isExported, boolean isOpened) throws IOException { + Path jar = Files.createTempFile("sample-module", ".jar"); + try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) { + out.putNextEntry(new JarEntry("module-info.class")); + out.write(moduleInfo(isExported, isOpened)); + out.closeEntry(); + out.putNextEntry(new JarEntry("sample/MyCallable.class")); + out.write(type(isPublic)); + out.closeEntry(); + } + return jar; + } + + private static byte[] type(boolean isPublic) { + return new ByteBuddy() + .subclass(Callable.class) + .name("sample.MyCallable") + .merge(isPublic ? Visibility.PUBLIC : Visibility.PACKAGE_PRIVATE) + .method(named("call")) + .intercept(FixedValue.value("foo")) + .make() + .getBytes(); + } + + private static byte[] moduleInfo(boolean isExported, boolean isOpened) { + ClassWriter classWriter = new ClassWriter(OpenedClassReader.ASM_API); + classWriter.visit(Opcodes.V9, Opcodes.ACC_MODULE, "module-info", null, null, null); + ModuleVisitor mv = classWriter.visitModule("mockito.test", 0, null); + mv.visitRequire("java.base", Opcodes.ACC_MANDATED, null); + mv.visitPackage("sample"); + if (isExported) { + mv.visitExport("sample", 0); + } + if (isOpened) { + mv.visitOpen("sample", 0); + } + mv.visitEnd(); + classWriter.visitEnd(); + return classWriter.toByteArray(); + } + + public static ModuleLayer layer(Path jar, boolean canRead, boolean namedModules) throws MalformedURLException { + Set modules = new HashSet<>(); + modules.add("mockito.test"); + ModuleFinder moduleFinder = ModuleFinder.of(jar); + if (namedModules) { + modules.add("org.mockito"); + modules.add("net.bytebuddy"); + modules.add("net.bytebuddy.agent"); + // We do not list all packages but only roots and packages that interact with the mock where + // we attempt to validate an interaction of two modules. This is of course a bit hacky as those + // libraries would normally be entirely encapsulated in an automatic module with all their classes + // but it is sufficient for the test and saves us a significant amount of code. + moduleFinder = ModuleFinder.compose(moduleFinder, + automaticModule("org.mockito", "org.mockito", "org.mockito.internal.creation.bytebuddy"), + automaticModule("net.bytebuddy", "net.bytebuddy"), + automaticModule("net.bytebuddy.agent", "net.bytebuddy.agent")); + } + Configuration configuration = Configuration.resolve( + moduleFinder, + Collections.singletonList(ModuleLayer.boot().configuration()), + ModuleFinder.of(), + modules + ); + ClassLoader classLoader = new ReplicatingClassLoader(jar); + ModuleLayer.Controller controller = ModuleLayer.defineModules( + configuration, + Collections.singletonList(ModuleLayer.boot()), + module -> classLoader + ); + if (canRead) { + controller.addReads( + controller.layer().findModule("mockito.test").orElseThrow(IllegalStateException::new), + Mockito.class.getModule() + ); + } + return controller.layer(); + } + + private static ModuleFinder automaticModule(String moduleName, String... packages) { + ModuleDescriptor descriptor = ModuleDescriptor.newAutomaticModule(moduleName) + .packages(new HashSet<>(Arrays.asList(packages))) + .build(); + ModuleReference reference = new ModuleReference(descriptor, null) { + @Override + public ModuleReader open() { + return new ModuleReader() { + @Override + public Optional find(String name) { + return Optional.empty(); + } + + @Override + public Stream list() { + return Stream.empty(); + } + + @Override + public void close() { + } + }; + } + }; + return new ModuleFinder() { + @Override + public Optional find(String name) { + return name.equals(moduleName) ? Optional.of(reference) : Optional.empty(); + } + + @Override + public Set findAll() { + return Collections.singleton(reference); + } + }; + } +} diff --git a/subprojects/module-test/src/test/java/org/mockito/moduletest/ReplicatingClassLoader.java b/subprojects/module-test/src/test/java/org/mockito/moduletest/ReplicatingClassLoader.java index 9ee006c880..c9cf0a32d2 100644 --- a/subprojects/module-test/src/test/java/org/mockito/moduletest/ReplicatingClassLoader.java +++ b/subprojects/module-test/src/test/java/org/mockito/moduletest/ReplicatingClassLoader.java @@ -48,4 +48,9 @@ public Class loadClass(String name) throws ClassNotFoundException { } } } + + @Override + protected URL findResource(String moduleName, String name) { + return Mockito.class.getResource("/" + name); + } } From 47ef05814784183cd5c1d297078e2ad7e31cce34 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 13 Aug 2020 20:32:52 +0200 Subject: [PATCH 072/963] Adds support for creating spies from within a mock instance's constructor, thus avoiding reflection on final fields. --- .../bytebuddy/ByteBuddyMockMaker.java | 7 ++ .../bytebuddy/ConstructionCallback.java | 2 +- .../bytebuddy/InlineByteBuddyMockMaker.java | 39 +++++++- .../bytebuddy/InlineBytecodeGenerator.java | 6 +- .../creation/bytebuddy/MockMethodAdvice.java | 96 ++++++++++++++++++- .../inject/MockMethodDispatcher.java | 9 +- .../org/mockito/internal/util/MockUtil.java | 16 +++- .../java/org/mockito/plugins/MockMaker.java | 20 ++++ .../InlineByteBuddyMockMakerTest.java | 63 +++++++++++- 9 files changed, 236 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java index e11c866ed1..5263ea1262 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java @@ -9,6 +9,7 @@ import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; +import java.util.Optional; import java.util.function.Function; /** @@ -28,6 +29,12 @@ public T createMock(MockCreationSettings settings, MockHandler handler) { return defaultByteBuddyMockMaker.createMock(settings, handler); } + @Override + public Optional createSpy( + MockCreationSettings settings, MockHandler handler, T object) { + return defaultByteBuddyMockMaker.createSpy(settings, handler, object); + } + @Override public Class createMockType(MockCreationSettings creationSettings) { return defaultByteBuddyMockMaker.createMockType(creationSettings); diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java index 8d5abe75bd..ac8ecc4040 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ConstructionCallback.java @@ -6,5 +6,5 @@ public interface ConstructionCallback { - void accept(Class type, Object object, Object[] arguments, String[] parameterTypeNames); + Object apply(Class type, Object object, Object[] arguments, String[] parameterTypeNames); } 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 66c61d59dd..a046972dc0 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -199,6 +199,8 @@ public class InlineByteBuddyMockMaker private final ThreadLocal mockitoConstruction = ThreadLocal.withInitial(() -> false); + private final ThreadLocal currentSpied = new ThreadLocal<>(); + public InlineByteBuddyMockMaker() { if (INITIALIZATION_ERROR != null) { String detail; @@ -252,8 +254,10 @@ public InlineByteBuddyMockMaker() { }; ConstructionCallback onConstruction = (type, object, arguments, parameterTypeNames) -> { - if (mockitoConstruction.get() || currentConstruction.get() != type) { - return; + if (mockitoConstruction.get()) { + return currentSpied.get(); + } else if (currentConstruction.get() != type) { + return null; } currentConstruction.remove(); isSuspended.set(true); @@ -273,6 +277,7 @@ public InlineByteBuddyMockMaker() { } finally { isSuspended.set(false); } + return null; }; bytecodeGenerator = @@ -288,6 +293,27 @@ public InlineByteBuddyMockMaker() { @Override public T createMock(MockCreationSettings settings, MockHandler handler) { + return doCreateMock(settings, handler, false); + } + + @Override + public Optional createSpy( + MockCreationSettings settings, MockHandler handler, T object) { + if (object == null) { + throw new MockitoConfigurationException("Spy instance must not be null"); + } + currentSpied.set(object); + try { + return Optional.ofNullable(doCreateMock(settings, handler, true)); + } finally { + currentSpied.remove(); + } + } + + private T doCreateMock( + MockCreationSettings settings, + MockHandler handler, + boolean nullOnNonInlineConstruction) { Class type = createMockType(settings); try { @@ -296,6 +322,9 @@ public T createMock(MockCreationSettings settings, MockHandler handler) { // We attempt to use the "native" mock maker first that avoids Objenesis and Unsafe instance = newInstance(type); } catch (InstantiationException ignored) { + if (nullOnNonInlineConstruction) { + return null; + } Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(settings); instance = instantiator.newInstance(type); @@ -753,7 +782,8 @@ private InlineConstructionMockContext( @Override public int getCount() { if (count == 0) { - throw new MockitoConfigurationException("mocked construction context is not initialized"); + throw new MockitoConfigurationException( + "mocked construction context is not initialized"); } return count; } @@ -767,7 +797,8 @@ public Constructor constructor() { parameterTypes[index++] = PRIMITIVES.get(parameterTypeName); } else { try { - parameterTypes[index++] = Class.forName(parameterTypeName, false, type.getClassLoader()); + parameterTypes[index++] = + Class.forName(parameterTypeName, false, type.getClassLoader()); } catch (ClassNotFoundException e) { throw new MockitoException( "Could not find parameter of type " + parameterTypeName, e); 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 95776e6893..fc3c69df13 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -350,8 +350,12 @@ public byte[] transform( return byteBuddy .redefine( classBeingRedefined, + // new ClassFileLocator.Compound( ClassFileLocator.Simple.of( - classBeingRedefined.getName(), classfileBuffer)) + classBeingRedefined.getName(), classfileBuffer) + // ,ClassFileLocator.ForClassLoader.ofSystemLoader() + // ) + ) // Note: The VM erases parameter meta data from the provided class file // (bug). We just add this information manually. .visit(new ParameterWritingVisitorWrapper(classBeingRedefined)) 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 4d12ce108c..33c58a6340 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -13,6 +13,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Predicate; @@ -20,6 +21,8 @@ import net.bytebuddy.ClassFileVersion; import net.bytebuddy.asm.Advice; import net.bytebuddy.asm.AsmVisitorWrapper; +import net.bytebuddy.description.field.FieldDescription; +import net.bytebuddy.description.field.FieldList; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.MethodList; import net.bytebuddy.description.method.ParameterDescription; @@ -28,6 +31,7 @@ import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.bind.annotation.Argument; import net.bytebuddy.implementation.bind.annotation.This; +import net.bytebuddy.implementation.bytecode.StackSize; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.jar.asm.Label; import net.bytebuddy.jar.asm.MethodVisitor; @@ -166,9 +170,9 @@ public Callable handleStatic(Class type, Method origin, Object[] arguments } @Override - public void handleConstruction( + public Object handleConstruction( Class type, Object object, Object[] arguments, String[] parameterTypeNames) { - onConstruction.accept(type, object, arguments, parameterTypeNames); + return onConstruction.apply(type, object, arguments, parameterTypeNames); } @Override @@ -423,10 +427,13 @@ public void visitCode() { * * if (MockMethodDispatcher.isConstructorMock(, Current.class) { * super(); - * MockMethodDispatcher.handleConstruction(Current.class, + * Current o = (Current) MockMethodDispatcher.handleConstruction(Current.class, * this, * new Object[] {argument1, argument2, ...}, * new String[] {argumentType1, argumentType2, ...}); + * if (o != null) { + * this.field = o.field; // for each declared field + * } * return; * } * @@ -549,19 +556,72 @@ public void visitCode() { Type.getInternalName(MockMethodDispatcher.class), "handleConstruction", Type.getMethodDescriptor( - Type.VOID_TYPE, + Type.getType(Object.class), Type.getType(String.class), Type.getType(Class.class), Type.getType(Object.class), Type.getType(Object[].class), Type.getType(String[].class)), false); + FieldList fields = + instrumentedType.getDeclaredFields().filter(not(isStatic())); + super.visitTypeInsn( + Opcodes.CHECKCAST, instrumentedType.getInternalName()); + super.visitInsn(Opcodes.DUP); + Label noSpy = new Label(); + super.visitJumpInsn(Opcodes.IFNULL, noSpy); + for (FieldDescription field : fields) { + super.visitInsn(Opcodes.DUP); + super.visitFieldInsn( + Opcodes.GETFIELD, + instrumentedType.getInternalName(), + field.getInternalName(), + field.getDescriptor()); + super.visitVarInsn(Opcodes.ALOAD, 0); + super.visitInsn( + field.getType().getStackSize() == StackSize.DOUBLE + ? Opcodes.DUP_X2 + : Opcodes.DUP_X1); + super.visitInsn(Opcodes.POP); + super.visitFieldInsn( + Opcodes.PUTFIELD, + instrumentedType.getInternalName(), + field.getInternalName(), + field.getDescriptor()); + } + super.visitLabel(noSpy); + if (implementationContext + .getClassFileVersion() + .isAtLeast(ClassFileVersion.JAVA_V6)) { + Object[] locals = + toFrames( + instrumentedType.getInternalName(), + instrumentedMethod + .getParameters() + .asTypeList() + .asErasures()); + super.visitFrame( + Opcodes.F_FULL, + locals.length, + locals, + 1, + new Object[] {instrumentedType.getInternalName()}); + } + super.visitInsn(Opcodes.POP); super.visitInsn(Opcodes.RETURN); super.visitLabel(label); if (implementationContext .getClassFileVersion() .isAtLeast(ClassFileVersion.JAVA_V6)) { - super.visitFrame(Opcodes.F_SAME, 0, null, 0, null); + Object[] locals = + toFrames( + Opcodes.UNINITIALIZED_THIS, + instrumentedMethod + .getParameters() + .asTypeList() + .asErasures()); + super.visitFrame( + Opcodes.F_FULL, locals.length, locals, 0, new Object[0]); } } @@ -583,6 +643,32 @@ public void visitMaxs(int maxStack, int maxLocals) { } return methodVisitor; } + + private static Object[] toFrames(Object self, List types) { + Object[] frames = new Object[1 + types.size()]; + frames[0] = self; + int index = 0; + for (TypeDescription type : types) { + Object frame; + if (type.represents(boolean.class) + || type.represents(byte.class) + || type.represents(short.class) + || type.represents(char.class) + || type.represents(int.class)) { + frame = Opcodes.INTEGER; + } else if (type.represents(long.class)) { + frame = Opcodes.LONG; + } else if (type.represents(float.class)) { + frame = Opcodes.FLOAT; + } else if (type.represents(double.class)) { + frame = Opcodes.DOUBLE; + } else { + frame = type.getInternalName(); + } + frames[++index] = frame; + } + return frames; + } } @Retention(RetentionPolicy.RUNTIME) 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 bcd12d3c64..3be8501574 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 @@ -41,13 +41,16 @@ public static boolean isConstructorMock(String identifier, Class type) { return DISPATCHERS.get(identifier).isConstructorMock(type); } - public static void handleConstruction( + @SuppressWarnings("unused") + public static Object handleConstruction( String identifier, Class type, Object object, Object[] arguments, String[] parameterTypeNames) { - DISPATCHERS.get(identifier).handleConstruction(type, object, arguments, parameterTypeNames); + return DISPATCHERS + .get(identifier) + .handleConstruction(type, object, arguments, parameterTypeNames); } public abstract Callable handle(Object instance, Method origin, Object[] arguments) @@ -56,7 +59,7 @@ public abstract Callable handle(Object instance, Method origin, Object[] argu public abstract Callable handleStatic(Class type, Method origin, Object[] arguments) throws Throwable; - public abstract void handleConstruction( + public abstract Object handleConstruction( Class type, Object object, Object[] arguments, String[] parameterTypeNames); public abstract boolean isMock(Object instance); diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java index 352645236a..46e782cba0 100644 --- a/src/main/java/org/mockito/internal/util/MockUtil.java +++ b/src/main/java/org/mockito/internal/util/MockUtil.java @@ -35,11 +35,21 @@ public static TypeMockability typeMockabilityOf(Class type) { public static T createMock(MockCreationSettings settings) { MockHandler mockHandler = createMockHandler(settings); - T mock = mockMaker.createMock(settings, mockHandler); - Object spiedInstance = settings.getSpiedInstance(); + + T mock; if (spiedInstance != null) { - new LenientCopyTool().copyToMock(spiedInstance, mock); + mock = + mockMaker + .createSpy(settings, mockHandler, (T) spiedInstance) + .orElseGet( + () -> { + T instance = mockMaker.createMock(settings, mockHandler); + new LenientCopyTool().copyToMock(spiedInstance, instance); + return instance; + }); + } else { + mock = mockMaker.createMock(settings, mockHandler); } return mock; diff --git a/src/main/java/org/mockito/plugins/MockMaker.java b/src/main/java/org/mockito/plugins/MockMaker.java index fc1a516606..fbdaf1d0e6 100644 --- a/src/main/java/org/mockito/plugins/MockMaker.java +++ b/src/main/java/org/mockito/plugins/MockMaker.java @@ -11,6 +11,7 @@ import org.mockito.mock.MockCreationSettings; import java.util.List; +import java.util.Optional; import java.util.function.Function; import static org.mockito.internal.util.StringUtil.join; @@ -73,6 +74,25 @@ public interface MockMaker { */ T createMock(MockCreationSettings settings, MockHandler handler); + /** + * By implementing this method, a mock maker can optionally support the creation of spies where all fields + * are set within a constructor. This avoids problems when creating spies of classes that declare + * effectively final instance fields where setting field values from outside the constructor is prohibited. + * + * @param settings Mock creation settings like type to mock, extra interfaces and so on. + * @param handler See {@link org.mockito.invocation.MockHandler}. + * Do not provide your own implementation at this time. Make sure your implementation of + * {@link #getHandler(Object)} will return this instance. + * @param instance The object to spy upon. + * @param Type of the mock to return, actually the settings.getTypeToMock. + * @return + * @since 3.5.0 + */ + default Optional createSpy( + MockCreationSettings settings, MockHandler handler, T instance) { + return Optional.empty(); + } + /** * Returns the handler for the {@code mock}. Do not provide your own implementations at this time * because the work on the {@link MockHandler} api is not completed. 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 07208c8a4a..bfc16b4d15 100644 --- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java +++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java @@ -11,11 +11,7 @@ import static org.assertj.core.api.Assertions.fail; import static org.junit.Assume.assumeTrue; -import java.util.HashMap; -import java.util.List; -import java.util.Observable; -import java.util.Observer; -import java.util.Set; +import java.util.*; import java.util.concurrent.Callable; import java.util.regex.Pattern; @@ -57,6 +53,29 @@ public void should_create_mock_from_final_class() throws Exception { assertThat(proxy.foo()).isEqualTo("bar"); } + @Test + public void should_create_mock_from_final_spy() throws Exception { + MockCreationSettings settings = settingsFor(FinalSpy.class); + Optional proxy = + mockMaker.createSpy( + settings, + new MockHandlerImpl<>(settings), + new FinalSpy("value", true, (byte) 1, (short) 1, (char) 1, 1, 1L, 1f, 1d)); + assertThat(proxy) + .hasValueSatisfying( + spy -> { + assertThat(spy.aString).isEqualTo("value"); + assertThat(spy.aBoolean).isTrue(); + assertThat(spy.aByte).isEqualTo((byte) 1); + assertThat(spy.aShort).isEqualTo((short) 1); + assertThat(spy.aChar).isEqualTo((char) 1); + assertThat(spy.anInt).isEqualTo(1); + assertThat(spy.aLong).isEqualTo(1L); + assertThat(spy.aFloat).isEqualTo(1f); + assertThat(spy.aDouble).isEqualTo(1d); + }); + } + @Test public void should_create_mock_from_non_constructable_class() throws Exception { MockCreationSettings settings = @@ -416,6 +435,40 @@ public String foo() { } } + private static final class FinalSpy { + + private final String aString; + private final boolean aBoolean; + private final byte aByte; + private final short aShort; + private final char aChar; + private final int anInt; + private final long aLong; + private final float aFloat; + private final double aDouble; + + private FinalSpy( + String aString, + boolean aBoolean, + byte aByte, + short aShort, + char aChar, + int anInt, + long aLong, + float aFloat, + double aDouble) { + this.aString = aString; + this.aBoolean = aBoolean; + this.aByte = aByte; + this.aShort = aShort; + this.aChar = aChar; + this.anInt = anInt; + this.aLong = aLong; + this.aFloat = aFloat; + this.aDouble = aDouble; + } + } + private static class NonConstructableClass { private NonConstructableClass() { From 5b4e61290dbd730eadf09b849784abcbb8f57f5a Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Fri, 14 Aug 2020 23:31:40 +0200 Subject: [PATCH 073/963] Merging constructor mocks with safe accessibility whilst fixing use of reflection where new deprecations are better considered. --- .../internal/configuration/ClassPathLoader.java | 2 +- .../plugins/DefaultMockitoPlugins.java | 2 +- .../configuration/plugins/PluginInitializer.java | 2 +- .../bytebuddy/InlineByteBuddyMockMaker.java | 8 +++----- .../creation/bytebuddy/MockMethodAdvice.java | 1 - .../bytebuddy/AbstractByteBuddyMockMakerTest.java | 2 +- .../util/reflection/LenientCopyToolTest.java | 15 --------------- .../spies/SpyingOnInterfacesTest.java | 2 +- 8 files changed, 8 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java b/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java index 8fc47b425f..0f031ee58a 100644 --- a/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java +++ b/src/main/java/org/mockito/internal/configuration/ClassPathLoader.java @@ -64,7 +64,7 @@ public IMockitoConfiguration loadConfiguration() { } try { - return (IMockitoConfiguration) configClass.newInstance(); + return (IMockitoConfiguration) configClass.getDeclaredConstructor().newInstance(); } catch (ClassCastException e) { throw new MockitoConfigurationException( "MockitoConfiguration class must implement " 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 f3192cba5a..38b882a322 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java @@ -79,7 +79,7 @@ private T create(Class pluginType, String className) { // Default implementation. Use our own ClassLoader instead of the context // ClassLoader, as the default implementation is assumed to be part of // Mockito and may not be available via the context ClassLoader. - return pluginType.cast(Class.forName(className).newInstance()); + return pluginType.cast(Class.forName(className).getDeclaredConstructor().newInstance()); } catch (Exception e) { throw new IllegalStateException( "Internal problem occurred, please report it. " 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 d58ca2cdf3..8f8f76edcb 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java @@ -47,7 +47,7 @@ public T loadImpl(Class service) { classOrAlias = plugins.getDefaultPluginClass(alias); } Class pluginClass = loader.loadClass(classOrAlias); - Object plugin = pluginClass.newInstance(); + Object plugin = pluginClass.getDeclaredConstructor().newInstance(); return service.cast(plugin); } return null; 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 a046972dc0..0a20882b2c 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -35,6 +35,7 @@ import org.mockito.invocation.MockHandler; import org.mockito.mock.MockCreationSettings; import org.mockito.plugins.InlineMockMaker; +import org.mockito.plugins.MemberAccessor; import static org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.*; import static org.mockito.internal.util.StringUtil.*; @@ -569,14 +570,11 @@ public T newInstance(Class cls) throws InstantiationException { for (Class type : types) { arguments[index++] = makeStandardArgument(type); } + MemberAccessor accessor = Plugins.getMemberAccessor(); try { - if (!Modifier.isPublic(selected.getModifiers()) - || !Modifier.isPublic(cls.getModifiers())) { - selected.setAccessible(true); - } mockitoConstruction.set(true); try { - return (T) selected.newInstance(arguments); + return (T) accessor.newInstance(selected, arguments); } finally { mockitoConstruction.set(false); } 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 3b1490775b..69a7ed21a6 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -12,7 +12,6 @@ import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.lang.reflect.Modifier; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; 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 f5b807a1ce..3ddc1817ba 100644 --- a/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java +++ b/src/test/java/org/mockito/internal/creation/bytebuddy/AbstractByteBuddyMockMakerTest.java @@ -165,7 +165,7 @@ public void instantiate_fine_when_objenesis_on_the_classpath() throws Exception classpath_with_objenesis); // when - mock_maker_class_loaded_fine_until.newInstance(); + mock_maker_class_loaded_fine_until.getConstructor().newInstance(); // then everything went fine } 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 b8c742aff7..e70d8aa3c4 100644 --- a/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/LenientCopyToolTest.java @@ -6,7 +6,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.*; import java.lang.reflect.Field; @@ -128,20 +127,6 @@ public void shouldCopyValuesOfInheritedFields() throws Exception { assertEquals(((InheritMe) from).privateInherited, ((InheritMe) to).privateInherited); } - @Test - public void shouldEnableAndThenDisableAccessibility() throws Exception { - // given - Field privateField = SomeObject.class.getDeclaredField("privateField"); - assertFalse(privateField.isAccessible()); - - // when - tool.copyToMock(from, to); - - // then - privateField = SomeObject.class.getDeclaredField("privateField"); - assertFalse(privateField.isAccessible()); - } - @Test public void shouldContinueEvenIfThereAreProblemsCopyingSingleFieldValue() throws Exception { // given diff --git a/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java b/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java index ec8d5933d2..b6fe514cde 100644 --- a/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java +++ b/src/test/java/org/mockitousage/spies/SpyingOnInterfacesTest.java @@ -106,7 +106,7 @@ public void shouldAllowSpyingOnDefaultMethod() throws Exception { .load(iFace.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); - Object object = spy(impl.newInstance()); + Object object = spy(impl.getConstructor().newInstance()); // when Assertions.assertThat(impl.getMethod("foo").invoke(object)).isEqualTo((Object) "bar"); From 70633c4876572343a57b5f718fae8967dae27108 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sat, 15 Aug 2020 23:19:17 +0000 Subject: [PATCH 074/963] 3.5.0 release (previous 3.4.8) + release notes updated by CI build 4710 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index e5ca6a4ee9..d7f2225d95 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.0 + - 2020-08-15 - [9 commits](https://github.com/mockito/mockito/compare/v3.4.8...v3.5.0) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.0) + - Pre release 3.5.0 [(#2004)](https://github.com/mockito/mockito/pull/2004) + #### 3.4.8 - 2020-08-09 - [1 commit](https://github.com/mockito/mockito/compare/v3.4.7...v3.4.8) by [Erhard Pointl](https://github.com/epeee) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.4.8-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.4.8) - Update objenesis to 3.1 [(#1998)](https://github.com/mockito/mockito/pull/1998) diff --git a/version.properties b/version.properties index 061b231748..6c51db087f 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.5.0 +version=3.5.1 #Previous version used to generate release notes delta -previousVersion=3.4.8 +previousVersion=3.5.0 From d42221ccd9e77cb71cd8d7fab947b3559412aac2 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 17 Aug 2020 20:29:16 +0200 Subject: [PATCH 075/963] Add signature checks to assure Android and Java 8 compatibility. Exclude classes which must not be run on Android. --- build.gradle | 9 ++++++ .../mockito/internal/MockedStaticImpl.java | 2 +- .../internal/SuppressSignatureCheck.java | 11 ++++++++ .../bytebuddy/InlineByteBuddyMockMaker.java | 28 ++++++++++--------- .../bytebuddy/InlineBytecodeGenerator.java | 2 ++ .../InstrumentationMemberAccessor.java | 2 ++ 6 files changed, 40 insertions(+), 14 deletions(-) create mode 100644 src/main/java/org/mockito/internal/SuppressSignatureCheck.java diff --git a/build.gradle b/build.gradle index 160cf24a6e..217f71d4b2 100644 --- a/build.gradle +++ b/build.gradle @@ -21,6 +21,7 @@ plugins { id 'eclipse' id 'com.github.ben-manes.versions' version '0.28.0' id 'biz.aQute.bnd.builder' version '5.1.0' + id 'ru.vyarus.animalsniffer' version '1.5.1' } description = 'Mockito mock objects library core API and implementation' @@ -98,6 +99,14 @@ dependencies { testRuntime configurations.compileOnly testUtil sourceSets.test.output + + signature 'org.codehaus.mojo.signature:java18:1.0@signature' + signature 'net.sf.androidscents.signature:android-api-level-24:7.0_r2@signature' +} + +animalsniffer { + sourceSets = [sourceSets.main] + annotation = 'org.mockito.internal.SuppressSignatureCheck' } wrapper { diff --git a/src/main/java/org/mockito/internal/MockedStaticImpl.java b/src/main/java/org/mockito/internal/MockedStaticImpl.java index cb7794cc03..7c3af584eb 100644 --- a/src/main/java/org/mockito/internal/MockedStaticImpl.java +++ b/src/main/java/org/mockito/internal/MockedStaticImpl.java @@ -172,6 +172,6 @@ private void assertNotClosed() { @Override public String toString() { - return "static mock for " + control.getType().getTypeName(); + return "static mock for " + control.getType().getName(); } } diff --git a/src/main/java/org/mockito/internal/SuppressSignatureCheck.java b/src/main/java/org/mockito/internal/SuppressSignatureCheck.java new file mode 100644 index 0000000000..c27483ebf7 --- /dev/null +++ b/src/main/java/org/mockito/internal/SuppressSignatureCheck.java @@ -0,0 +1,11 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.internal; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.CLASS) +@Documented +public @interface SuppressSignatureCheck { } 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 0a20882b2c..2d75418e6b 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -28,6 +28,7 @@ import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.base.MockitoInitializationException; import org.mockito.exceptions.misusing.MockitoConfigurationException; +import org.mockito.internal.SuppressSignatureCheck; import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.util.Platform; import org.mockito.internal.util.concurrent.DetachedThreadLocal; @@ -99,6 +100,7 @@ * support this feature. */ @Incubating +@SuppressSignatureCheck public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineMockMaker, Instantiator { @@ -506,7 +508,7 @@ public StaticMockControl createStaticMock( || ClassLoader.class.isAssignableFrom(type)) { throw new MockitoException( "It is not possible to mock static methods of " - + type.getTypeName() + + type.getName() + " to avoid interfering with class loading what leads to infinite loops"); } @@ -534,7 +536,7 @@ public ConstructionMockControl createConstructionMock( } else if (type.isPrimitive() || Modifier.isAbstract(type.getModifiers())) { throw new MockitoException( "It is not possible to construct primitive types or abstract types: " - + type.getTypeName()); + + type.getName()); } bytecodeGenerator.mockClassConstruction(type); @@ -555,7 +557,7 @@ public ConstructionMockControl createConstructionMock( public T newInstance(Class cls) throws InstantiationException { Constructor[] constructors = cls.getDeclaredConstructors(); if (constructors.length == 0) { - throw new InstantiationException(cls.getTypeName() + " does not define a constructor"); + throw new InstantiationException(cls.getName() + " does not define a constructor"); } Constructor selected = constructors[0]; for (Constructor constructor : constructors) { @@ -579,7 +581,7 @@ public T newInstance(Class cls) throws InstantiationException { mockitoConstruction.set(false); } } catch (Exception e) { - throw new InstantiationException("Could not instantiate " + cls.getTypeName(), e); + throw new InstantiationException("Could not instantiate " + cls.getName(), e); } } @@ -754,14 +756,14 @@ private static class InlineConstructionMockContext implements MockedConstruction private static final Map> PRIMITIVES = new HashMap<>(); static { - PRIMITIVES.put(boolean.class.getTypeName(), boolean.class); - PRIMITIVES.put(byte.class.getTypeName(), byte.class); - PRIMITIVES.put(short.class.getTypeName(), short.class); - PRIMITIVES.put(char.class.getTypeName(), char.class); - PRIMITIVES.put(int.class.getTypeName(), int.class); - PRIMITIVES.put(long.class.getTypeName(), long.class); - PRIMITIVES.put(float.class.getTypeName(), float.class); - PRIMITIVES.put(double.class.getTypeName(), double.class); + PRIMITIVES.put(boolean.class.getName(), boolean.class); + PRIMITIVES.put(byte.class.getName(), byte.class); + PRIMITIVES.put(short.class.getName(), short.class); + PRIMITIVES.put(char.class.getName(), char.class); + PRIMITIVES.put(int.class.getName(), int.class); + PRIMITIVES.put(long.class.getName(), long.class); + PRIMITIVES.put(float.class.getName(), float.class); + PRIMITIVES.put(double.class.getName(), double.class); } private int count; @@ -810,7 +812,7 @@ public Constructor constructor() { join( "Could not resolve constructor of type", "", - type.getTypeName(), + type.getName(), "", "with arguments of types", Arrays.toString(parameterTypes)), 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 fc3c69df13..409f58201c 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -37,6 +37,7 @@ import net.bytebuddy.utility.OpenedClassReader; import net.bytebuddy.utility.RandomString; import org.mockito.exceptions.base.MockitoException; +import org.mockito.internal.SuppressSignatureCheck; import org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher; import org.mockito.internal.util.concurrent.DetachedThreadLocal; import org.mockito.internal.util.concurrent.WeakConcurrentMap; @@ -48,6 +49,7 @@ import static net.bytebuddy.matcher.ElementMatchers.*; import static org.mockito.internal.util.StringUtil.*; +@SuppressSignatureCheck public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTransformer { private static final String PRELOAD = "org.mockito.inline.preload"; diff --git a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java index c74c79efa6..bbe8c18f6c 100644 --- a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java +++ b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java @@ -9,6 +9,7 @@ import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.implementation.MethodCall; import org.mockito.exceptions.base.MockitoInitializationException; +import org.mockito.internal.SuppressSignatureCheck; import org.mockito.plugins.MemberAccessor; import java.lang.instrument.Instrumentation; @@ -21,6 +22,7 @@ import static net.bytebuddy.matcher.ElementMatchers.named; import static org.mockito.internal.util.StringUtil.join; +@SuppressSignatureCheck class InstrumentationMemberAccessor implements MemberAccessor { private static final Map, Class> WRAPPERS = new HashMap<>(); From ec659f4ded5809aa0af890d588c4dea21a813138 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 17 Aug 2020 20:49:06 +0200 Subject: [PATCH 076/963] Do not use invoke/invokeExact directly but from generated code to avoid breaking Android builds which cannot process these methods. --- .../internal/SuppressSignatureCheck.java | 2 +- .../InstrumentationMemberAccessor.java | 77 ++++++++++++------- 2 files changed, 52 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/mockito/internal/SuppressSignatureCheck.java b/src/main/java/org/mockito/internal/SuppressSignatureCheck.java index c27483ebf7..ced5635e0b 100644 --- a/src/main/java/org/mockito/internal/SuppressSignatureCheck.java +++ b/src/main/java/org/mockito/internal/SuppressSignatureCheck.java @@ -8,4 +8,4 @@ @Retention(RetentionPolicy.CLASS) @Documented -public @interface SuppressSignatureCheck { } +public @interface SuppressSignatureCheck {} diff --git a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java index bbe8c18f6c..6be9db8d27 100644 --- a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java +++ b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java @@ -69,6 +69,13 @@ class InstrumentationMemberAccessor implements MemberAccessor { "setAccessible", boolean.class)) .onArgument(0) .withArgument(1)) + .method(named("invokeWithArguments")) + .intercept( + MethodCall.invoke( + MethodHandle.class.getMethod( + "invokeWithArguments", Object[].class)) + .onArgument(0) + .withArgument(1)) .make() .load( InstrumentationMemberAccessor.class.getClassLoader(), @@ -146,17 +153,20 @@ public Object newInstance(Constructor constructor, Object... arguments) } assureArguments(constructor, null, null, arguments, constructor.getParameterTypes()); try { - Object module = getModule.bindTo(constructor.getDeclaringClass()).invokeWithArguments(); + Object module = + DISPATCHER.invokeWithArguments( + getModule.bindTo(constructor.getDeclaringClass())); String packageName = constructor.getDeclaringClass().getPackage().getName(); assureOpen(module, packageName); MethodHandle handle = ((MethodHandles.Lookup) - privateLookupIn.invokeExact( + DISPATCHER.invokeWithArguments( + privateLookupIn, constructor.getDeclaringClass(), DISPATCHER.getLookup())) .unreflectConstructor(constructor); try { - return handle.invokeWithArguments(arguments); + return DISPATCHER.invokeWithArguments(handle, arguments); } catch (Throwable t) { throw new InvocationTargetException(t); } @@ -182,19 +192,22 @@ public Object invoke(Method method, Object target, Object... arguments) arguments, method.getParameterTypes()); try { - Object module = getModule.bindTo(method.getDeclaringClass()).invokeWithArguments(); + Object module = + DISPATCHER.invokeWithArguments(getModule.bindTo(method.getDeclaringClass())); String packageName = method.getDeclaringClass().getPackage().getName(); assureOpen(module, packageName); MethodHandle handle = ((MethodHandles.Lookup) - privateLookupIn.invokeExact( - method.getDeclaringClass(), DISPATCHER.getLookup())) + DISPATCHER.invokeWithArguments( + privateLookupIn, + method.getDeclaringClass(), + DISPATCHER.getLookup())) .unreflect(method); if (!Modifier.isStatic(method.getModifiers())) { handle = handle.bindTo(target); } try { - return handle.invokeWithArguments(arguments); + return DISPATCHER.invokeWithArguments(handle, arguments); } catch (Throwable t) { throw new InvocationTargetException(t); } @@ -221,18 +234,21 @@ public Object get(Field field, Object target) { new Object[0], new Class[0]); try { - Object module = getModule.bindTo(field.getDeclaringClass()).invokeWithArguments(); + Object module = + DISPATCHER.invokeWithArguments(getModule.bindTo(field.getDeclaringClass())); String packageName = field.getDeclaringClass().getPackage().getName(); assureOpen(module, packageName); MethodHandle handle = ((MethodHandles.Lookup) - privateLookupIn.invokeExact( - field.getDeclaringClass(), DISPATCHER.getLookup())) + DISPATCHER.invokeWithArguments( + privateLookupIn, + field.getDeclaringClass(), + DISPATCHER.getLookup())) .unreflectGetter(field); if (!Modifier.isStatic(field.getModifiers())) { handle = handle.bindTo(target); } - return handle.invokeWithArguments(); + return DISPATCHER.invokeWithArguments(handle); } catch (Throwable t) { throw new IllegalStateException("Could not read " + field + " on " + target, t); } @@ -248,7 +264,8 @@ public void set(Field field, Object target, Object value) throws IllegalAccessEx new Class[] {field.getType()}); boolean illegalAccess = false; try { - Object module = getModule.bindTo(field.getDeclaringClass()).invokeWithArguments(); + Object module = + DISPATCHER.invokeWithArguments(getModule.bindTo(field.getDeclaringClass())); String packageName = field.getDeclaringClass().getPackage().getName(); assureOpen(module, packageName); // Method handles do not allow setting final fields where setAccessible(true) @@ -270,13 +287,15 @@ public void set(Field field, Object target, Object value) throws IllegalAccessEx try { MethodHandle handle = ((MethodHandles.Lookup) - privateLookupIn.invokeExact( - field.getDeclaringClass(), DISPATCHER.getLookup())) + DISPATCHER.invokeWithArguments( + privateLookupIn, + field.getDeclaringClass(), + DISPATCHER.getLookup())) .unreflectSetter(field); if (!Modifier.isStatic(field.getModifiers())) { handle = handle.bindTo(target); } - handle.invokeWithArguments(value); + DISPATCHER.invokeWithArguments(handle, value); } finally { if (isFinal) { DISPATCHER.setAccessible(field, false); @@ -292,17 +311,18 @@ public void set(Field field, Object target, Object value) throws IllegalAccessEx } private void assureOpen(Object module, String packageName) throws Throwable { - if (!(Boolean) isOpen.invokeWithArguments(module, packageName, DISPATCHER.getModule())) { - redefineModule - .bindTo(INSTRUMENTATION) - .invokeWithArguments( - module, - Collections.emptySet(), - Collections.emptyMap(), - Collections.singletonMap( - packageName, Collections.singleton(DISPATCHER.getModule())), - Collections.emptySet(), - Collections.emptyMap()); + if (!(Boolean) + DISPATCHER.invokeWithArguments( + isOpen, module, packageName, DISPATCHER.getModule())) { + DISPATCHER.invokeWithArguments( + redefineModule.bindTo(INSTRUMENTATION), + module, + Collections.emptySet(), + Collections.emptyMap(), + Collections.singletonMap( + packageName, Collections.singleton(DISPATCHER.getModule())), + Collections.emptySet(), + Collections.emptyMap()); } } @@ -361,5 +381,10 @@ public interface Dispatcher { Object getModule(); void setAccessible(AccessibleObject target, boolean value); + + // Used to avoid invoke/invokeExact being exposed to Android where this class should + // never be loaded. Since the invocation happens from the generated code, the Android + // build pipeline does not fail. + Object invokeWithArguments(MethodHandle handle, Object... arguments) throws Throwable; } } From 2dd7ea1eca9861a881909df159f0aa376fd62e40 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Tue, 18 Aug 2020 13:20:49 +0000 Subject: [PATCH 077/963] 3.5.1 release (previous 3.5.0) + release notes updated by CI build 4715 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index d7f2225d95..8dbdbadd1a 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.1 + - 2020-08-18 - [3 commits](https://github.com/mockito/mockito/compare/v3.5.0...v3.5.1) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.1-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.1) + - Introduce animal sniffer [(#2006)](https://github.com/mockito/mockito/pull/2006) + #### 3.5.0 - 2020-08-15 - [9 commits](https://github.com/mockito/mockito/compare/v3.4.8...v3.5.0) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.0) - Pre release 3.5.0 [(#2004)](https://github.com/mockito/mockito/pull/2004) diff --git a/version.properties b/version.properties index 6c51db087f..7f015553f7 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ #Currently building Mockito version -version=3.5.1 +version=3.5.2 #Previous version used to generate release notes delta -previousVersion=3.5.0 +previousVersion=3.5.1 From dd5f2c1f2fbf177c14fb90f97247abcaec7719b3 Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Tue, 18 Aug 2020 21:55:44 +0100 Subject: [PATCH 078/963] Publish to Maven Central [ci maven-central-release] --- version.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.properties b/version.properties index 7f015553f7..00b4ab2e38 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ -#Currently building Mockito version +# Currently building Mockito version version=3.5.2 -#Previous version used to generate release notes delta +# Previous version used to generate release notes delta previousVersion=3.5.1 From 31bdc245a39fc22c4bb67bf4cf0bc0c3c5292238 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Tue, 18 Aug 2020 21:01:54 +0000 Subject: [PATCH 079/963] 3.5.2 release (previous 3.5.1) + release notes updated by CI build 4717 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 8dbdbadd1a..07eb52de95 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.2 + - 2020-08-18 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.1...v3.5.2) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.2-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.2) + - No pull requests referenced in commit messages. + #### 3.5.1 - 2020-08-18 - [3 commits](https://github.com/mockito/mockito/compare/v3.5.0...v3.5.1) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.1-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.1) - Introduce animal sniffer [(#2006)](https://github.com/mockito/mockito/pull/2006) diff --git a/version.properties b/version.properties index 00b4ab2e38..c614979e79 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.2 +version=3.5.3 # Previous version used to generate release notes delta -previousVersion=3.5.1 +previousVersion=3.5.2 From 7ee851854fb4cf76e8062d7af250840f8716f211 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 20 Aug 2020 22:41:48 +0200 Subject: [PATCH 080/963] Fixes #2012: Uses constructor for mock instantiation if explicitly configured. --- .../bytebuddy/InlineByteBuddyMockMaker.java | 28 +++++++++---- .../mockitoinline/SpyWithConstructorTest.java | 41 +++++++++++++++++++ 2 files changed, 60 insertions(+), 9 deletions(-) create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/SpyWithConstructorTest.java 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 2d75418e6b..d836d07a7c 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -30,6 +30,7 @@ import org.mockito.exceptions.misusing.MockitoConfigurationException; import org.mockito.internal.SuppressSignatureCheck; import org.mockito.internal.configuration.plugins.Plugins; +import org.mockito.internal.creation.instance.ConstructorInstantiator; import org.mockito.internal.util.Platform; import org.mockito.internal.util.concurrent.DetachedThreadLocal; import org.mockito.internal.util.concurrent.WeakConcurrentMap; @@ -321,16 +322,25 @@ private T doCreateMock( try { T instance; - try { - // We attempt to use the "native" mock maker first that avoids Objenesis and Unsafe - instance = newInstance(type); - } catch (InstantiationException ignored) { - if (nullOnNonInlineConstruction) { - return null; + if (settings.isUsingConstructor()) { + instance = + new ConstructorInstantiator( + settings.getOuterClassInstance() != null, + settings.getConstructorArgs()) + .newInstance(type); + } else { + try { + // We attempt to use the "native" mock maker first that avoids + // Objenesis and Unsafe + instance = newInstance(type); + } catch (InstantiationException ignored) { + if (nullOnNonInlineConstruction) { + return null; + } + Instantiator instantiator = + Plugins.getInstantiatorProvider().getInstantiator(settings); + instance = instantiator.newInstance(type); } - Instantiator instantiator = - Plugins.getInstantiatorProvider().getInstantiator(settings); - instance = instantiator.newInstance(type); } MockMethodInterceptor mockMethodInterceptor = new MockMethodInterceptor(handler, settings); diff --git a/subprojects/inline/src/test/java/org/mockitoinline/SpyWithConstructorTest.java b/subprojects/inline/src/test/java/org/mockitoinline/SpyWithConstructorTest.java new file mode 100644 index 0000000000..fcaa581123 --- /dev/null +++ b/subprojects/inline/src/test/java/org/mockitoinline/SpyWithConstructorTest.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitoinline; + +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.*; + +public class SpyWithConstructorTest { + + private SomethingAbstract somethingAbstract; + + @Before + public void setUp() { + somethingAbstract = mock(SomethingAbstract.class, withSettings() + .useConstructor("foo") + .defaultAnswer(CALLS_REAL_METHODS)); + } + + @Test + public void shouldUseConstructor() { + assertEquals("foo", somethingAbstract.getValue()); + } + + static abstract class SomethingAbstract { + + private final String value; + + SomethingAbstract(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } +} From 7e942c40bfad5335bb6a7219c31b4e44580f96be Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 20 Aug 2020 22:46:26 +0200 Subject: [PATCH 081/963] Attempts to fix stack overflow error. --- .../internal/creation/bytebuddy/InlineByteBuddyMockMaker.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 d836d07a7c..31a6dc9f09 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -259,7 +259,9 @@ public InlineByteBuddyMockMaker() { ConstructionCallback onConstruction = (type, object, arguments, parameterTypeNames) -> { if (mockitoConstruction.get()) { - return currentSpied.get(); + Object spy = currentSpied.get(); + // Avoid that exceptions during spy creation cause class cast exceptions. + return type.isInstance(spy) ? spy : null; } else if (currentConstruction.get() != type) { return null; } From 5cb5a665840a84fa90a6f9aee9a4f4b982007cb3 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 20 Aug 2020 21:39:13 +0000 Subject: [PATCH 082/963] 3.5.3 release (previous 3.5.2) + release notes updated by CI build 4723 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 07eb52de95..678418e45e 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.3 + - 2020-08-20 - [3 commits](https://github.com/mockito/mockito/compare/v3.5.2...v3.5.3) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.3-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.3) + - [ci maven-central-release] Constructor dispatch [(#2013)](https://github.com/mockito/mockito/pull/2013) + - Constructor not called when using mockito-inline (3.5.x) [(#2012)](https://github.com/mockito/mockito/issues/2012) + #### 3.5.2 - 2020-08-18 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.1...v3.5.2) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.2-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.2) - No pull requests referenced in commit messages. diff --git a/version.properties b/version.properties index c614979e79..10bee63027 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.3 +version=3.5.4 # Previous version used to generate release notes delta -previousVersion=3.5.2 +previousVersion=3.5.3 From 3d1405f1c431888b2641a003868ba5b9300aa611 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Fri, 21 Aug 2020 10:44:16 +0200 Subject: [PATCH 083/963] Only enable mocking of types right before instantiation to avoid circular interception of constructor creation. --- .../bytebuddy/InlineByteBuddyMockMaker.java | 32 ++++++++++++++----- .../InstrumentationMemberAccessor.java | 27 +++++++++++++--- .../util/reflection/ModuleMemberAccessor.java | 7 ++++ .../reflection/ReflectionMemberAccessor.java | 9 +++++- .../org/mockito/plugins/MemberAccessor.java | 18 +++++++++++ 5 files changed, 80 insertions(+), 13 deletions(-) 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 31a6dc9f09..1287219340 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -260,8 +260,18 @@ public InlineByteBuddyMockMaker() { (type, object, arguments, parameterTypeNames) -> { if (mockitoConstruction.get()) { Object spy = currentSpied.get(); - // Avoid that exceptions during spy creation cause class cast exceptions. - return type.isInstance(spy) ? spy : null; + if (spy == null) { + return null; + } else if (type.isInstance(spy)) { + return spy; + } else { + // Unexpected construction of non-spied object + throw new MockitoException( + "Unexpected spy for " + + type.getName() + + " on instance of " + + object.getClass().getName()); + } } else if (currentConstruction.get() != type) { return null; } @@ -586,12 +596,18 @@ public T newInstance(Class cls) throws InstantiationException { } MemberAccessor accessor = Plugins.getMemberAccessor(); try { - mockitoConstruction.set(true); - try { - return (T) accessor.newInstance(selected, arguments); - } finally { - mockitoConstruction.set(false); - } + return (T) + accessor.newInstance( + selected, + callback -> { + mockitoConstruction.set(true); + try { + return callback.newInstance(); + } finally { + mockitoConstruction.set(false); + } + }, + arguments); } catch (Exception e) { throw new InstantiationException("Could not instantiate " + cls.getName(), e); } diff --git a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java index 6be9db8d27..a8e1c26467 100644 --- a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java +++ b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java @@ -18,6 +18,7 @@ import java.lang.invoke.MethodType; import java.lang.reflect.*; import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; import static net.bytebuddy.matcher.ElementMatchers.named; import static org.mockito.internal.util.StringUtil.join; @@ -147,6 +148,13 @@ class InstrumentationMemberAccessor implements MemberAccessor { @Override public Object newInstance(Constructor constructor, Object... arguments) throws InstantiationException, InvocationTargetException { + return newInstance(constructor, ConstructionDispatcher::newInstance, arguments); + } + + @Override + public Object newInstance( + Constructor constructor, OnConstruction onConstruction, Object... arguments) + throws InstantiationException, InvocationTargetException { if (Modifier.isAbstract(constructor.getDeclaringClass().getModifiers())) { throw new InstantiationException( "Cannot instantiate abstract " + constructor.getDeclaringClass().getTypeName()); @@ -165,10 +173,21 @@ public Object newInstance(Constructor constructor, Object... arguments) constructor.getDeclaringClass(), DISPATCHER.getLookup())) .unreflectConstructor(constructor); - try { - return DISPATCHER.invokeWithArguments(handle, arguments); - } catch (Throwable t) { - throw new InvocationTargetException(t); + AtomicBoolean thrown = new AtomicBoolean(); + Object value = + onConstruction.invoke( + () -> { + try { + return DISPATCHER.invokeWithArguments(handle, arguments); + } catch (Throwable throwable) { + thrown.set(true); + return throwable; + } + }); + if (thrown.get()) { + throw new InvocationTargetException((Throwable) value); + } else { + return value; } } catch (InvocationTargetException e) { throw e; diff --git a/src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java index 8be77860ad..1eb25c6b06 100644 --- a/src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java +++ b/src/main/java/org/mockito/internal/util/reflection/ModuleMemberAccessor.java @@ -30,6 +30,13 @@ public Object newInstance(Constructor constructor, Object... arguments) return delegate.newInstance(constructor, arguments); } + @Override + public Object newInstance( + Constructor constructor, OnConstruction onConstruction, Object... arguments) + throws InstantiationException, InvocationTargetException, IllegalAccessException { + return delegate.newInstance(constructor, onConstruction, arguments); + } + @Override public Object invoke(Method method, Object target, Object... arguments) throws InvocationTargetException, IllegalAccessException { diff --git a/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java index e61a5bcc02..d96e9693b9 100644 --- a/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java +++ b/src/main/java/org/mockito/internal/util/reflection/ReflectionMemberAccessor.java @@ -14,9 +14,16 @@ public class ReflectionMemberAccessor implements MemberAccessor { @Override public Object newInstance(Constructor constructor, Object... arguments) throws InstantiationException, InvocationTargetException, IllegalAccessException { + return newInstance(constructor, ConstructionDispatcher::newInstance, arguments); + } + + @Override + public Object newInstance( + Constructor constructor, OnConstruction onConstruction, Object... arguments) + throws InstantiationException, InvocationTargetException, IllegalAccessException { silentSetAccessible(constructor, true); try { - return constructor.newInstance(arguments); + return onConstruction.invoke(() -> constructor.newInstance(arguments)); } catch (InvocationTargetException | IllegalAccessException | InstantiationException diff --git a/src/main/java/org/mockito/plugins/MemberAccessor.java b/src/main/java/org/mockito/plugins/MemberAccessor.java index 081814e1db..caccb656da 100644 --- a/src/main/java/org/mockito/plugins/MemberAccessor.java +++ b/src/main/java/org/mockito/plugins/MemberAccessor.java @@ -21,10 +21,28 @@ public interface MemberAccessor { Object newInstance(Constructor constructor, Object... arguments) throws InstantiationException, InvocationTargetException, IllegalAccessException; + default Object newInstance( + Constructor constructor, OnConstruction onConstruction, Object... arguments) + throws InstantiationException, InvocationTargetException, IllegalAccessException { + return onConstruction.invoke(() -> newInstance(constructor, arguments)); + } + Object invoke(Method method, Object target, Object... arguments) throws InvocationTargetException, IllegalAccessException; Object get(Field field, Object target) throws IllegalAccessException; void set(Field field, Object target, Object value) throws IllegalAccessException; + + interface OnConstruction { + + Object invoke(ConstructionDispatcher dispatcher) + throws InstantiationException, InvocationTargetException, IllegalAccessException; + } + + interface ConstructionDispatcher { + + Object newInstance() + throws InstantiationException, InvocationTargetException, IllegalAccessException; + } } From c0e48cdc9b0e90b791dc54d0cd88e38dac26f155 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Fri, 21 Aug 2020 09:07:01 +0000 Subject: [PATCH 084/963] 3.5.4 release (previous 3.5.3) + release notes updated by CI build 4728 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 678418e45e..f755623d17 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.4 + - 2020-08-21 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.3...v3.5.4) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.4-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.4) + - Only enable mocking of types right before instantiation to avoid circular interception of constructor creation. [(#2017)](https://github.com/mockito/mockito/pull/2017) + #### 3.5.3 - 2020-08-20 - [3 commits](https://github.com/mockito/mockito/compare/v3.5.2...v3.5.3) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.3-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.3) - [ci maven-central-release] Constructor dispatch [(#2013)](https://github.com/mockito/mockito/pull/2013) diff --git a/version.properties b/version.properties index 10bee63027..03abf9751d 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.4 +version=3.5.5 # Previous version used to generate release notes delta -previousVersion=3.5.3 +previousVersion=3.5.4 From 42a154f235c245740b8292e01782b009843e0090 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Sat, 22 Aug 2020 21:45:11 +0200 Subject: [PATCH 085/963] Add validation to MockMethodDispatcher that this class is only ever loaded by the bootstrap class loader. This is normally assured by Mockito but other testing frameworks that work with instrumentation can interfer with this. This might be difficult to discover for those frameworks as seen with Robolectric. This explicit error should help to discover such discrepencies. --- .../bytebuddy/inject/MockMethodDispatcher.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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 3be8501574..8bc489e7dd 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,6 +11,22 @@ public abstract class MockMethodDispatcher { + static { + ClassLoader classLoader = MockMethodDispatcher.class.getClassLoader(); + if (classLoader != null) { + // Do not use Mockito classes in here as this is executed on the boot loader. + throw new IllegalStateException( + MockMethodDispatcher.class.getName() + + " is not loaded by the bootstrap class loader but by " + + classLoader.toString() + + ".\n\nThis causes the inline mock maker to not work as expected. " + + "Please contact the maintainer of this class loader implementation " + + "to assure that this class is never loaded by another class loader. " + + "The bootstrap class loader must always be queried first for this " + + "class for Mockito's inline mock maker to function correctly."); + } + } + private static final ConcurrentMap DISPATCHERS = new ConcurrentHashMap<>(); From c5406ae5c0c5915ffd02e49a916a261fe7d44d0c Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Sat, 22 Aug 2020 21:46:10 +0200 Subject: [PATCH 086/963] Add validation to MockMethodDispatcher that this class is only ever loaded by the bootstrap class loader. This is normally assured by Mockito but other testing frameworks that work with instrumentation can interfer with this. This might be difficult to discover for those frameworks as seen with Robolectric. This explicit error should help to discover such discrepencies. --- .../creation/bytebuddy/inject/MockMethodDispatcher.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 8bc489e7dd..a6784d36e1 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 @@ -17,8 +17,8 @@ public abstract class MockMethodDispatcher { // Do not use Mockito classes in here as this is executed on the boot loader. throw new IllegalStateException( MockMethodDispatcher.class.getName() - + " is not loaded by the bootstrap class loader but by " - + classLoader.toString() + + " is not loaded by the bootstrap class loader but by an instance of " + + classLoader.getClass().getName() + ".\n\nThis causes the inline mock maker to not work as expected. " + "Please contact the maintainer of this class loader implementation " + "to assure that this class is never loaded by another class loader. " From 065dd127fdd34b6570ae78075c12d4d4026fbbcb Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sat, 22 Aug 2020 20:11:33 +0000 Subject: [PATCH 087/963] 3.5.5 release (previous 3.5.4) + release notes updated by CI build 4734 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index f755623d17..103190cbf8 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.5 + - 2020-08-22 - [3 commits](https://github.com/mockito/mockito/compare/v3.5.4...v3.5.5) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.5-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.5) + - Constructor dispatch [(#2020)](https://github.com/mockito/mockito/pull/2020) + #### 3.5.4 - 2020-08-21 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.3...v3.5.4) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.4-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.4) - Only enable mocking of types right before instantiation to avoid circular interception of constructor creation. [(#2017)](https://github.com/mockito/mockito/pull/2017) diff --git a/version.properties b/version.properties index 03abf9751d..2c986e8329 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.5 +version=3.5.6 # Previous version used to generate release notes delta -previousVersion=3.5.4 +previousVersion=3.5.5 From eaa12bfc018ed00fcd35588dc900d657a9740e32 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 24 Aug 2020 10:29:12 +0200 Subject: [PATCH 088/963] Add suspension when Mockito exception is thrown. --- .../bytebuddy/InlineByteBuddyMockMaker.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) 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 1287219340..96477f4776 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -265,12 +265,18 @@ public InlineByteBuddyMockMaker() { } else if (type.isInstance(spy)) { return spy; } else { - // Unexpected construction of non-spied object - throw new MockitoException( - "Unexpected spy for " - + type.getName() - + " on instance of " - + object.getClass().getName()); + isSuspended.set(true); + try { + // Unexpected construction of non-spied object + throw new MockitoException( + "Unexpected spy for " + + type.getName() + + " on instance of " + + object.getClass().getName(), + object instanceof Throwable ? (Throwable) object : null); + } finally { + isSuspended.set(false); + } } } else if (currentConstruction.get() != type) { return null; From 57f7db8c4c72f06cb6c94a7edce1f255847e12ac Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 24 Aug 2020 12:27:55 +0200 Subject: [PATCH 089/963] Refine module openness check --- .../reflection/InstrumentationMemberAccessor.java | 12 ++++++++---- subprojects/inline/inline.gradle | 4 ++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java index a8e1c26467..d1bfa4e809 100644 --- a/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java +++ b/src/main/java/org/mockito/internal/util/reflection/InstrumentationMemberAccessor.java @@ -95,6 +95,7 @@ class InstrumentationMemberAccessor implements MemberAccessor { INITIALIZATION_ERROR = throwable; } + @SuppressWarnings("unused") private final MethodHandle getModule, isOpen, redefineModule, privateLookupIn; InstrumentationMemberAccessor() { @@ -116,7 +117,7 @@ class InstrumentationMemberAccessor implements MemberAccessor { .findVirtual( module, "isOpen", - MethodType.methodType(boolean.class, String.class, module)); + MethodType.methodType(boolean.class, String.class)); redefineModule = MethodHandles.publicLookup() .findVirtual( @@ -330,9 +331,12 @@ public void set(Field field, Object target, Object value) throws IllegalAccessEx } private void assureOpen(Object module, String packageName) throws Throwable { - if (!(Boolean) - DISPATCHER.invokeWithArguments( - isOpen, module, packageName, DISPATCHER.getModule())) { + // It would be more reliable to check if a module's package already is opened to + // the dispatcher module from before. Unfortunately, there is no reliable check + // for doing so since the isOpen(String, Module) method always returns true + // if the second argument is an unnamed module. Therefore, for now, we need + // to reopen packages even if they are already opened to the dispatcher module. + if (!(Boolean) DISPATCHER.invokeWithArguments(isOpen, module, packageName)) { DISPATCHER.invokeWithArguments( redefineModule.bindTo(INSTRUMENTATION), module, diff --git a/subprojects/inline/inline.gradle b/subprojects/inline/inline.gradle index 22db17b067..1fc71c86b2 100644 --- a/subprojects/inline/inline.gradle +++ b/subprojects/inline/inline.gradle @@ -12,3 +12,7 @@ tasks.javadoc.enabled = false //required by the "StressTest.java" and "OneLinerStubStressTest.java" test.maxHeapSize = "256m" retryTest.maxHeapSize = "256m" + +test { + jvmArgs '--illegal-access=debug' +} From f48b98ac940e8e9e3f0782b37247f031507566da Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 24 Aug 2020 23:51:25 +0200 Subject: [PATCH 090/963] Only apply argument on illegal module access for inline tests if Java version is at least 9. --- subprojects/inline/inline.gradle | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/subprojects/inline/inline.gradle b/subprojects/inline/inline.gradle index 1fc71c86b2..9d9b39d6c7 100644 --- a/subprojects/inline/inline.gradle +++ b/subprojects/inline/inline.gradle @@ -13,6 +13,8 @@ tasks.javadoc.enabled = false test.maxHeapSize = "256m" retryTest.maxHeapSize = "256m" -test { - jvmArgs '--illegal-access=debug' +if (JavaVersion.current().java9Compatible) { + test { + jvmArgs '--illegal-access=deny' + } } From 929840ab691b2f502b9958ac9483104bfd88a9ee Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Mon, 24 Aug 2020 22:21:12 +0000 Subject: [PATCH 091/963] 3.5.6 release (previous 3.5.5) + release notes updated by CI build 4744 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 103190cbf8..2e36d33b49 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.6 + - 2020-08-24 - [5 commits](https://github.com/mockito/mockito/compare/v3.5.5...v3.5.6) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.6-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.6) + - Only apply argument on illegal module access for inline tests if Java version is at least 9. [(#2022)](https://github.com/mockito/mockito/pull/2022) + - Constructor dispatch [(#2021)](https://github.com/mockito/mockito/pull/2021) + #### 3.5.5 - 2020-08-22 - [3 commits](https://github.com/mockito/mockito/compare/v3.5.4...v3.5.5) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.5-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.5) - Constructor dispatch [(#2020)](https://github.com/mockito/mockito/pull/2020) diff --git a/version.properties b/version.properties index 2c986e8329..b6f1ad233c 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.6 +version=3.5.7 # Previous version used to generate release notes delta -previousVersion=3.5.5 +previousVersion=3.5.6 From 24d8d790c22913a9a92ea70bad721b06a735cd46 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Wed, 26 Aug 2020 00:08:57 +0200 Subject: [PATCH 092/963] Initializes classes prior to instrumentation to avoid uncontrolled code execution. Fixes \# #2011 --- .../bytebuddy/InlineBytecodeGenerator.java | 10 ++++++++ .../org/mockitoinline/InitializationTest.java | 25 +++++++++++++++++++ .../java/org/mockitoinline/PluginTest.java | 8 +++++- 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 subprojects/inline/src/test/java/org/mockitoinline/InitializationTest.java 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 409f58201c..067dea7a04 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -206,6 +206,7 @@ public Class mockClass(MockFeatures features) { Set> types = new HashSet<>(); types.add(features.mockedType); types.addAll(features.interfaces); + synchronized (this) { triggerRetransformation(types, false); } @@ -223,17 +224,26 @@ public synchronized void mockClassConstruction(Class type) { triggerRetransformation(Collections.singleton(type), false); } + private static void assureInitialization(Class type) { + try { + Class.forName(type.getName(), true, type.getClassLoader()); + } catch (Throwable ignore) { + } + } + private void triggerRetransformation(Set> types, boolean flat) { Set> targets = new HashSet>(); for (Class type : types) { if (flat) { if (!mocked.contains(type) && flatMocked.add(type)) { + assureInitialization(type); targets.add(type); } } else { do { if (mocked.add(type)) { + assureInitialization(type); if (!flatMocked.remove(type)) { targets.add(type); } diff --git a/subprojects/inline/src/test/java/org/mockitoinline/InitializationTest.java b/subprojects/inline/src/test/java/org/mockitoinline/InitializationTest.java new file mode 100644 index 0000000000..c4f62f400f --- /dev/null +++ b/subprojects/inline/src/test/java/org/mockitoinline/InitializationTest.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitoinline; + +import org.junit.Test; +import org.mockito.Mockito; + +import static junit.framework.TestCase.assertEquals; + +public class InitializationTest { + + @Test + public void assure_initialization_prior_to_instrumentation() { + @SuppressWarnings("unused") + SampleEnum mock = Mockito.mock(SampleEnum.class); + SampleEnum[] values = SampleEnum.values(); + assertEquals("VALUE", values[0].name()); + } + + public enum SampleEnum { + VALUE + } +} diff --git a/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java b/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java index 19526db2a9..16e2da2915 100644 --- a/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java +++ b/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java @@ -7,14 +7,20 @@ import org.junit.Test; import org.mockito.internal.configuration.plugins.Plugins; import org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker; +import org.mockito.internal.util.reflection.ModuleMemberAccessor; import static org.junit.Assert.*; public class PluginTest { @Test - public void plugin_type_should_be_inline() throws Exception { + public void mock_maker_should_be_inline() throws Exception { assertTrue(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker); } + @Test + public void member_accessor_should_be_module() throws Exception { + assertTrue(Plugins.getMemberAccessor() instanceof ModuleMemberAccessor); + } + } From 8007df7a25d6c59eb561c1f6023d724d3b3c167f Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Tue, 25 Aug 2020 22:39:16 +0000 Subject: [PATCH 093/963] 3.5.7 release (previous 3.5.6) + release notes updated by CI build 4749 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 2e36d33b49..19d0aea2f2 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.7 + - 2020-08-25 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.6...v3.5.7) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.7-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.7) + - Initializes classes prior to instrumentation to avoid uncontrolled code execution. [(#2023)](https://github.com/mockito/mockito/pull/2023) + - Stackoverflow error when upgrading to v3.5.2 [(#2011)](https://github.com/mockito/mockito/issues/2011) + #### 3.5.6 - 2020-08-24 - [5 commits](https://github.com/mockito/mockito/compare/v3.5.5...v3.5.6) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.6-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.6) - Only apply argument on illegal module access for inline tests if Java version is at least 9. [(#2022)](https://github.com/mockito/mockito/pull/2022) diff --git a/version.properties b/version.properties index b6f1ad233c..487925c725 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.7 +version=3.5.8 # Previous version used to generate release notes delta -previousVersion=3.5.6 +previousVersion=3.5.7 From 282855246f2428fdd8563815cb5e46ffd2d0471d Mon Sep 17 00:00:00 2001 From: ahmadmoawad Date: Thu, 27 Aug 2020 20:22:15 +0200 Subject: [PATCH 094/963] Fix typo in CONTRIBUTING.md and SpyOnInjectedFieldsHandler (#1994) --- .github/CONTRIBUTING.md | 2 +- .../configuration/injection/SpyOnInjectedFieldsHandler.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index f8135316b5..dcb6481825 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -48,7 +48,7 @@ Things we pay attention in a PR : For that matter it's possible to commit [_semantic_ changes](http://lemike-de.tumblr.com/post/79041908218/semantic-commits). _Tests are an asset, so is history_. - _Exemple gratia_: + _Example gratia_: ``` Fixes #73 : The new feature 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 6230e1b86f..73f3004c19 100644 --- a/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java +++ b/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java @@ -33,7 +33,7 @@ public class SpyOnInjectedFieldsHandler extends MockInjectionStrategy { protected boolean processInjection(Field field, Object fieldOwner, Set mockCandidates) { FieldReader fieldReader = new FieldReader(fieldOwner, field); - // TODO refoctor : code duplicated in SpyAnnotationEngine + // TODO refactor : code duplicated in SpyAnnotationEngine if (!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) { try { Object instance = fieldReader.read(); From a8b156509fc8e35cf122e1abe8c36d1e196ed041 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 27 Aug 2020 18:28:44 +0000 Subject: [PATCH 095/963] 3.5.8 release (previous 3.5.7) + release notes updated by CI build 4758 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 19d0aea2f2..8e6b0f8f39 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.8 + - 2020-08-27 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.7...v3.5.8) by [ahmadmoawad](https://github.com/ahmadmoawad) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.8-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.8) + - Fix typo in CONTRIBUTING.md and SpyOnInjectedFieldsHandler [(#1994)](https://github.com/mockito/mockito/pull/1994) + #### 3.5.7 - 2020-08-25 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.6...v3.5.7) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.7-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.7) - Initializes classes prior to instrumentation to avoid uncontrolled code execution. [(#2023)](https://github.com/mockito/mockito/pull/2023) diff --git a/version.properties b/version.properties index 487925c725..6c4ced6b5e 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.8 +version=3.5.9 # Previous version used to generate release notes delta -previousVersion=3.5.7 +previousVersion=3.5.8 From 626d4573c702625611d2024463bae606a4e8cca4 Mon Sep 17 00:00:00 2001 From: Sinan Kozak Date: Wed, 2 Sep 2020 01:26:24 +0300 Subject: [PATCH 096/963] Fixes #2007 : Downgrade objenesis version for mockito-android (#2024) [ci maven-central-release] Co-authored-by: Tim van der Lippe --- build.gradle | 2 +- gradle/dependencies.gradle | 4 +++- subprojects/android/android.gradle | 23 ++++++++++++++++++++++- subprojects/osgi-test/osgi-test.gradle | 2 +- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 217f71d4b2..e30ddb1a5a 100644 --- a/build.gradle +++ b/build.gradle @@ -88,7 +88,7 @@ dependencies { compile libraries.bytebuddy, libraries.bytebuddyagent compileOnly libraries.junit4, libraries.hamcrest, libraries.opentest4j - compile libraries.objenesis + compile libraries.objenesis3 testCompile libraries.asm diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 9ae3679927..f907965b08 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -25,7 +25,9 @@ libraries.errorproneTestApi = "com.google.errorprone:error_prone_test_helpers:${ libraries.autoservice = "com.google.auto.service:auto-service:1.0-rc5" -libraries.objenesis = 'org.objenesis:objenesis:3.1' +// objenesis 3.x fails on android instrumentation test compile. https://github.com/mockito/mockito/issues/2007 +libraries.objenesis2 = 'org.objenesis:objenesis:2.6' +libraries.objenesis3 = 'org.objenesis:objenesis:3.1' libraries.asm = 'org.ow2.asm:asm:7.0' diff --git a/subprojects/android/android.gradle b/subprojects/android/android.gradle index 8f86eabb98..bd5a6959a2 100644 --- a/subprojects/android/android.gradle +++ b/subprojects/android/android.gradle @@ -3,8 +3,29 @@ description = "Mockito for Android" apply from: "$rootDir/gradle/java-library.gradle" dependencies { - compile project.rootProject + compile(project.rootProject) { + exclude group: 'org.objenesis', module: 'objenesis' + } compile libraries.bytebuddyandroid + compile(libraries.objenesis2) { + version { + strictly '[2.6, 3.0[' + } + because( + '\n' + + 'MOCKITO DEPENDENCY PROBLEM:\n' + + '\n' + + 'Mockito core uses Objenesis 3.x and Objenesis 3.x does not work with android api 25 and below.\n' + + 'If you have mockito-core dependency with mockito-android, remove mockito-core.\n' + + 'If you have mockito-kotlin, exclude mockito-core.\n' + + 'implementation("com.nhaarman.mockitokotlin2:mockito-kotlin") {\n' + + ' exclude group: "org.mockito", module: "mockito-core"\n' + + '}\n' + + 'For more information please check; \n' + + ' https://github.com/mockito/mockito/pull/2024\n' + + ' https://github.com/mockito/mockito/pull/2007\n' + ) + } } tasks.javadoc.enabled = false diff --git a/subprojects/osgi-test/osgi-test.gradle b/subprojects/osgi-test/osgi-test.gradle index 8ebcc042f3..ad5964c543 100644 --- a/subprojects/osgi-test/osgi-test.gradle +++ b/subprojects/osgi-test/osgi-test.gradle @@ -23,7 +23,7 @@ configurations { dependencies { testRuntimeBundles project.rootProject testRuntimeBundles libraries.bytebuddy - testRuntimeBundles libraries.objenesis + testRuntimeBundles libraries.objenesis3 testRuntimeBundles tasks.testBundle.outputs.files testRuntimeBundles tasks.otherBundle.outputs.files } From fcd788cf20bdd2ead398706afeb6beb5411831b8 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Tue, 1 Sep 2020 22:32:36 +0000 Subject: [PATCH 097/963] 3.5.9 release (previous 3.5.8) + release notes updated by CI build 4763 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 8e6b0f8f39..dfc13572fe 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.9 + - 2020-09-01 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.8...v3.5.9) by [Sinan Kozak](https://github.com/kozaxinan) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.9-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.9) + - Fixes #2007 : Downgrade objenesis version for mockito-android [(#2024)](https://github.com/mockito/mockito/pull/2024) + - Android instrumentation test packaging fails for mockito-android 3.5.0 with minSdk < 26 [(#2007)](https://github.com/mockito/mockito/issues/2007) + #### 3.5.8 - 2020-08-27 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.7...v3.5.8) by [ahmadmoawad](https://github.com/ahmadmoawad) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.8-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.8) - Fix typo in CONTRIBUTING.md and SpyOnInjectedFieldsHandler [(#1994)](https://github.com/mockito/mockito/pull/1994) diff --git a/version.properties b/version.properties index 6c4ced6b5e..b621277ab1 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.9 +version=3.5.10 # Previous version used to generate release notes delta -previousVersion=3.5.8 +previousVersion=3.5.9 From 093d5279456ccafcaf9c56a437e4a504e7b70dc4 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 3 Sep 2020 22:47:13 +0200 Subject: [PATCH 098/963] Escape mock during method dispatch on mock to avoid premature garbage collection. Fixes #1802. --- .../bytebuddy/MockMethodInterceptor.java | 44 +++++++++++++++---- .../PrematureGarbageCollectionTest.java | 43 ++++++++++++++++++ 2 files changed, 79 insertions(+), 8 deletions(-) create mode 100644 src/test/java/org/mockito/PrematureGarbageCollectionTest.java 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 532ecc804d..0ca02727f1 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java @@ -6,6 +6,8 @@ import static org.mockito.internal.invocation.DefaultInvocationFactory.createInvocation; +import java.io.IOException; +import java.io.ObjectInputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.Method; @@ -36,12 +38,19 @@ public class MockMethodInterceptor implements Serializable { private final ByteBuddyCrossClassLoaderSerializationSupport serializationSupport; + private transient ThreadLocal weakReferenceHatch = new ThreadLocal<>(); + public MockMethodInterceptor(MockHandler handler, MockCreationSettings mockCreationSettings) { this.handler = handler; this.mockCreationSettings = mockCreationSettings; serializationSupport = new ByteBuddyCrossClassLoaderSerializationSupport(); } + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + weakReferenceHatch = new ThreadLocal<>(); + } + Object doIntercept(Object mock, Method invokedMethod, Object[] arguments, RealMethod realMethod) throws Throwable { return doIntercept(mock, invokedMethod, arguments, realMethod, new LocationImpl()); @@ -54,14 +63,33 @@ Object doIntercept( RealMethod realMethod, Location location) throws Throwable { - return handler.handle( - createInvocation( - mock, - invokedMethod, - arguments, - realMethod, - mockCreationSettings, - location)); + // If the currently dispatched method is used in a hot path, typically a tight loop and if + // the mock is not used after the currently dispatched method, the JVM might attempt a + // garbage collection of the mock instance even before the execution of the current + // method is completed. Since we only reference the mock weakly from hereon after to avoid + // leaking the instance, it might therefore be garbage collected before the + // handler.handle(...) method completes. Since the handler method expects the mock to be + // present while a method call onto the mock is dispatched, this can lead to the problem + // described in GitHub #1802. + // + // To avoid this problem, we distract the JVM JIT by escaping the mock instance to a thread + // local field for the duration of the handler's dispatch. + // + // When dropping support for Java 8, instead of this hatch we should use an explicit fence + // https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Reference.html#reachabilityFence-java.lang.Object- + weakReferenceHatch.set(mock); + try { + return handler.handle( + createInvocation( + mock, + invokedMethod, + arguments, + realMethod, + mockCreationSettings, + location)); + } finally { + weakReferenceHatch.remove(); + } } public MockHandler getMockHandler() { diff --git a/src/test/java/org/mockito/PrematureGarbageCollectionTest.java b/src/test/java/org/mockito/PrematureGarbageCollectionTest.java new file mode 100644 index 0000000000..cb10a9298a --- /dev/null +++ b/src/test/java/org/mockito/PrematureGarbageCollectionTest.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito; + +import org.junit.Test; + +public class PrematureGarbageCollectionTest { + + @Test + public void provoke_premature_garbage_collection() { + for (int i = 0; i < 500; i++) { + populateNodeList(); + } + } + + private static void populateNodeList() { + Node node = nodes(); + while (node != null) { + Node next = node.next; + node.object.run(); + node = next; + } + } + + private static Node nodes() { + Node node = null; + for (int i = 0; i < 1_000; ++i) { + Node next = new Node(); + next.next = node; + node = next; + } + return node; + } + + private static class Node { + + private Node next; + + private final Runnable object = Mockito.mock(Runnable.class); + } +} From b6ae6cf12b93ef9445e524224375aab1eb76129d Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 3 Sep 2020 22:41:41 +0000 Subject: [PATCH 099/963] 3.5.10 release (previous 3.5.9) + release notes updated by CI build 4773 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index dfc13572fe..63b0113421 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.10 + - 2020-09-03 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.9...v3.5.10) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.10-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.10) + - Escape mock during method dispatch on mock to avoid premature garbage collection. [(#2034)](https://github.com/mockito/mockito/pull/2034) + - Exception "The mock object was garbage collected." [(#1802)](https://github.com/mockito/mockito/issues/1802) + #### 3.5.9 - 2020-09-01 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.8...v3.5.9) by [Sinan Kozak](https://github.com/kozaxinan) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.9-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.9) - Fixes #2007 : Downgrade objenesis version for mockito-android [(#2024)](https://github.com/mockito/mockito/pull/2024) diff --git a/version.properties b/version.properties index b621277ab1..087c94e069 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.10 +version=3.5.11 # Previous version used to generate release notes delta -previousVersion=3.5.9 +previousVersion=3.5.10 From e6fdaf766d42b9acda43ed1a7ced02b83859196d Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 14 Sep 2020 19:56:33 +0200 Subject: [PATCH 100/963] Complete javadoc. --- src/main/java/org/mockito/plugins/MockMaker.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/plugins/MockMaker.java b/src/main/java/org/mockito/plugins/MockMaker.java index fbdaf1d0e6..fcebbb3ae7 100644 --- a/src/main/java/org/mockito/plugins/MockMaker.java +++ b/src/main/java/org/mockito/plugins/MockMaker.java @@ -85,7 +85,7 @@ public interface MockMaker { * {@link #getHandler(Object)} will return this instance. * @param instance The object to spy upon. * @param Type of the mock to return, actually the settings.getTypeToMock. - * @return + * @return The spy instance, if this mock maker supports direct spy creation. * @since 3.5.0 */ default Optional createSpy( From 48d817fe83c556e95cf84e87d9a119211351a08f Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Mon, 14 Sep 2020 20:28:50 +0200 Subject: [PATCH 101/963] Add mock resolver API to allow for resolving provided instances from third-party frameworks. --- .../configuration/plugins/PluginFinder.java | 28 ++++++++++ .../plugins/PluginInitializer.java | 34 +++++++++++++ .../configuration/plugins/PluginLoader.java | 30 +++++++++++ .../configuration/plugins/PluginRegistry.java | 14 +++++ .../configuration/plugins/Plugins.java | 11 ++++ .../internal/util/DefaultMockingDetails.java | 2 +- .../org/mockito/internal/util/MockUtil.java | 25 +++++++-- .../org/mockito/plugins/MockResolver.java | 22 ++++++++ .../plugins/resolver/MockResolverTest.java | 51 +++++++++++++++++++ .../plugins/resolver/MyMockResolver.java | 18 +++++++ .../plugins/switcher/PluginSwitchTest.java | 2 + .../org.mockito.plugins.MockResolver | 1 + 12 files changed, 233 insertions(+), 5 deletions(-) create mode 100644 src/main/java/org/mockito/plugins/MockResolver.java create mode 100644 subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MockResolverTest.java create mode 100644 subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MyMockResolver.java create mode 100644 subprojects/extTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockResolver 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 7385afb184..3ca2ac5cd4 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginFinder.java @@ -6,6 +6,8 @@ import java.io.InputStream; import java.net.URL; +import java.util.ArrayList; +import java.util.List; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.util.io.IOUtil; @@ -43,4 +45,30 @@ String findPluginClass(Iterable resources) { } return null; } + + List findPluginClasses(Iterable resources) { + List pluginClassNames = new ArrayList<>(); + for (URL resource : resources) { + InputStream s = null; + try { + 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 + continue; + } + if (!pluginSwitch.isEnabled(pluginClassName)) { + continue; + } + pluginClassNames.add(pluginClassName); + } catch (Exception e) { + throw new MockitoException( + "Problems reading plugin implementation from: " + resource, e); + } finally { + IOUtil.closeQuietly(s); + } + } + return pluginClassNames; + } } 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 8f8f76edcb..296397edc3 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginInitializer.java @@ -6,7 +6,9 @@ import java.io.IOException; import java.net.URL; +import java.util.ArrayList; import java.util.Enumeration; +import java.util.List; import org.mockito.internal.util.collections.Iterables; import org.mockito.plugins.PluginSwitch; @@ -56,4 +58,36 @@ public T loadImpl(Class service) { "Failed to load " + service + " implementation declared in " + resources, e); } } + + public List loadImpls(Class service) { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + if (loader == null) { + loader = ClassLoader.getSystemClassLoader(); + } + Enumeration resources; + try { + resources = loader.getResources("mockito-extensions/" + service.getName()); + } catch (IOException e) { + throw new IllegalStateException("Failed to load " + service, e); + } + + try { + List classesOrAliases = + new PluginFinder(pluginSwitch) + .findPluginClasses(Iterables.toIterable(resources)); + List impls = new ArrayList<>(); + for (String classOrAlias : classesOrAliases) { + if (classOrAlias.equals(alias)) { + classOrAlias = plugins.getDefaultPluginClass(alias); + } + Class pluginClass = loader.loadClass(classOrAlias); + Object plugin = pluginClass.getDeclaredConstructor().newInstance(); + impls.add(service.cast(plugin)); + } + return impls; + } catch (Exception e) { + throw new IllegalStateException( + "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 3d724aa49a..e76bb9729f 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/PluginLoader.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginLoader.java @@ -7,6 +7,8 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.Collections; +import java.util.List; import org.mockito.plugins.PluginSwitch; @@ -90,4 +92,32 @@ public Object invoke(Object proxy, Method method, Object[] args) }); } } + + /** + * Scans the classpath for given {@code pluginType} and returns a list of its instances. + * + * @return An list of {@code pluginType} or an empty list if none was found. + */ + @SuppressWarnings("unchecked") + List loadPlugins(final Class pluginType) { + try { + return initializer.loadImpls(pluginType); + } catch (final Throwable t) { + return Collections.singletonList( + (T) + Proxy.newProxyInstance( + pluginType.getClassLoader(), + new Class[] {pluginType}, + new InvocationHandler() { + @Override + public Object invoke( + Object proxy, Method method, Object[] args) + throws Throwable { + throw new IllegalStateException( + "Could not initialize plugin: " + pluginType, + 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 ba7aae1728..9a12d1755a 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java @@ -7,6 +7,8 @@ import org.mockito.internal.creation.instance.InstantiatorProviderAdapter; import org.mockito.plugins.*; +import java.util.List; + class PluginRegistry { private final PluginSwitch pluginSwitch = @@ -31,6 +33,9 @@ class PluginRegistry { private final MockitoLogger mockitoLogger = new PluginLoader(pluginSwitch).loadPlugin(MockitoLogger.class); + private final List mockResolvers = + new PluginLoader(pluginSwitch).loadPlugins(MockResolver.class); + PluginRegistry() { Object impl = new PluginLoader(pluginSwitch) @@ -100,4 +105,13 @@ AnnotationEngine getAnnotationEngine() { MockitoLogger getMockitoLogger() { return mockitoLogger; } + + /** + * Returns a list of available mock resolvers if any. + * + * @return A list of available mock resolvers or an empty list if none are registered. + */ + List getMockResolvers() { + return mockResolvers; + } } 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 603a03008a..da225a2886 100644 --- a/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java +++ b/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java @@ -6,6 +6,8 @@ import org.mockito.plugins.*; +import java.util.List; + /** * Access to Mockito behavior that can be reconfigured by plugins */ @@ -71,6 +73,15 @@ public static MockitoLogger getMockitoLogger() { return registry.getMockitoLogger(); } + /** + * Returns a list of available mock resolvers if any. + * + * @return A list of available mock resolvers or an empty list if none are registered. + */ + public static List getMockResolvers() { + return registry.getMockResolvers(); + } + /** * @return instance of mockito plugins type */ diff --git a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java index e9887a57b5..1ad5a757f8 100644 --- a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java +++ b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java @@ -73,7 +73,7 @@ public Object getMock() { return toInspect; } - private MockHandler mockHandler() { + private MockHandler mockHandler() { assertGoodMock(); return MockUtil.getMockHandler(toInspect); } diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java index 46e782cba0..9ee2cd5315 100644 --- a/src/main/java/org/mockito/internal/util/MockUtil.java +++ b/src/main/java/org/mockito/internal/util/MockUtil.java @@ -16,6 +16,7 @@ import org.mockito.mock.MockName; import org.mockito.plugins.MockMaker; import org.mockito.plugins.MockMaker.TypeMockability; +import org.mockito.plugins.MockResolver; import java.util.function.Function; @@ -63,13 +64,16 @@ public static void resetMock(T mock) { mockMaker.resetMock(mock, newHandler, settings); } - public static MockHandler getMockHandler(T mock) { + public static MockHandler getMockHandler(Object mock) { if (mock == null) { throw new NotAMockException("Argument should be a mock, but is null!"); } - if (isMock(mock)) { - return mockMaker.getHandler(mock); + mock = resolve(mock); + + MockHandler handler = mockMaker.getHandler(mock); + if (handler != null) { + return handler; } else { throw new NotAMockException("Argument should be a mock, but is: " + mock.getClass()); } @@ -96,7 +100,20 @@ public static boolean isMock(Object mock) { // 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; + if (mock == null) { + return false; + } + + mock = resolve(mock); + + return mockMaker.getHandler(mock) != null; + } + + private static Object resolve(Object mock) { + for (MockResolver mockResolver : Plugins.getMockResolvers()) { + mock = mockResolver.resolve(mock); + } + return mock; } public static MockName getMockName(Object mock) { diff --git a/src/main/java/org/mockito/plugins/MockResolver.java b/src/main/java/org/mockito/plugins/MockResolver.java new file mode 100644 index 0000000000..6eaa756f7e --- /dev/null +++ b/src/main/java/org/mockito/plugins/MockResolver.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockito.plugins; + +/** + * A mock resolver offers an opportunity to resolve a mock from any instance that is + * provided to the {@link org.mockito.Mockito}-DSL. This mechanism can be used by + * frameworks that provide mocks that are implemented by Mockito but which are wrapped + * by other instances to enhance the proxy further. + */ +public interface MockResolver { + + /** + * Returns the provided instance or the unwrapped mock that the provided + * instance represents. This method must not return {@code null}. + * @param instance The instance passed to the {@link org.mockito.Mockito}-DSL. + * @return The provided instance or the unwrapped mock. + */ + Object resolve(Object instance); +} diff --git a/subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MockResolverTest.java b/subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MockResolverTest.java new file mode 100644 index 0000000000..bd51fe6dc2 --- /dev/null +++ b/subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MockResolverTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitousage.plugins.resolver; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +@MockitoSettings(strictness = Strictness.WARN) +@ExtendWith(MockitoExtension.class) +class MockResolverTest { + + @Test + void mock_resolver_can_unwrap_mocked_instance() { + Foo mock = mock(Foo.class), wrapper = new MockWrapper(mock); + when(wrapper.doIt()).thenReturn(123); + assertThat(mock.doIt()).isEqualTo(123); + assertThat(wrapper.doIt()).isEqualTo(123); + verify(wrapper, times(2)).doIt(); + } + + interface Foo { + int doIt(); + } + + static class MockWrapper implements Foo { + + private final Foo mock; + + MockWrapper(Foo mock) { + this.mock = mock; + } + + Object getMock() { + return mock; + } + + @Override + public int doIt() { + return mock.doIt(); + } + } + +} diff --git a/subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MyMockResolver.java b/subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MyMockResolver.java new file mode 100644 index 0000000000..e14804f6c5 --- /dev/null +++ b/subprojects/extTest/src/test/java/org/mockitousage/plugins/resolver/MyMockResolver.java @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2020 Mockito contributors + * This program is made available under the terms of the MIT License. + */ +package org.mockitousage.plugins.resolver; + +import org.mockito.plugins.MockResolver; + +public class MyMockResolver implements MockResolver { + + @Override + public Object resolve(Object instance) { + if (instance instanceof MockResolverTest.MockWrapper) { + return ((MockResolverTest.MockWrapper) instance).getMock(); + } + return instance; + } +} diff --git a/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/PluginSwitchTest.java b/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/PluginSwitchTest.java index d61f150bae..000c2e8ca9 100644 --- a/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/PluginSwitchTest.java +++ b/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/PluginSwitchTest.java @@ -7,6 +7,7 @@ import org.junit.Test; import org.mockitousage.plugins.instantiator.MyInstantiatorProvider2; import org.mockitousage.plugins.logger.MyMockitoLogger; +import org.mockitousage.plugins.resolver.MyMockResolver; import org.mockitousage.plugins.stacktrace.MyStackTraceCleanerProvider; import java.util.List; @@ -25,6 +26,7 @@ public void plugin_switcher_is_used() { assertEquals(MyPluginSwitch.invokedFor, asList(MyMockMaker.class.getName(), MyStackTraceCleanerProvider.class.getName(), MyMockitoLogger.class.getName(), + MyMockResolver.class.getName(), MyInstantiatorProvider2.class.getName())); } diff --git a/subprojects/extTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockResolver b/subprojects/extTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockResolver new file mode 100644 index 0000000000..7f2835f93a --- /dev/null +++ b/subprojects/extTest/src/test/resources/mockito-extensions/org.mockito.plugins.MockResolver @@ -0,0 +1 @@ +org.mockitousage.plugins.resolver.MyMockResolver From 4a40f582397c40fbce587af3e2f1e16583228e5e Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 17 Sep 2020 00:40:07 +0200 Subject: [PATCH 102/963] Do not exclude synthetic constructors from instrumentation. Fixes #2040. --- .../creation/bytebuddy/InlineBytecodeGenerator.java | 3 ++- .../internal/creation/bytebuddy/MockMethodAdvice.java | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) 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 067dea7a04..2bf9d15769 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -91,7 +91,8 @@ public InlineBytecodeGenerator( new ByteBuddy() .with(TypeValidation.DISABLED) .with(Implementation.Context.Disabled.Factory.INSTANCE) - .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE); + .with(MethodGraph.Compiler.ForDeclaredMethods.INSTANCE) + .ignore(isSynthetic().and(not(isConstructor())).or(isDefaultFinalizer())); mocked = new WeakConcurrentSet<>(WeakConcurrentSet.Cleaner.INLINE); flatMocked = new WeakConcurrentSet<>(WeakConcurrentSet.Cleaner.INLINE); String identifier = RandomString.make(); 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 69a7ed21a6..a12c70199f 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -397,13 +397,14 @@ public MethodVisitor wrap( .getDeclaredMethods() .filter(isConstructor().and(not(isPrivate()))); int arguments = Integer.MAX_VALUE; - boolean visible = false; + boolean packagePrivate = true; MethodDescription.InDefinedShape current = null; for (MethodDescription.InDefinedShape constructor : constructors) { if (constructor.getParameters().size() < arguments - && (!visible || constructor.isPackagePrivate())) { + && (packagePrivate || !constructor.isPackagePrivate())) { + arguments = constructor.getParameters().size(); + packagePrivate = constructor.isPackagePrivate(); current = constructor; - visible = constructor.isPackagePrivate(); } } if (current != null) { From 5a664cfd68bd50d3f3447ce44879d60045b199ec Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 17 Sep 2020 21:34:18 +0000 Subject: [PATCH 103/963] 3.5.11 release (previous 3.5.10) + release notes updated by CI build 4792 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 63b0113421..8601f484e3 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.11 + - 2020-09-17 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.10...v3.5.11) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.11-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.11) + - Do not exclude synthetic constructors from instrumentation. Fixes #2040. [(#2046)](https://github.com/mockito/mockito/pull/2046) + - Mockito.spy(Activity).getBaseContext() returns null on Robolectric 4.4 and Java8 [(#2040)](https://github.com/mockito/mockito/issues/2040) + #### 3.5.10 - 2020-09-03 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.9...v3.5.10) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.10-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.10) - Escape mock during method dispatch on mock to avoid premature garbage collection. [(#2034)](https://github.com/mockito/mockito/pull/2034) diff --git a/version.properties b/version.properties index 087c94e069..f7a6424065 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.11 +version=3.5.12 # Previous version used to generate release notes delta -previousVersion=3.5.10 +previousVersion=3.5.11 From c81b028f4ac121f4939341ef724465d307274cd0 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Wed, 16 Sep 2020 01:11:01 +0200 Subject: [PATCH 104/963] Fixing "best" constructor choice. --- .../internal/creation/bytebuddy/MockMethodAdvice.java | 10 +++++++--- src/main/java/org/mockito/internal/util/MockUtil.java | 6 +++++- 2 files changed, 12 insertions(+), 4 deletions(-) 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 69a7ed21a6..9323368a14 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -397,13 +397,17 @@ public MethodVisitor wrap( .getDeclaredMethods() .filter(isConstructor().and(not(isPrivate()))); int arguments = Integer.MAX_VALUE; - boolean visible = false; + boolean packagePrivate = true; MethodDescription.InDefinedShape current = null; for (MethodDescription.InDefinedShape constructor : constructors) { + // We are choosing the shortest constructor with regards to arguments. + // Yet, we prefer a non-package-private constructor since they require + // the super class to be on the same class loader. if (constructor.getParameters().size() < arguments - && (!visible || constructor.isPackagePrivate())) { + && (packagePrivate || !constructor.isPackagePrivate())) { + arguments = constructor.getParameters().size(); + packagePrivate = constructor.isPackagePrivate(); current = constructor; - visible = constructor.isPackagePrivate(); } } if (current != null) { diff --git a/src/main/java/org/mockito/internal/util/MockUtil.java b/src/main/java/org/mockito/internal/util/MockUtil.java index 9ee2cd5315..25a29d2c0d 100644 --- a/src/main/java/org/mockito/internal/util/MockUtil.java +++ b/src/main/java/org/mockito/internal/util/MockUtil.java @@ -56,11 +56,12 @@ public static T createMock(MockCreationSettings settings) { return mock; } - public static void resetMock(T mock) { + public static void resetMock(Object mock) { MockHandler oldHandler = getMockHandler(mock); MockCreationSettings settings = oldHandler.getMockSettings(); MockHandler newHandler = createMockHandler(settings); + mock = resolve(mock); mockMaker.resetMock(mock, newHandler, settings); } @@ -110,6 +111,9 @@ public static boolean isMock(Object mock) { } private static Object resolve(Object mock) { + if (mock instanceof Class) { // static mocks are resolved by definition + return mock; + } for (MockResolver mockResolver : Plugins.getMockResolvers()) { mock = mockResolver.resolve(mock); } From 6ec033c1e4a2c59a636573d79620fc287ebe86ae Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Sat, 19 Sep 2020 01:47:06 +0200 Subject: [PATCH 105/963] Update Byte Buddy to 1.10.15 (#2050) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index f907965b08..e8166e5c6d 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -4,7 +4,7 @@ ext { def versions = [:] -versions.bytebuddy = '1.10.13' +versions.bytebuddy = '1.10.15' versions.junitJupiter = '5.4.2' versions.errorprone = '2.4.0' From e338d9167cb5a6acb4b3ec5f02bec3eb4769e4ae Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Fri, 18 Sep 2020 23:53:42 +0000 Subject: [PATCH 106/963] 3.5.12 release (previous 3.5.11) + release notes updated by CI build 4800 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 8601f484e3..d155049a70 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.12 + - 2020-09-18 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.11...v3.5.12) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.12-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.12) + - Update Byte Buddy. [(#2050)](https://github.com/mockito/mockito/pull/2050) + #### 3.5.11 - 2020-09-17 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.10...v3.5.11) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.11-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.11) - Do not exclude synthetic constructors from instrumentation. Fixes #2040. [(#2046)](https://github.com/mockito/mockito/pull/2046) diff --git a/version.properties b/version.properties index f7a6424065..c152754918 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.12 +version=3.5.13 # Previous version used to generate release notes delta -previousVersion=3.5.11 +previousVersion=3.5.12 From 079e847891959a7a3cbb5a8390efa65eba583b7a Mon Sep 17 00:00:00 2001 From: Sinan Kozak Date: Thu, 24 Sep 2020 16:32:35 +0300 Subject: [PATCH 107/963] Use single version for strict dependency check in mockito-android (#2053) [ci maven-central-release] --- subprojects/android/android.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/android/android.gradle b/subprojects/android/android.gradle index bd5a6959a2..508cd7ed05 100644 --- a/subprojects/android/android.gradle +++ b/subprojects/android/android.gradle @@ -9,7 +9,7 @@ dependencies { compile libraries.bytebuddyandroid compile(libraries.objenesis2) { version { - strictly '[2.6, 3.0[' + strictly '2.6' } because( '\n' + From 0ddbcb689e43f6a01f549c5efdd75defb39ebc14 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Thu, 24 Sep 2020 13:39:13 +0000 Subject: [PATCH 108/963] 3.5.13 release (previous 3.5.12) + release notes updated by CI build 4808 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index d155049a70..0895152c85 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.13 + - 2020-09-24 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.12...v3.5.13) by [Sinan Kozak](https://github.com/kozaxinan) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.13-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.13) + - Use single version for strictly in mockito-android [(#2053)](https://github.com/mockito/mockito/pull/2053) + #### 3.5.12 - 2020-09-18 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.11...v3.5.12) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.12-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.12) - Update Byte Buddy. [(#2050)](https://github.com/mockito/mockito/pull/2050) diff --git a/version.properties b/version.properties index c152754918..1aedc49ec6 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.13 +version=3.5.14 # Previous version used to generate release notes delta -previousVersion=3.5.12 +previousVersion=3.5.13 From b16ec17cafdbf4fb968413c4992f044c1bb9526a Mon Sep 17 00:00:00 2001 From: shestee <53140474+shestee@users.noreply.github.com> Date: Fri, 16 Oct 2020 23:33:03 +0200 Subject: [PATCH 109/963] Fix typo in osgi.gradle (#2070) --- gradle/mockito-core/osgi.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle index a18942589d..cdee44287b 100644 --- a/gradle/mockito-core/osgi.gradle +++ b/gradle/mockito-core/osgi.gradle @@ -14,7 +14,7 @@ jar { bnd( 'Bundle-Name': 'Mockito Mock Library for Java. Core bundle requires Byte Buddy and Objenesis.', 'Bundle-SymbolicName': 'org.mockito.mockito-core', - 'Bundl-version': project.version.replace('-', '.'), + 'Bundle-version': project.version.replace('-', '.'), '-versionpolicy': '[${version;==;${@}},${version;+;${@}})', 'Export-Package': "!org.mockito.internal.*,org.mockito.*;version=${version}", 'Import-Package': [ From 214d66fa84af85026be9791456fccc06af2f6b61 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Sat, 17 Oct 2020 16:42:18 +0200 Subject: [PATCH 110/963] Fixes #2061: ArgumentMatcher error messages use lambda class names (#2071) --- .../matchers/text/MatcherToString.java | 15 ++++++-- .../org/mockito/internal/util/StringUtil.java | 2 +- .../matchers/text/MatcherToStringTest.java | 35 +++++++++++++++++++ .../mockito/internal/util/StringUtilTest.java | 13 +++---- 4 files changed, 56 insertions(+), 9 deletions(-) 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 3be972e7c5..937dc34f9e 100644 --- a/src/main/java/org/mockito/internal/matchers/text/MatcherToString.java +++ b/src/main/java/org/mockito/internal/matchers/text/MatcherToString.java @@ -5,7 +5,7 @@ package org.mockito.internal.matchers.text; import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod; -import static org.mockito.internal.util.StringUtil.decamelizeMatcher; +import static org.mockito.internal.util.StringUtil.decamelizeMatcherName; import java.lang.reflect.Method; @@ -37,6 +37,17 @@ static String toString(ArgumentMatcher matcher) { } cls = cls.getSuperclass(); } - return decamelizeMatcher(matcher.getClass().getSimpleName()); + + String matcherName; + Class matcherClass = matcher.getClass(); + // Lambdas have non-empty getSimpleName() (despite being synthetic) + // but that name is not useful for user + if (matcherClass.isSynthetic()) { + matcherName = ""; + } else { + matcherName = matcherClass.getSimpleName(); + } + + return decamelizeMatcherName(matcherName); } } diff --git a/src/main/java/org/mockito/internal/util/StringUtil.java b/src/main/java/org/mockito/internal/util/StringUtil.java index b58a36fce5..7e55666085 100644 --- a/src/main/java/org/mockito/internal/util/StringUtil.java +++ b/src/main/java/org/mockito/internal/util/StringUtil.java @@ -60,7 +60,7 @@ public static String join(String start, String linePrefix, Collection lines) return out.substring(0, out.length() - 1); // lose last EOL } - public static String decamelizeMatcher(String className) { + public static String decamelizeMatcherName(String className) { if (className.length() == 0) { return ""; } 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 d0d7869e8b..746ee69ea3 100644 --- a/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java +++ b/src/test/java/org/mockito/internal/matchers/text/MatcherToStringTest.java @@ -13,22 +13,26 @@ public class MatcherToStringTest extends TestBase { static class MatcherWithoutDescription implements ArgumentMatcher { + @Override public boolean matches(Object argument) { return false; } } static class MatcherWithDescription implements ArgumentMatcher { + @Override public boolean matches(Object argument) { return false; } + @Override public String toString() { return "*my custom description*"; } } static class MatcherWithInheritedDescription extends MatcherWithDescription { + @Override public boolean matches(Object argument) { return false; } @@ -45,4 +49,35 @@ public void better_toString_for_matchers() { "*my custom description*", MatcherToString.toString(new MatcherWithInheritedDescription())); } + + @Test + public void default_name_for_anonymous_matchers() { + ArgumentMatcher anonymousMatcher = + new ArgumentMatcher() { + @Override + public boolean matches(Object argument) { + return false; + } + }; + assertEquals("", MatcherToString.toString(anonymousMatcher)); + + ArgumentMatcher anonymousDescriptiveMatcher = + new MatcherWithDescription() { + @Override + public boolean matches(Object argument) { + return false; + } + }; + assertEquals( + "*my custom description*", MatcherToString.toString(anonymousDescriptiveMatcher)); + } + + @Test + public void default_name_for_synthetic_matchers() { + ArgumentMatcher lambdaMatcher = argument -> true; + assertEquals("", MatcherToString.toString(lambdaMatcher)); + + ArgumentMatcher methodRefMatcher = lambdaMatcher::matches; + assertEquals("", MatcherToString.toString(methodRefMatcher)); + } } diff --git a/src/test/java/org/mockito/internal/util/StringUtilTest.java b/src/test/java/org/mockito/internal/util/StringUtilTest.java index e9c40538bc..526d399264 100644 --- a/src/test/java/org/mockito/internal/util/StringUtilTest.java +++ b/src/test/java/org/mockito/internal/util/StringUtilTest.java @@ -15,15 +15,16 @@ public class StringUtilTest { @Test - public void decamelizes_matcher() throws Exception { + public void decamelizes_matcher_name() throws Exception { assertEquals( "", - StringUtil.decamelizeMatcher("SentenceWithStrongLanguage")); - assertEquals("", StringUtil.decamelizeMatcher("WEIRDO1")); - assertEquals("<_>", StringUtil.decamelizeMatcher("_")); + StringUtil.decamelizeMatcherName("SentenceWithStrongLanguage")); + assertEquals("", StringUtil.decamelizeMatcherName("WEIRDO1")); + assertEquals("<_>", StringUtil.decamelizeMatcherName("_")); assertEquals( - "", StringUtil.decamelizeMatcher("HasExactly3Elements")); - assertEquals("", StringUtil.decamelizeMatcher("")); + "", + StringUtil.decamelizeMatcherName("HasExactly3Elements")); + assertEquals("", StringUtil.decamelizeMatcherName("")); } @Test From e388e924ccc018934def0eb189a2926fca6063cb Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sat, 17 Oct 2020 14:48:44 +0000 Subject: [PATCH 111/963] 3.5.14 release (previous 3.5.13) + release notes updated by CI build 4814 [ci skip-release] --- doc/release-notes/official.md | 6 ++++++ version.properties | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 0895152c85..cf67541505 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,11 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.14 + - 2020-10-17 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.13...v3.5.14) by [Marcono1234](https://github.com/Marcono1234) (1), [shestee](https://github.com/shestee) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.14-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.14) + - Fixes #2061: ArgumentMatcher error messages use lambda class names [(#2071)](https://github.com/mockito/mockito/pull/2071) + - Fixed typo in osgi.gradle [(#2070)](https://github.com/mockito/mockito/pull/2070) + - Lambda used as ArgumentMatcher causes decamelized lambda name to appear in error message [(#2061)](https://github.com/mockito/mockito/issues/2061) + #### 3.5.13 - 2020-09-24 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.12...v3.5.13) by [Sinan Kozak](https://github.com/kozaxinan) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.13-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.13) - Use single version for strictly in mockito-android [(#2053)](https://github.com/mockito/mockito/pull/2053) diff --git a/version.properties b/version.properties index 1aedc49ec6..c63aaee313 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.14 +version=3.5.15 # Previous version used to generate release notes delta -previousVersion=3.5.13 +previousVersion=3.5.14 From 18da8f2a874bf0d366453d9391e78ef861a833a6 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Mon, 19 Oct 2020 13:55:21 +0000 Subject: [PATCH 112/963] 3.5.15 release (previous 3.5.14) + release notes updated by CI build 4819 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index cf67541505..f0b0d65cdb 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.5.15 + - 2020-10-19 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.14...v3.5.15) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.15-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.15) + - Mock resolver plugin [(#2042)](https://github.com/mockito/mockito/pull/2042) + #### 3.5.14 - 2020-10-17 - [2 commits](https://github.com/mockito/mockito/compare/v3.5.13...v3.5.14) by [Marcono1234](https://github.com/Marcono1234) (1), [shestee](https://github.com/shestee) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.14-green.svg)](https://bintray.com/mockito/maven/mockito-development/3.5.14) - Fixes #2061: ArgumentMatcher error messages use lambda class names [(#2071)](https://github.com/mockito/mockito/pull/2071) diff --git a/version.properties b/version.properties index c63aaee313..f5aa82d139 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.15 +version=3.5.16 # Previous version used to generate release notes delta -previousVersion=3.5.14 +previousVersion=3.5.15 From eba5964a4b051bf566aaf46ca749cde2b36d96ba Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Sat, 24 Oct 2020 23:25:04 +0100 Subject: [PATCH 113/963] Publish new minor version to Maven Central [ci maven-central-release] --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index f5aa82d139..c598debc69 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.5.16 +version=3.6.0 # Previous version used to generate release notes delta previousVersion=3.5.15 From 9fadca578aceaa01ab1d09c6bbd21aa144c154db Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Sat, 24 Oct 2020 22:31:29 +0000 Subject: [PATCH 114/963] 3.6.0 release (previous 3.5.15) + release notes updated by CI build 4828 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index f0b0d65cdb..76de0a20a8 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.6.0 + - 2020-10-24 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.15...v3.6.0) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.6.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.6.0) + - No pull requests referenced in commit messages. + #### 3.5.15 - 2020-10-19 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.14...v3.5.15) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.15-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.15) - Mock resolver plugin [(#2042)](https://github.com/mockito/mockito/pull/2042) diff --git a/version.properties b/version.properties index c598debc69..2cdfdc6bc9 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.6.0 +version=3.6.1 # Previous version used to generate release notes delta -previousVersion=3.5.15 +previousVersion=3.6.0 From 23a9d6a7e32d2023c67cdb024d7fa24749e2ce0f Mon Sep 17 00:00:00 2001 From: sfaber Date: Mon, 26 Oct 2020 10:13:41 -0500 Subject: [PATCH 115/963] Retry 3.6.0 release --- doc/release-notes/official.md | 4 ---- version.properties | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 76de0a20a8..f0b0d65cdb 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,9 +1,5 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* -#### 3.6.0 - - 2020-10-24 - [1 commit](https://github.com/mockito/mockito/compare/v3.5.15...v3.6.0) by [Tim van der Lippe](https://github.com/TimvdLippe) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.6.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.6.0) - - No pull requests referenced in commit messages. - #### 3.5.15 - 2020-10-19 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.14...v3.5.15) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.15-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.15) - Mock resolver plugin [(#2042)](https://github.com/mockito/mockito/pull/2042) diff --git a/version.properties b/version.properties index 2cdfdc6bc9..c598debc69 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.6.1 +version=3.6.0 # Previous version used to generate release notes delta -previousVersion=3.6.0 +previousVersion=3.5.15 From f22a47786ebb776b5453fc595fa4a79eb7ec0b0c Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Mon, 26 Oct 2020 20:49:55 +0000 Subject: [PATCH 116/963] 3.6.0 release (previous 3.5.15) + release notes updated by CI build 4832 [ci skip-release] --- doc/release-notes/official.md | 4 ++++ version.properties | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index f0b0d65cdb..1738f315e3 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,9 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.6.0 + - 2020-10-26 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.15...v3.6.0) by [Szczepan Faber](https://github.com/mockitoguy) (2), shipkit-org (1), [Tim van der Lippe](https://github.com/TimvdLippe) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.6.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.6.0) + - Retry 3.6.0 release [(#2077)](https://github.com/mockito/mockito/pull/2077) + #### 3.5.15 - 2020-10-19 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.14...v3.5.15) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.15-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.15) - Mock resolver plugin [(#2042)](https://github.com/mockito/mockito/pull/2042) diff --git a/version.properties b/version.properties index c598debc69..2cdfdc6bc9 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.6.0 +version=3.6.1 # Previous version used to generate release notes delta -previousVersion=3.5.15 +previousVersion=3.6.0 From 80c1d4ab1a5f2a0c7318b78d03a368c18085553b Mon Sep 17 00:00:00 2001 From: sfaber Date: Mon, 26 Oct 2020 17:24:29 -0500 Subject: [PATCH 117/963] Reverted to retry the release --- doc/release-notes/official.md | 4 ---- version.properties | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index 1738f315e3..f0b0d65cdb 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,9 +1,5 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* -#### 3.6.0 - - 2020-10-26 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.15...v3.6.0) by [Szczepan Faber](https://github.com/mockitoguy) (2), shipkit-org (1), [Tim van der Lippe](https://github.com/TimvdLippe) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.6.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.6.0) - - Retry 3.6.0 release [(#2077)](https://github.com/mockito/mockito/pull/2077) - #### 3.5.15 - 2020-10-19 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.14...v3.5.15) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.15-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.15) - Mock resolver plugin [(#2042)](https://github.com/mockito/mockito/pull/2042) diff --git a/version.properties b/version.properties index 2cdfdc6bc9..c598debc69 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.6.1 +version=3.6.0 # Previous version used to generate release notes delta -previousVersion=3.6.0 +previousVersion=3.5.15 From caac3535daaeb9370cd25f23694d3d059a72d8d9 Mon Sep 17 00:00:00 2001 From: shipkit-org Date: Tue, 27 Oct 2020 02:25:33 +0000 Subject: [PATCH 118/963] 3.6.0 release (previous 3.5.15) + release notes updated by CI build 4836 [ci skip-release] --- doc/release-notes/official.md | 5 +++++ version.properties | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md index f0b0d65cdb..d59675e852 100644 --- a/doc/release-notes/official.md +++ b/doc/release-notes/official.md @@ -1,5 +1,10 @@ *Release notes were automatically generated by [Shipkit](http://shipkit.org/)* +#### 3.6.0 + - 2020-10-27 - [7 commits](https://github.com/mockito/mockito/compare/v3.5.15...v3.6.0) by [Szczepan Faber](https://github.com/mockitoguy) (4), [shipkit-org](https://github.com/shipkit-org) (2), [Tim van der Lippe](https://github.com/TimvdLippe) (1) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.6.0-green.svg)](https://bintray.com/mockito/maven/mockito/3.6.0) + - Retry the release [(#2078)](https://github.com/mockito/mockito/pull/2078) + - Retry 3.6.0 release [(#2077)](https://github.com/mockito/mockito/pull/2077) + #### 3.5.15 - 2020-10-19 - [4 commits](https://github.com/mockito/mockito/compare/v3.5.14...v3.5.15) by [Rafael Winterhalter](https://github.com/raphw) - published to [![Bintray](https://img.shields.io/badge/Bintray-3.5.15-green.svg)](https://bintray.com/mockito/maven/mockito/3.5.15) - Mock resolver plugin [(#2042)](https://github.com/mockito/mockito/pull/2042) diff --git a/version.properties b/version.properties index c598debc69..2cdfdc6bc9 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,5 @@ # Currently building Mockito version -version=3.6.0 +version=3.6.1 # Previous version used to generate release notes delta -previousVersion=3.5.15 +previousVersion=3.6.0 From 7c512975310fbc54372b2cb16bfde9af39358e08 Mon Sep 17 00:00:00 2001 From: sfaber Date: Fri, 16 Oct 2020 15:45:02 -0500 Subject: [PATCH 119/963] Migration to future Shipkit Started migrating existing Shipkit configuration to the new model (small, decoupled, specialized Gradle plugins). --- build.gradle | 14 ++--- gradle/java-library.gradle | 4 +- gradle/java-publication.gradle | 91 +++++++++++++++++++++++++++ gradle/shipkit.gradle | 110 +++++++++++++++------------------ version.properties | 7 +-- 5 files changed, 149 insertions(+), 77 deletions(-) create mode 100644 gradle/java-publication.gradle diff --git a/build.gradle b/build.gradle index e30ddb1a5a..bfc5bfb226 100644 --- a/build.gradle +++ b/build.gradle @@ -9,8 +9,10 @@ buildscript { classpath 'gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.14.0' classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.2.1' - //Using buildscript.classpath so that we can resolve shipkit from maven local, during local testing - classpath 'org.shipkit:shipkit:2.1.6' + //Using buildscript.classpath so that we can resolve plugins from maven local, during local testing + classpath "org.shipkit:shipkit-auto-version:0.0.+" + classpath "org.shipkit:shipkit-changelog:0.0.+" + classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+" classpath 'com.google.googlejavaformat:google-java-format:1.8' } @@ -29,13 +31,7 @@ description = 'Mockito mock objects library core API and implementation' apply plugin: 'base' archivesBaseName = "mockito-core" -apply plugin: "org.shipkit.java" -allprojects { - plugins.withId("java") { - //Only upload specific modules we select - bintrayUpload.enabled = false - } -} +apply from: 'gradle/shipkit.gradle' apply from: 'gradle/root/ide.gradle' apply from: 'gradle/root/gradle-fix.gradle' diff --git a/gradle/java-library.gradle b/gradle/java-library.gradle index be214c6c24..7402eaeed9 100644 --- a/gradle/java-library.gradle +++ b/gradle/java-library.gradle @@ -6,6 +6,8 @@ if (!archivesBaseName.startsWith("mockito-")) { archivesBaseName = "mockito-" + project.name } +apply from: "$rootDir/gradle/java-publication.gradle" + generatePomFileForJavaLibraryPublication.doLast { //validates the the pom has correct artifact id to avoid issues like #1444 def pom = new XmlSlurper().parse(destination) @@ -13,8 +15,6 @@ generatePomFileForJavaLibraryPublication.doLast { assert pom.name == archivesBaseName } -bintrayUpload.enabled = true - sourceCompatibility = 1.8 targetCompatibility = 1.8 diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle new file mode 100644 index 0000000000..b35814fb21 --- /dev/null +++ b/gradle/java-publication.gradle @@ -0,0 +1,91 @@ +//Sources/javadoc artifacts required by Maven module publications +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource + include "LICENSE" +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from tasks.javadoc + include "LICENSE" +} + +artifacts { + archives sourcesJar + archives javadocJar +} + +//Gradle Maven publishing plugin configuration (https://docs.gradle.org/current/userguide/publishing_maven.html) +apply plugin: "maven-publish" +publishing { + publications { + javaLibrary(MavenPublication) { //name of the publication + from components.java + artifact sourcesJar + artifact javadocJar + + artifactId = project.archivesBaseName + + pom { + name = artifactId + description = "Most popular mocking framework for unit tests written in Java" + url = "https://github.com/mockito/mockito" + licenses { + license { + name = 'MIT' + url = 'https://github.com/mockito/mockito/blob/release/3.x/LICENSE' + } + } + developers { + ['mockitoguy:Szczepan Faber', 'bric3:Brice Dutheil', 'raphw:Rafael Winterhalter', + 'TimvdLippe:Tim van der Lippe'].each { devData -> + developer { + def devInfo = devData.split(':') + id = devInfo[0] + name = devInfo[1] + url = 'https://github.com/' + devInfo[0] + roles = ["Core developer"] + } + } + } + scm { + url = 'https://github.com/mockito/mockito.git' + } + } + } + } + + //useful for testing - running "publish" will create artifacts/pom in a local dir + repositories { maven { url = "$buildDir/repo" } } +} + +//fleshes out problems with Maven pom generation when building +tasks.build.dependsOn("publishJavaLibraryPublicationToMavenLocal"); + +//Bintray Gradle plugin configuration (https://github.com/bintray/gradle-bintray-plugin) +//Plugin jars are added to the buildscript classpath in the root build.gradle file +apply plugin: "com.jfrog.bintray" + +bintray { + user = 'szczepiq' + key = System.getenv('BINTRAY_API_KEY') + publish = true + dryRun = project.hasProperty("bintrayDryRun") + publications = ['javaLibrary'] + + pkg { + repo = 'examples' + userOrg = 'shipkit' + name = "shipkit-demo" + licenses = ['MIT'] + labels = ['continuous delivery', 'release automation', 'mockito', 'shipkit'] + vcsUrl = "https://github.com/shipkit/shipkit-demo.git" + + version { + name = project.version + vcsTag = "v$name" + attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin'] + } + } +} diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index aa4546cd0e..a9c35d117c 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -1,26 +1,19 @@ -shipkit { - gitHub.repository = "mockito/mockito" - gitHub.readOnlyAuthToken = "a0a4c0f41c200f7c653323014d6a72a127764e17" +apply plugin: "org.shipkit.shipkit-auto-version" +apply plugin: "org.shipkit.shipkit-changelog" +apply plugin: "org.shipkit.shipkit-gh-release" - releaseNotes.file = "doc/release-notes/official.md" - releaseNotes.labelMapping = [ - '1.* incompatible': 'Incompatible changes with previous major version (v1.x)', - 'java-9': "Java 9 support", - 'java-8': "Java 8 support", - 'new feature': "New features", - 'BDD': 'Behavior-Driven Development support', - 'bug': "Bugfixes", - 'enhancement': "Enhancements", - 'android': "Android support", - 'docs': 'Documentation' - ] - - git.releasableBranchRegex = "release/.+" // 'release/2.x', 'release/3.x', etc. - - def buildNo = System.getenv("TRAVIS_BUILD_NUMBER") - git.commitMessagePostfix = buildNo? "by CI build $buildNo\n\n[ci skip-release]" : "by local build\n\n[ci skip-release]" +tasks.named("generateChangelog") { + previousRevision = "v" + project.ext.'shipkit-auto-version.previous-version' + readOnlyToken = "a0a4c0f41c200f7c653323014d6a72a127764e17" + repository = "mockito/mockito" +} - team.developers = ['mockitoguy:Szczepan Faber', 'bric3:Brice Dutheil', 'raphw:Rafael Winterhalter', 'TimvdLippe:Tim van der Lippe'] +tasks.named("githubRelease") { + def genTask = tasks.named("generateChangelog").get() + dependsOn genTask + repository = genTask.repository + changelog = genTask.outputFile + writeToken = System.getenv("GH_WRITE_TOKEN") } /** @@ -30,44 +23,38 @@ shipkit { */ boolean centralRelease = shouldReleaseToCentral(project) -afterEvaluate { - //using afterEvaluate because 'assertReleaseNeeded' task is added after 'shipkit.gradle' file is evaluated by Gradle - [assertReleaseNeeded, releaseNeeded].each { - it.skipComparePublications = centralRelease - } -} - -allprojects { - plugins.withId("org.shipkit.bintray") { - bintray { - pkg { - repo = 'maven' //https://bintray.com/mockito/maven - //We need to use some user id here, because the Bintray key is associated with the user - //However, any user id is good, so longer the user has necessary privileges to the repository - user = 'szczepiq' //https://bintray.com/szczepiq - - userOrg = 'mockito' //https://bintray.com/mockito - name = 'mockito' //https://bintray.com/mockito/maven/mockito - licenses = ['MIT'] - labels = ['mocks', 'tdd', 'unit tests'] - publish = true //can be changed to 'false' for testing - - //See our Bintray packages at https://bintray.com/mockito/maven - name = centralRelease? "mockito" : "mockito-development" - - version { - //Notable versions are automatically synced to Maven Central repository (https://oss.sonatype.org/) - mavenCentralSync { - sync = centralRelease - user = System.env.NEXUS_TOKEN_USER - password = System.env.NEXUS_TOKEN_PWD - } - } - } - } - } -} +//allprojects { +// plugins.withId("org.shipkit.bintray") { +// bintray { +// pkg { +// repo = 'maven' //https://bintray.com/mockito/maven +// +// //We need to use some user id here, because the Bintray key is associated with the user +// //However, any user id is good, so longer the user has necessary privileges to the repository +// user = 'szczepiq' //https://bintray.com/szczepiq +// +// userOrg = 'mockito' //https://bintray.com/mockito +// name = 'mockito' //https://bintray.com/mockito/maven/mockito +// licenses = ['MIT'] +// labels = ['mocks', 'tdd', 'unit tests'] +// publish = true //can be changed to 'false' for testing +// +// //See our Bintray packages at https://bintray.com/mockito/maven +// name = centralRelease? "mockito" : "mockito-development" +// +// version { +// //Notable versions are automatically synced to Maven Central repository (https://oss.sonatype.org/) +// mavenCentralSync { +// sync = centralRelease +// user = System.env.NEXUS_TOKEN_USER +// password = System.env.NEXUS_TOKEN_PWD +// } +// } +// } +// } +// } +//} /** * Finds out if we should release to Maven Central. @@ -82,8 +69,9 @@ static boolean shouldReleaseToCentral(project) { - project property 'maven-central-release' exists: $centralReleaseByProjectProperty - Maven Central release is enabled: $centralRelease""" project.logger.info(message) - project.afterEvaluate { - project.tasks.performRelease.doLast { logger.lifecycle(message) } - } +//TODO? +// project.afterEvaluate { +// project.tasks.performRelease.doLast { logger.lifecycle(message) } +// } return centralRelease } diff --git a/version.properties b/version.properties index 2cdfdc6bc9..40f7f3fd14 100644 --- a/version.properties +++ b/version.properties @@ -1,5 +1,2 @@ -# Currently building Mockito version -version=3.6.1 - -# Previous version used to generate release notes delta -previousVersion=3.6.0 +//Used by Shipkit Auto Version Gradle plugin: https://github.com/shipkit/shipkit-auto-version +version=3.5.* From 0b2dfdcd441f3edc35d5ee2598dd0fde0161ae57 Mon Sep 17 00:00:00 2001 From: sfaber Date: Sat, 17 Oct 2020 14:28:08 -0500 Subject: [PATCH 120/963] Ensured that mockito-core pom file is equivalent. There is one deviation: Gradle's pom builder does not write the packaging 'jar' to the pom file. This is OK because it's Maven's default. --- gradle/java-publication.gradle | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index b35814fb21..a92b096ceb 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -29,12 +29,19 @@ publishing { pom { name = artifactId - description = "Most popular mocking framework for unit tests written in Java" + description = project.description + + //Gradle does not write 'jar' packaging to the pom (unlike other packaging types). + //This is OK because 'jar' is implicit/default: + // https://maven.apache.org/guides/introduction/introduction-to-the-pom.html#minimal-pom + packaging = project.tasks.jar.extension + url = "https://github.com/mockito/mockito" licenses { license { - name = 'MIT' + name = 'The MIT License' url = 'https://github.com/mockito/mockito/blob/release/3.x/LICENSE' + distribution = 'repo' } } developers { @@ -52,6 +59,14 @@ publishing { scm { url = 'https://github.com/mockito/mockito.git' } + issueManagement { + url = 'https://github.com/mockito/mockito/issues' + system = 'GitHub issues' + } + ciManagement { + url = 'https://travis-ci.org/mockito/mockito' + system = 'TravisCI' + } } } } From b79989415a5884d716f6708a237fdd7ecf156af3 Mon Sep 17 00:00:00 2001 From: sfaber Date: Sat, 17 Oct 2020 15:12:08 -0500 Subject: [PATCH 121/963] Fixed problem with license and empty artifacts --- gradle/java-publication.gradle | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index a92b096ceb..1e7697b6d0 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -1,14 +1,23 @@ //Sources/javadoc artifacts required by Maven module publications +def licenseSpec = copySpec { + from project.rootDir + include "LICENSE" +} + task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' from sourceSets.main.allSource - include "LICENSE" + with licenseSpec } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from tasks.javadoc - include "LICENSE" + with licenseSpec +} + +jar { + with licenseSpec } artifacts { From 278ed01f7c043d38560f7bdeebc3d010691fa264 Mon Sep 17 00:00:00 2001 From: sfaber Date: Sun, 18 Oct 2020 23:00:33 -0500 Subject: [PATCH 122/963] Enabled Bintray releases --- gradle/java-publication.gradle | 58 +++++++++++++++++++++++++------ gradle/shipkit.gradle | 62 +--------------------------------- 2 files changed, 49 insertions(+), 71 deletions(-) diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index 1e7697b6d0..eb2242888e 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -85,31 +85,69 @@ publishing { } //fleshes out problems with Maven pom generation when building -tasks.build.dependsOn("publishJavaLibraryPublicationToMavenLocal"); +tasks.build.dependsOn("publishJavaLibraryPublicationToMavenLocal") + +/** + * Mockito team does not publish to Maven Central every release as requested by the community. + * We publish to maven central only some versions. All versions are published to Bintray on every change. + * See https://github.com/mockito/mockito/issues/911 + */ +def centralRelease = shouldReleaseToCentral(project) + +/** + * Finds out if we should release to Maven Central. + * To test this logic, run build with '-i' (info logging) and inspect the build output. + */ +static boolean shouldReleaseToCentral(project) { + return false +// boolean centralReleaseByCommit = System.getenv("TRAVIS_COMMIT_MESSAGE")?.contains("[ci maven-central-release]") +// boolean centralReleaseByProjectProperty = project.hasProperty("maven-central-release") +// boolean centralRelease = centralReleaseByCommit || centralReleaseByProjectProperty +// def message = """Release was using following settings: +// - commit message contains '[ci maven-central-release]': $centralReleaseByCommit +// - project property 'maven-central-release' exists: $centralReleaseByProjectProperty +// - Maven Central release is enabled: $centralRelease""" +// project.logger.info(message) +// project.afterEvaluate { +// project.tasks.bintrayUpload.doLast { logger.lifecycle(message) } +// } +// return centralRelease +} //Bintray Gradle plugin configuration (https://github.com/bintray/gradle-bintray-plugin) //Plugin jars are added to the buildscript classpath in the root build.gradle file apply plugin: "com.jfrog.bintray" bintray { - user = 'szczepiq' + //We need to use some user id here, because the Bintray key is associated with the user + //However, any user id is good, so longer the user has necessary privileges to the repository + user = 'szczepiq' //https://bintray.com/szczepiq key = System.getenv('BINTRAY_API_KEY') - publish = true + publish = false //can be changed to 'false' for testing dryRun = project.hasProperty("bintrayDryRun") publications = ['javaLibrary'] pkg { - repo = 'examples' - userOrg = 'shipkit' - name = "shipkit-demo" + repo = 'maven' //https://bintray.com/mockito/maven + userOrg = 'mockito' //https://bintray.com/mockito + + //See our Bintray packages at https://bintray.com/mockito/maven + name = centralRelease? "mockito" : "mockito-development" + licenses = ['MIT'] - labels = ['continuous delivery', 'release automation', 'mockito', 'shipkit'] - vcsUrl = "https://github.com/shipkit/shipkit-demo.git" + labels = ['mocks', 'tdd', 'unit tests'] + vcsUrl = "https://github.com/mockito/mockito.git" version { name = project.version - vcsTag = "v$name" - attributes = ['gradle-plugin': 'com.use.less:com.use.less.gradle:gradle-useless-plugin'] + vcsTag = "v$project.version" + + //Notable versions are automatically synced to Maven Central repository (https://oss.sonatype.org/) + mavenCentralSync { + sync = centralRelease + user = System.env.NEXUS_TOKEN_USER + password = System.env.NEXUS_TOKEN_PWD + } } } } diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index a9c35d117c..4018878d6c 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -14,64 +14,4 @@ tasks.named("githubRelease") { repository = genTask.repository changelog = genTask.outputFile writeToken = System.getenv("GH_WRITE_TOKEN") -} - -/** - * Mockito team does not publish to Maven Central every release as requested by the community. - * We publish to maven central only some versions. All versions are published to Bintray on every change. - * See https://github.com/mockito/mockito/issues/911 - */ -boolean centralRelease = shouldReleaseToCentral(project) - - -//allprojects { -// plugins.withId("org.shipkit.bintray") { -// bintray { -// pkg { -// repo = 'maven' //https://bintray.com/mockito/maven -// -// //We need to use some user id here, because the Bintray key is associated with the user -// //However, any user id is good, so longer the user has necessary privileges to the repository -// user = 'szczepiq' //https://bintray.com/szczepiq -// -// userOrg = 'mockito' //https://bintray.com/mockito -// name = 'mockito' //https://bintray.com/mockito/maven/mockito -// licenses = ['MIT'] -// labels = ['mocks', 'tdd', 'unit tests'] -// publish = true //can be changed to 'false' for testing -// -// //See our Bintray packages at https://bintray.com/mockito/maven -// name = centralRelease? "mockito" : "mockito-development" -// -// version { -// //Notable versions are automatically synced to Maven Central repository (https://oss.sonatype.org/) -// mavenCentralSync { -// sync = centralRelease -// user = System.env.NEXUS_TOKEN_USER -// password = System.env.NEXUS_TOKEN_PWD -// } -// } -// } -// } -// } -//} - -/** - * Finds out if we should release to Maven Central. - * To test this logic, run build with '-i' (info logging) and inspect the build output. - */ -static boolean shouldReleaseToCentral(project) { - boolean centralReleaseByCommit = System.getenv("TRAVIS_COMMIT_MESSAGE")?.contains("[ci maven-central-release]") - boolean centralReleaseByProjectProperty = project.hasProperty("maven-central-release") - boolean centralRelease = centralReleaseByCommit || centralReleaseByProjectProperty - def message = """Release was using following settings: - - commit message contains '[ci maven-central-release]': $centralReleaseByCommit - - project property 'maven-central-release' exists: $centralReleaseByProjectProperty - - Maven Central release is enabled: $centralRelease""" - project.logger.info(message) -//TODO? -// project.afterEvaluate { -// project.tasks.performRelease.doLast { logger.lifecycle(message) } -// } - return centralRelease -} +} \ No newline at end of file From 5d1e2a47a2c275d13338a5ed30e9e4ae349940fd Mon Sep 17 00:00:00 2001 From: sfaber Date: Mon, 19 Oct 2020 20:56:11 -0500 Subject: [PATCH 123/963] Fixed Maven Central publications --- gradle/java-publication.gradle | 31 ++----------------------------- gradle/shipkit.gradle | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 29 deletions(-) diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index eb2242888e..3eabe09e4c 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -87,33 +87,6 @@ publishing { //fleshes out problems with Maven pom generation when building tasks.build.dependsOn("publishJavaLibraryPublicationToMavenLocal") -/** - * Mockito team does not publish to Maven Central every release as requested by the community. - * We publish to maven central only some versions. All versions are published to Bintray on every change. - * See https://github.com/mockito/mockito/issues/911 - */ -def centralRelease = shouldReleaseToCentral(project) - -/** - * Finds out if we should release to Maven Central. - * To test this logic, run build with '-i' (info logging) and inspect the build output. - */ -static boolean shouldReleaseToCentral(project) { - return false -// boolean centralReleaseByCommit = System.getenv("TRAVIS_COMMIT_MESSAGE")?.contains("[ci maven-central-release]") -// boolean centralReleaseByProjectProperty = project.hasProperty("maven-central-release") -// boolean centralRelease = centralReleaseByCommit || centralReleaseByProjectProperty -// def message = """Release was using following settings: -// - commit message contains '[ci maven-central-release]': $centralReleaseByCommit -// - project property 'maven-central-release' exists: $centralReleaseByProjectProperty -// - Maven Central release is enabled: $centralRelease""" -// project.logger.info(message) -// project.afterEvaluate { -// project.tasks.bintrayUpload.doLast { logger.lifecycle(message) } -// } -// return centralRelease -} - //Bintray Gradle plugin configuration (https://github.com/bintray/gradle-bintray-plugin) //Plugin jars are added to the buildscript classpath in the root build.gradle file apply plugin: "com.jfrog.bintray" @@ -132,7 +105,7 @@ bintray { userOrg = 'mockito' //https://bintray.com/mockito //See our Bintray packages at https://bintray.com/mockito/maven - name = centralRelease? "mockito" : "mockito-development" + name = project.rootProject.ext.mavenCentralRelease? "mockito" : "mockito-development" licenses = ['MIT'] labels = ['mocks', 'tdd', 'unit tests'] @@ -144,7 +117,7 @@ bintray { //Notable versions are automatically synced to Maven Central repository (https://oss.sonatype.org/) mavenCentralSync { - sync = centralRelease + sync = project.rootProject.ext.mavenCentralRelease user = System.env.NEXUS_TOKEN_USER password = System.env.NEXUS_TOKEN_PWD } diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index 4018878d6c..1dd2f1cc23 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -14,4 +14,30 @@ tasks.named("githubRelease") { repository = genTask.repository changelog = genTask.outputFile writeToken = System.getenv("GH_WRITE_TOKEN") +} + +/** + * Mockito team does not publish to Maven Central every release as requested by the community. + * We publish to maven central only some versions. All versions are published to Bintray on every change. + * See https://github.com/mockito/mockito/issues/911 + */ +ext.mavenCentralRelease = shouldReleaseToCentral(project) + +/** + * Finds out if we should release to Maven Central. + * To test this logic, run build with '-i' (info logging) and inspect the build output. + */ +static boolean shouldReleaseToCentral(project) { + boolean centralReleaseByCommit = System.getenv("TRAVIS_COMMIT_MESSAGE")?.contains("[ci maven-central-release]") + boolean centralReleaseByProjectProperty = project.hasProperty("maven-central-release") + boolean centralRelease = centralReleaseByCommit || centralReleaseByProjectProperty + def message = """Bintray publish was using following settings: + - commit message contains '[ci maven-central-release]': $centralReleaseByCommit + - project property 'maven-central-release' exists: $centralReleaseByProjectProperty + - Maven Central release is enabled: $centralRelease""" + project.logger.info(message) + project.afterEvaluate { + project.tasks.bintrayPublish.doLast { logger.lifecycle(message) } + } + return centralRelease } \ No newline at end of file From 616f5eb982a34e95a10e43e39db0d24443b5a889 Mon Sep 17 00:00:00 2001 From: sfaber Date: Wed, 21 Oct 2020 21:29:44 -0500 Subject: [PATCH 124/963] Fixed Travis configuration --- .travis.yml | 10 ++++++---- gradle/java-publication.gradle | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index f8d4486d73..eb70ada874 100644 --- a/.travis.yml +++ b/.travis.yml @@ -52,10 +52,12 @@ install: - true script: - # We are using && below on purpose - # ciPerformRelease must run only when the entire build has completed - # This guarantees that no release steps are executed when the build or tests fail - - ./gradlew build idea -s && ./gradlew ciPerformRelease + # To validate changes, we run building and bintray upload in dry run, and idea task. This happens on every build, even PRs. + # To publish, we perform github release and perform bintray upload (no dry run). This only for main branch builds. + - > + ./gradlew build bintrayUpload idea --scan -PbintrayDryRun + && if [ -z "$SKIP_RELEASE" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ] && [ "$TRAVIS_BRANCH" = "release/3.x" ]; + then ./gradlew githubRelease bintrayUpload --scan; fi after_success: #Generates coverage report: diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index 3eabe09e4c..287a30a77a 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -96,7 +96,7 @@ bintray { //However, any user id is good, so longer the user has necessary privileges to the repository user = 'szczepiq' //https://bintray.com/szczepiq key = System.getenv('BINTRAY_API_KEY') - publish = false //can be changed to 'false' for testing + publish = true //can be changed to 'false' for testing dryRun = project.hasProperty("bintrayDryRun") publications = ['javaLibrary'] From 31957a91ae4ba1ff48943b5a8b35e9af85ab7d0e Mon Sep 17 00:00:00 2001 From: sfaber Date: Wed, 28 Oct 2020 09:45:38 -0500 Subject: [PATCH 125/963] Reordered the release steps Based the past experience let's try the approach to perform "bintrayUpload" *before* tagging the release in GitHub. Originally we thought that tagging *before* artifact publishing is a good idea. Bad tag is easier to revert than reverting binary artifacts publish. In fact, we cannot unpublish artifacts from some repositories, such as Maven Central. In practice though, tagging almost never fails. Therefore, let's run the task that *may* fail before tagging. This way, in case of a failure, there is less manual fixing (removing tags/release notes from GH) and less confusion to our end users (no more releases on GH that don't have any artifacts). --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index eb70ada874..00043d5d1b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -57,7 +57,7 @@ script: - > ./gradlew build bintrayUpload idea --scan -PbintrayDryRun && if [ -z "$SKIP_RELEASE" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ] && [ "$TRAVIS_BRANCH" = "release/3.x" ]; - then ./gradlew githubRelease bintrayUpload --scan; fi + then ./gradlew bintrayUpload githubRelease --scan; fi after_success: #Generates coverage report: From c1a7956a9fb3685ad3d59ffe5d41b55dbb6025e9 Mon Sep 17 00:00:00 2001 From: sfaber Date: Wed, 28 Oct 2020 13:45:09 -0500 Subject: [PATCH 126/963] Fixed the version number --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index 40f7f3fd14..08fdb9c84c 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ //Used by Shipkit Auto Version Gradle plugin: https://github.com/shipkit/shipkit-auto-version -version=3.5.* +version=3.6.* From 5570aba3efde807d2c9af4fc8cdc0a1e004a8469 Mon Sep 17 00:00:00 2001 From: Joe Shannon <35498448+joeshannon@users.noreply.github.com> Date: Wed, 28 Oct 2020 21:46:00 +0000 Subject: [PATCH 127/963] Fixes #2083 : Modify casing of Bundle-Version manifest header (#2084) OSGi specification may accept case insensitive headers but this is causing problems for Eclipse PDE development with version constraints. Switch to match casing of other headers and agree with name provided at: https://www.osgi.org/bundle-headers-reference/ --- gradle/mockito-core/osgi.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle index cdee44287b..f44ea9c18b 100644 --- a/gradle/mockito-core/osgi.gradle +++ b/gradle/mockito-core/osgi.gradle @@ -14,7 +14,7 @@ jar { bnd( 'Bundle-Name': 'Mockito Mock Library for Java. Core bundle requires Byte Buddy and Objenesis.', 'Bundle-SymbolicName': 'org.mockito.mockito-core', - 'Bundle-version': project.version.replace('-', '.'), + 'Bundle-Version': project.version.replace('-', '.'), '-versionpolicy': '[${version;==;${@}},${version;+;${@}})', 'Export-Package': "!org.mockito.internal.*,org.mockito.*;version=${version}", 'Import-Package': [ From ada3bf275408281819a23adff60108405229bc2f Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 30 Oct 2020 14:00:29 -0500 Subject: [PATCH 128/963] Experimental CI build via GH action [WIP] Experimental CI build via GH action [skip travis] --- .github/workflows/ci.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..a70be188e2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +# Experimental/WIP CI build (attempting to migrate from Travis CI) +name: WIP CI build + +on: + push: + branches: [ release/3.x ] + pull_request: + branches: [ release/3.x ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Build + run: ./gradlew build From f44957f68fda14b2cd489b54debdc6d00a9b9751 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 30 Oct 2020 14:05:29 -0500 Subject: [PATCH 129/963] Update ci.yml [skip travis] --- .github/workflows/ci.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a70be188e2..882d07371e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,10 +13,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v2 # https://github.com/actions/checkout + with: + fetch-depth: 100 # just enough to get recent tags and commits - name: Set up JDK 1.8 uses: actions/setup-java@v1 with: java-version: 1.8 - name: Build - run: ./gradlew build + run: ./gradlew build -x animalSnifferMain From 5f37b5a7123471fd6a24774474b5e54c49489b14 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 30 Oct 2020 14:13:36 -0500 Subject: [PATCH 130/963] Basic build matrix [skip travis] --- .github/workflows/ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 882d07371e..e50c9731df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,9 @@ jobs: build: runs-on: ubuntu-latest + strategy: + matrix: + java: [8, 11, 14] steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout @@ -19,6 +22,6 @@ jobs: - name: Set up JDK 1.8 uses: actions/setup-java@v1 with: - java-version: 1.8 + java-version: ${{ matrix.java }} - name: Build run: ./gradlew build -x animalSnifferMain From 7f4cefb1518f60269a34c3deee5611d71f202683 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 30 Oct 2020 14:19:56 -0500 Subject: [PATCH 131/963] Updated matrix [travis skip] --- .github/workflows/ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e50c9731df..908e288902 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,7 @@ jobs: strategy: matrix: java: [8, 11, 14] + mock-maker: ['mock-maker-default', 'mock-maker-inline'] steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout @@ -23,5 +24,7 @@ jobs: uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - - name: Build + - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} run: ./gradlew build -x animalSnifferMain + env: + MOCK_MAKER: ${{ matrix.mock-maker }} From baab674d8a8aa895fbcbef3344a4adc8a2e9b258 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 30 Oct 2020 14:56:17 -0500 Subject: [PATCH 132/963] Added release step Added release step that is disabled for now [skip travis] --- .github/workflows/ci.yml | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 908e288902..1a2a0c5980 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,23 +4,22 @@ name: WIP CI build on: push: branches: [ release/3.x ] + tags-ignore: [v*] pull_request: branches: [ release/3.x ] jobs: build: - runs-on: ubuntu-latest strategy: matrix: java: [8, 11, 14] mock-maker: ['mock-maker-default', 'mock-maker-inline'] - - steps: + steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: fetch-depth: 100 # just enough to get recent tags and commits - - name: Set up JDK 1.8 + - name: Set up Java ${{ matrix.java }} uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} @@ -28,3 +27,18 @@ jobs: run: ./gradlew build -x animalSnifferMain env: MOCK_MAKER: ${{ matrix.mock-maker }} + release: + runs-on: ubuntu-latest + needs: [build] + if: success() && github.event_name == 'push' && github.ref == 'release/3.x' + steps: + - uses: actions/checkout@v2 # https://github.com/actions/checkout + with: + fetch-depth: 100 # just enough to get recent tags and commits + - name: Set up Java 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Build and publish + run: ./gradlew bintrayUpload githubRelease --scan -x animalSnifferMain -m + From a0ee1427e3899a453aae3e802f39d85d5e102054 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 31 Oct 2020 11:21:07 -0500 Subject: [PATCH 133/963] Enabled coverage reporting in CI Also reduced the build matrix for faster testing. [skip travis] --- .github/workflows/ci.yml | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a2a0c5980..12c60d49e2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,8 +13,8 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - java: [8, 11, 14] - mock-maker: ['mock-maker-default', 'mock-maker-inline'] + java: [8, 11] # TODO: [8, 11, 14] + mock-maker: ['mock-maker-default'] # TODO: ['mock-maker-default', 'mock-maker-inline'] steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: @@ -24,9 +24,14 @@ jobs: with: java-version: ${{ matrix.java }} - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} - run: ./gradlew build -x animalSnifferMain + run: ./gradlew build -x animalSnifferMain --scan # TODO: animalSniffer env: MOCK_MAKER: ${{ matrix.mock-maker }} + - name: Upload coverage report + if: matrix.java == 8 && matrix.mock-maker = 'mock-maker-default' + run: | + ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" + bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" release: runs-on: ubuntu-latest needs: [build] @@ -40,5 +45,4 @@ jobs: with: java-version: 8 - name: Build and publish - run: ./gradlew bintrayUpload githubRelease --scan -x animalSnifferMain -m - + run: ./gradlew bintrayUpload githubRelease --scan -m From 79cda5735c9834d367d0a256896d99808e1e0b76 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 31 Oct 2020 11:25:39 -0500 Subject: [PATCH 134/963] Fixed bug in GH action workflow file [skip travis] --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12c60d49e2..26d8e92356 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: env: MOCK_MAKER: ${{ matrix.mock-maker }} - name: Upload coverage report - if: matrix.java == 8 && matrix.mock-maker = 'mock-maker-default' + if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' run: | ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" From 9d6b5b29b5148fefeadf4ea6451e24d42bf10655 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 31 Oct 2020 11:38:08 -0500 Subject: [PATCH 135/963] Fixed bug in workflow file Ensured that the release step is executed. [travis skip] --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 26d8e92356..58c85ec7ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,7 +35,7 @@ jobs: release: runs-on: ubuntu-latest needs: [build] - if: success() && github.event_name == 'push' && github.ref == 'release/3.x' + if: github.event_name == 'push' && github.ref == 'release/3.x' steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: From f70b1e214c524df146e1e20d6ae69e015b3d9a34 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 31 Oct 2020 11:50:48 -0500 Subject: [PATCH 136/963] Fixed bug in workflow file [travis skip] --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58c85ec7ac..b8765720e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,7 +35,7 @@ jobs: release: runs-on: ubuntu-latest needs: [build] - if: github.event_name == 'push' && github.ref == 'release/3.x' + if: github.event_name == 'push' && github.ref == 'refs/heads/release/3.x' steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: From 4fa9dd41f4e8dc920a4a2c3043e8a104bc1894ed Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 31 Oct 2020 12:00:39 -0500 Subject: [PATCH 137/963] Faster testing of the workflow file Started running the main build in dry-run mode so that we have faster turnaround on testing the CI. [skip travis] --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b8765720e7..efcfeda7e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,7 @@ jobs: with: java-version: ${{ matrix.java }} - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} - run: ./gradlew build -x animalSnifferMain --scan # TODO: animalSniffer + run: ./gradlew build -m --scan # TODO: remove -m env: MOCK_MAKER: ${{ matrix.mock-maker }} - name: Upload coverage report From 4d44781331fd57dda6c31cf1d70151ad04883e2a Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Tue, 3 Nov 2020 10:09:01 -0600 Subject: [PATCH 138/963] Ported more features to GH Action - Made the coverage report work for every job (based on the discussion with @TimvdLippe). Codecov merges all reports from a single CI invocation, giving us a more accurate coverage value. - Added spotless invocation as a part of a single job (there is no point running spotless step for every job in the matrix - it will have the same results each time) [skip travis] --- .github/workflows/ci.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index efcfeda7e3..f7674adcc4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,12 +23,15 @@ jobs: uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} + - name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." + #We want to run spotless check only in a single job + if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' + run: ./gradlew spotlessCheck - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} run: ./gradlew build -m --scan # TODO: remove -m env: MOCK_MAKER: ${{ matrix.mock-maker }} - name: Upload coverage report - if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' run: | ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" From 252d99dc6628a0166a18476ddefcdda80909d2b0 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Thu, 5 Nov 2020 13:20:25 +0100 Subject: [PATCH 139/963] Update animal-sniffer plugin (#2088) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index bfc5bfb226..ed9ae5b450 100644 --- a/build.gradle +++ b/build.gradle @@ -23,7 +23,7 @@ plugins { id 'eclipse' id 'com.github.ben-manes.versions' version '0.28.0' id 'biz.aQute.bnd.builder' version '5.1.0' - id 'ru.vyarus.animalsniffer' version '1.5.1' + id 'ru.vyarus.animalsniffer' version '1.5.2' } description = 'Mockito mock objects library core API and implementation' From b49879e845b35e06a985fe0e4c75187e018f52d6 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 6 Nov 2020 21:18:46 -0600 Subject: [PATCH 140/963] Added reproducibility check Tidy up in the code comments [skip travis] --- .github/workflows/ci.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7674adcc4..e0c4da2f0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,8 +23,12 @@ jobs: uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} + - name: "Check reproducibility of artifacts" + # Run on a single job, with the version of java used for releases + if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' + run: ./check_reproducibility.sh - name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." - #We want to run spotless check only in a single job + # Run on a single job, with java version compatible with spotless if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' run: ./gradlew spotlessCheck - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} From 561cd05a80860f0023ba56e3215c14d942ea52fb Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 6 Nov 2020 21:23:18 -0600 Subject: [PATCH 141/963] Made checkout more reliable Added more commits to the fetch depth to ensure that we're getting all tags needed to auto-deduct version. 1000 is for my sanity and it shouldn't slow down the checkout (I'll verify). [skip travis] --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e0c4da2f0e..32d1b14f34 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: 100 # just enough to get recent tags and commits + fetch-depth: 1000 # just enough to get recent tags and commits - name: Set up Java ${{ matrix.java }} uses: actions/setup-java@v1 with: @@ -46,7 +46,7 @@ jobs: steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: 100 # just enough to get recent tags and commits + fetch-depth: 1000 # just enough to get recent tags and commits - name: Set up Java 8 uses: actions/setup-java@v1 with: From 8ab28f38c8204595c172f4f87afb5ec5575ee3c9 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 6 Nov 2020 21:31:33 -0600 Subject: [PATCH 142/963] Fixed checkout bug Further testing exposed a problem: to get all tags, I need fetch-depth '0' (all history and tags). We'll evaluate the performance implication [skip travis] --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 32d1b14f34..b1701f80c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: 1000 # just enough to get recent tags and commits + fetch-depth: '0' # all tags (version deduction) and commits (changelog generation) - name: Set up Java ${{ matrix.java }} uses: actions/setup-java@v1 with: @@ -46,7 +46,7 @@ jobs: steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: 1000 # just enough to get recent tags and commits + fetch-depth: '0' # all tags (version deduction) and commits (changelog generation) - name: Set up Java 8 uses: actions/setup-java@v1 with: From 888da322b7e61d567d838b2f28ff20c75f13ffed Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 7 Nov 2020 12:16:00 -0600 Subject: [PATCH 143/963] Added releasability [skip travis] --- .github/workflows/ci.yml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1701f80c2..14783987f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,12 +13,12 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - java: [8, 11] # TODO: [8, 11, 14] + java: [8] # TODO: [8, 11, 14] mock-maker: ['mock-maker-default'] # TODO: ['mock-maker-default', 'mock-maker-inline'] steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: '0' # all tags (version deduction) and commits (changelog generation) + fetch-depth: '0' # # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci - name: Set up Java ${{ matrix.java }} uses: actions/setup-java@v1 with: @@ -32,7 +32,7 @@ jobs: if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' run: ./gradlew spotlessCheck - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} - run: ./gradlew build -m --scan # TODO: remove -m + run: ./gradlew build bintrayUpload idea --scan -PbintrayDryRun -m # TODO: remove -m env: MOCK_MAKER: ${{ matrix.mock-maker }} - name: Upload coverage report @@ -46,10 +46,13 @@ jobs: steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: '0' # all tags (version deduction) and commits (changelog generation) + fetch-depth: '0' # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci - name: Set up Java 8 uses: actions/setup-java@v1 with: java-version: 8 - name: Build and publish - run: ./gradlew bintrayUpload githubRelease --scan -m + run: ./gradlew bintrayUpload githubRelease --scan -PbintrayDryRun # TODO remove -PbintrayDryRun + env: + GH_WRITE_TOKEN: ${{secrets.GH_WRITE_TOKEN}} + BINTRAY_API_KEY: ${{secrets.BINTRAY_API_KEY}} From 723eff61af01138cd9fcfdcc3ddacb7847b25d00 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sat, 7 Nov 2020 12:26:02 -0600 Subject: [PATCH 144/963] Update ci.yml Ignored the release step for now, after a successful smoke test [skip travis] --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14783987f5..58a2e95aff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: with: java-version: 8 - name: Build and publish - run: ./gradlew bintrayUpload githubRelease --scan -PbintrayDryRun # TODO remove -PbintrayDryRun + run: ./gradlew bintrayUpload githubRelease --scan -m # TODO remove -m env: GH_WRITE_TOKEN: ${{secrets.GH_WRITE_TOKEN}} BINTRAY_API_KEY: ${{secrets.BINTRAY_API_KEY}} From 95bc0387d65c59ce5753702f9aa89e35d618fcc5 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sun, 8 Nov 2020 10:29:18 -0600 Subject: [PATCH 145/963] Enabled full build with GH Actions Enabled the full build. For now, releasing is disabled. [skip travis] --- .github/workflows/ci.yml | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58a2e95aff..f8629dc4db 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,39 +9,57 @@ on: branches: [ release/3.x ] jobs: + + # + # Main build job + # build: runs-on: ubuntu-latest + + # Definition of the build matrix strategy: matrix: - java: [8] # TODO: [8, 11, 14] - mock-maker: ['mock-maker-default'] # TODO: ['mock-maker-default', 'mock-maker-inline'] - steps: - - uses: actions/checkout@v2 # https://github.com/actions/checkout + java: [8, 11, 14] + mock-maker: ['mock-maker-default', 'mock-maker-inline'] + + # Build steps + steps: + - name: 1. Check out code + uses: actions/checkout@v2 # https://github.com/actions/checkout with: fetch-depth: '0' # # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci - - name: Set up Java ${{ matrix.java }} + + - name: 2. Set up Java ${{ matrix.java }} uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - - name: "Check reproducibility of artifacts" + + - name: 3. Build and check reproducibility of artifacts (single job only) # Run on a single job, with the version of java used for releases if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' run: ./check_reproducibility.sh - - name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." + + - name: 4. Spotless check (single job only). Run './gradlew spotlessApply' locally if this job fails. # Run on a single job, with java version compatible with spotless if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' run: ./gradlew spotlessCheck - - name: Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} - run: ./gradlew build bintrayUpload idea --scan -PbintrayDryRun -m # TODO: remove -m + + - name: 5. Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} + run: ./gradlew build bintrayUpload idea --scan -PbintrayDryRun env: MOCK_MAKER: ${{ matrix.mock-maker }} - - name: Upload coverage report + + - name: 6. Upload coverage report run: | ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" + + # + # Release job, only for pushes to the main branch + # release: runs-on: ubuntu-latest - needs: [build] + needs: [build] # build job must pass before we can release if: github.event_name == 'push' && github.ref == 'refs/heads/release/3.x' steps: - uses: actions/checkout@v2 # https://github.com/actions/checkout From 5014d086ab0190989a2180abb8a3e11f3f3883d0 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Sun, 8 Nov 2020 10:54:26 -0600 Subject: [PATCH 146/963] Enabled CI on GH Actions Renamed the workflow. Now it works and it is no longer "work in progress" [skip travis] --- .github/workflows/ci.yml | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8629dc4db..b1692bc716 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,4 @@ -# Experimental/WIP CI build (attempting to migrate from Travis CI) -name: WIP CI build +name: CI on: push: @@ -22,38 +21,41 @@ jobs: java: [8, 11, 14] mock-maker: ['mock-maker-default', 'mock-maker-inline'] - # Build steps + # All build steps steps: + - name: 1. Check out code uses: actions/checkout@v2 # https://github.com/actions/checkout with: - fetch-depth: '0' # # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci - + fetch-depth: '0' # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci + - name: 2. Set up Java ${{ matrix.java }} uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - + + # TODO: add step for gradle wrapper validation and remove the other workflow + - name: 3. Build and check reproducibility of artifacts (single job only) # Run on a single job, with the version of java used for releases if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' run: ./check_reproducibility.sh - + - name: 4. Spotless check (single job only). Run './gradlew spotlessApply' locally if this job fails. # Run on a single job, with java version compatible with spotless if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' run: ./gradlew spotlessCheck - + - name: 5. Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} run: ./gradlew build bintrayUpload idea --scan -PbintrayDryRun env: MOCK_MAKER: ${{ matrix.mock-maker }} - + - name: 6. Upload coverage report run: | ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" - + # # Release job, only for pushes to the main branch # @@ -62,13 +64,16 @@ jobs: needs: [build] # build job must pass before we can release if: github.event_name == 'push' && github.ref == 'refs/heads/release/3.x' steps: - - uses: actions/checkout@v2 # https://github.com/actions/checkout + - name: Check out code + uses: actions/checkout@v2 # https://github.com/actions/checkout with: fetch-depth: '0' # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci + - name: Set up Java 8 uses: actions/setup-java@v1 with: java-version: 8 + - name: Build and publish run: ./gradlew bintrayUpload githubRelease --scan -m # TODO remove -m env: From 63cbc1099d575908f2f0f03cc9588594b8bdf909 Mon Sep 17 00:00:00 2001 From: sfaber Date: Sun, 8 Nov 2020 10:59:33 -0600 Subject: [PATCH 147/963] Switched CI to GH Actions [skip travis] --- .travis.yml | 65 ---------------------------------- README.md | 4 +-- build.gradle | 2 +- gradle/java-publication.gradle | 4 +-- 4 files changed, 5 insertions(+), 70 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 00043d5d1b..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,65 +0,0 @@ -# More details on how to configure the Travis build -# https://docs.travis-ci.com/user/customizing-the-build/ - -# Speed up build by leveraging travis caches -cache: - directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ - -# Enabling container based infrastructure hoping it will help the build speed <= this didn't work well, so it's reverted -# see https://docs.travis-ci.com/user/migrating-from-legacy/ and https://docs.travis-ci.com/user/ci-environment -sudo: true - -language: java - -dist: trusty - -matrix: - include: - - jdk: openjdk8 - - jdk: openjdk8 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk11 - env: SKIP_RELEASE=true - - jdk: openjdk11 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk14 - env: SKIP_RELEASE=true - - jdk: openjdk14 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) - - jdk: openjdk11 - name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." - script: ./gradlew spotlessCheck - # Do not upload a coverage report, as we don't run the tests for this job - after_success: true - - jdk: openjdk8 - name: "Check reproducibility of jars" - script: ./check_reproducibility.sh - # Do not upload a coverage report, as we don't run the tests for this job - after_success: true - -branches: - #Don't build tags - except: - - /^v\d/ - -#Below skips the installation step completely (https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step) -#We need it because otherwise Travis CI injects an awkward './gradlew assemble' step into the CI workflow -#We want to control and decide what Gradle tasks are executed -install: - - true - -script: - # To validate changes, we run building and bintray upload in dry run, and idea task. This happens on every build, even PRs. - # To publish, we perform github release and perform bintray upload (no dry run). This only for main branch builds. - - > - ./gradlew build bintrayUpload idea --scan -PbintrayDryRun - && if [ -z "$SKIP_RELEASE" ] && [ "$TRAVIS_PULL_REQUEST" = "false" ] && [ "$TRAVIS_BRANCH" = "release/3.x" ]; - then ./gradlew bintrayUpload githubRelease --scan; fi - -after_success: - #Generates coverage report: - - ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" - - bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" diff --git a/README.md b/README.md index 12b36459aa..6774bc92bd 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Most popular mocking framework for Java -[![Build Status](https://travis-ci.org/mockito/mockito.svg?branch=release/3.x)](https://travis-ci.org/mockito/mockito) +[![CI](https://github.com/mockito/mockito/workflows/CI/badge.svg)](https://github.com/mockito/mockito/actions?query=workflow%3ACI) [![Coverage Status](https://img.shields.io/codecov/c/github/mockito/mockito.svg)](https://codecov.io/github/mockito/mockito) [![MIT License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/mockito/mockito/blob/release/3.x/LICENSE) @@ -64,7 +64,7 @@ Then, _open_ the generated *.ipr file in IDEA. ## How to release new version? Mockito [implements Continuous Delivery model](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview). -Every change on main branch (for example merging a pull request) triggers a release build on Travis CI. +Every change on the main branch (for example merging a pull request) triggers a release build on CI. The build publishes new version if specific criteria are met: all tests green, no 'ci skip release' used in commit message, see the build log for more information. Every new version is published to ["mockito/maven" Bintray repository](https://bintray.com/mockito/maven). New versions that Mockito team deems "notable" are additionally published to [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.mockito%22) and [JCenter](https://bintray.com/bintray/jcenter). diff --git a/build.gradle b/build.gradle index ed9ae5b450..64b4fe7581 100644 --- a/build.gradle +++ b/build.gradle @@ -111,7 +111,7 @@ wrapper { } spotless { - // We run the check separately on Travis, so don't run this by default + // We run the check separately on CI, so don't run this by default enforceCheck = false java { diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index 287a30a77a..e7e03d444c 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -73,8 +73,8 @@ publishing { system = 'GitHub issues' } ciManagement { - url = 'https://travis-ci.org/mockito/mockito' - system = 'TravisCI' + url = 'https://github.com/mockito/mockito/actions' + system = 'GH Actions' } } } From ac82b910014cfe6e7b55cb7f4068989ba2f61af0 Mon Sep 17 00:00:00 2001 From: sfaber Date: Sun, 8 Nov 2020 16:44:11 -0600 Subject: [PATCH 148/963] Kept Travis, enabled releases 1. Kept Travis build for a little while until we are confident with GH actions. 2. Enabled releasing from GH actions. Based on my testing I feel confident it will work. 3. Removed releasing/code coverage reporting from Travis to avoid confusing/incorrect behavior. --- .github/workflows/ci.yml | 2 +- .travis.yml | 58 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 .travis.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1692bc716..2464c3bbb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -75,7 +75,7 @@ jobs: java-version: 8 - name: Build and publish - run: ./gradlew bintrayUpload githubRelease --scan -m # TODO remove -m + run: ./gradlew bintrayUpload githubRelease --scan env: GH_WRITE_TOKEN: ${{secrets.GH_WRITE_TOKEN}} BINTRAY_API_KEY: ${{secrets.BINTRAY_API_KEY}} diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..791eb7e023 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,58 @@ +# More details on how to configure the Travis build +# https://docs.travis-ci.com/user/customizing-the-build/ + +# Speed up build by leveraging travis caches +cache: + directories: + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ + +# Enabling container based infrastructure hoping it will help the build speed <= this didn't work well, so it's reverted +# see https://docs.travis-ci.com/user/migrating-from-legacy/ and https://docs.travis-ci.com/user/ci-environment +sudo: true + +language: java + +dist: trusty + +matrix: + include: + - jdk: openjdk8 + - jdk: openjdk8 + env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline + - jdk: openjdk11 + env: SKIP_RELEASE=true + - jdk: openjdk11 + env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline + - jdk: openjdk14 + env: SKIP_RELEASE=true + - jdk: openjdk14 + env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline + # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) + - jdk: openjdk11 + name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." + script: ./gradlew spotlessCheck + # Do not upload a coverage report, as we don't run the tests for this job + after_success: true + - jdk: openjdk8 + name: "Check reproducibility of jars" + script: ./check_reproducibility.sh + # Do not upload a coverage report, as we don't run the tests for this job + after_success: true + +branches: + #Don't build tags + except: + - /^v\d/ + +#Below skips the installation step completely (https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step) +#We need it because otherwise Travis CI injects an awkward './gradlew assemble' step into the CI workflow +#We want to control and decide what Gradle tasks are executed +install: + - true + +script: + # To validate changes, we run building and bintray upload in dry run, and idea task. This happens on every build, even PRs. + # To publish, we perform github release and perform bintray upload (no dry run). This only for main branch builds. + - > + ./gradlew build bintrayUpload idea --scan -PbintrayDryRun \ No newline at end of file From 7f9e1cab50d962159f21744a472ee67e1d3b47d3 Mon Sep 17 00:00:00 2001 From: sfaber Date: Sun, 8 Nov 2020 16:57:45 -0600 Subject: [PATCH 149/963] Added code comment --- .travis.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 791eb7e023..c1b99c2136 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,13 @@ -# More details on how to configure the Travis build -# https://docs.travis-ci.com/user/customizing-the-build/ +# +# TRAVIS BUILD IS DEPRECATED +# +# WE ARE MOVING TO GH ACTIONS +# +# PLEASE DO NOT UPDATE THIS FILE ANY MORE +# +# This file can be removed once we have enough builds with GH Actions, likely Jan'21 +# See: https://github.com/mockito/mockito/issues/2080 +# # Speed up build by leveraging travis caches cache: From 7fa0e41ce3ba9c303e98fe0443a73b2b8956ebc1 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Mon, 9 Nov 2020 10:18:38 -0600 Subject: [PATCH 150/963] [CI] triggering build on push and pull request Configured the CI workflow to trigger builds on pull requests and pushes across all branches, not only our current main development branch. This behavior is standard for default Travis CI setup. It is also what is expected by devs working on Mockito [skip travis]. --- .github/workflows/ci.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2464c3bbb5..8b8b987c89 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,10 +2,8 @@ name: CI on: push: - branches: [ release/3.x ] tags-ignore: [v*] pull_request: - branches: [ release/3.x ] jobs: From cc0090ba2366484fc6480b3318910f2e560f55fe Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Mon, 9 Nov 2020 10:33:58 -0600 Subject: [PATCH 151/963] Fixed bug with CI workflow Ensure that branches are correctly configured [skip travis] --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b8b987c89..bedf095e7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,10 @@ name: CI on: push: - tags-ignore: [v*] + branches: ['**'] + tags-ignore: [v*] # release tags are automatically generated after a successful CI build, no need to run CI against them pull_request: + branches: ['**'] jobs: From 33bd1840140088fa130d2a5b1d7f702b33800641 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Tue, 10 Nov 2020 10:16:24 -0600 Subject: [PATCH 152/963] Improved CI workflow Made Gradle wrapper validation a part of the main CI workflow. This way, we can remove the explicit wrapper validation workflow. Less workflows -> simpler CI. Fixe #2094 [skip travis] --- .github/workflows/ci.yml | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bedf095e7c..d8a3b831f6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: mock-maker: ['mock-maker-default', 'mock-maker-inline'] # All build steps + # SINGLE-MATRIX-JOB means that the step does not need to be executed on every job in the matrix steps: - name: 1. Check out code @@ -34,30 +35,30 @@ jobs: with: java-version: ${{ matrix.java }} - # TODO: add step for gradle wrapper validation and remove the other workflow + - name: 3. Validate Gradle wrapper + if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' # SINGLE-MATRIX-JOB + uses: gradle/wrapper-validation-action@v1 # https://github.com/gradle/wrapper-validation-action - - name: 3. Build and check reproducibility of artifacts (single job only) - # Run on a single job, with the version of java used for releases - if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' + - name: 4. Build and check reproducibility of artifacts (single job only) + if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' # SINGLE-MATRIX-JOB run: ./check_reproducibility.sh - - name: 4. Spotless check (single job only). Run './gradlew spotlessApply' locally if this job fails. - # Run on a single job, with java version compatible with spotless - if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' + - name: 5. Spotless check (single job only). Run './gradlew spotlessApply' locally if this job fails. + if: matrix.java == 11 && matrix.mock-maker == 'mock-maker-default' # SINGLE-MATRIX-JOB run: ./gradlew spotlessCheck - - name: 5. Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} + - name: 6. Build on Java ${{ matrix.java }} with ${{ matrix.mock-maker }} run: ./gradlew build bintrayUpload idea --scan -PbintrayDryRun env: MOCK_MAKER: ${{ matrix.mock-maker }} - - name: 6. Upload coverage report + - name: 7. Upload coverage report run: | ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" # - # Release job, only for pushes to the main branch + # Release job, only for pushes to the main development branch # release: runs-on: ubuntu-latest From d0cd8c2fc88ac1b35a841c018fc7051d8132d1be Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Tue, 10 Nov 2020 10:22:44 -0600 Subject: [PATCH 153/963] Removed redundant CI workflow We don't need an explicit workflow for wrapper validation. We already run this as a step in the build: https://github.com/mockito/mockito/runs/1380756176?check_suite_focus=true#step:4:1 --- .github/workflows/gradle-wrapper-validation.yml | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 .github/workflows/gradle-wrapper-validation.yml diff --git a/.github/workflows/gradle-wrapper-validation.yml b/.github/workflows/gradle-wrapper-validation.yml deleted file mode 100644 index 405a2b3065..0000000000 --- a/.github/workflows/gradle-wrapper-validation.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: "Validate Gradle Wrapper" -on: [push, pull_request] - -jobs: - validation: - name: "Validation" - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: gradle/wrapper-validation-action@v1 From cf70fd9047253bd4e25387e9bd97cea4cc1ac25b Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Tue, 10 Nov 2020 23:35:33 +0100 Subject: [PATCH 154/963] Improve error message if initializer fails. --- gradle/dependencies.gradle | 2 +- .../bytebuddy/InlineBytecodeGenerator.java | 51 +++++++++++++------ 2 files changed, 36 insertions(+), 17 deletions(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index e8166e5c6d..7c62a4d000 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -4,7 +4,7 @@ ext { def versions = [:] -versions.bytebuddy = '1.10.15' +versions.bytebuddy = '1.10.18' versions.junitJupiter = '5.4.2' versions.errorprone = '2.4.0' 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 2bf9d15769..5b95e9f493 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -228,33 +228,52 @@ public synchronized void mockClassConstruction(Class type) { private static void assureInitialization(Class type) { try { Class.forName(type.getName(), true, type.getClassLoader()); - } catch (Throwable ignore) { + } catch (ExceptionInInitializerError e) { + throw new MockitoException( + join( + "Cannot instrument class that could not be initialized.", + "", + "A class that is not initializable would always fail during instrumentation.", + "Static initializers are never mocked by Mockito to avoid permanent disintegration of classes."), + e.getException()); + } catch (Throwable ignored) { } } private void triggerRetransformation(Set> types, boolean flat) { Set> targets = new HashSet>(); - for (Class type : types) { - if (flat) { - if (!mocked.contains(type) && flatMocked.add(type)) { - assureInitialization(type); - targets.add(type); - } - } else { - do { - if (mocked.add(type)) { + try { + for (Class type : types) { + if (flat) { + if (!mocked.contains(type) && flatMocked.add(type)) { assureInitialization(type); - if (!flatMocked.remove(type)) { - targets.add(type); - } - addInterfaces(targets, type.getInterfaces()); + targets.add(type); } - type = type.getSuperclass(); - } while (type != null); + } else { + do { + if (mocked.add(type)) { + assureInitialization(type); + if (!flatMocked.remove(type)) { + targets.add(type); + } + addInterfaces(targets, type.getInterfaces()); + } + type = type.getSuperclass(); + } while (type != null); + } + } + } catch (Throwable t) { + for (Class target : targets) { + mocked.remove(target); + flatMocked.remove(target); } + throw t; } + // The object type does not ever need instrumentation. + targets.remove(Object.class); + if (!targets.isEmpty()) { try { assureCanReadMockito(targets); From 3b09f8e8e0e8aa60039b7f17207a18032d8e7a8f Mon Sep 17 00:00:00 2001 From: shestee <53140474+shestee@users.noreply.github.com> Date: Wed, 11 Nov 2020 18:50:35 +0100 Subject: [PATCH 155/963] Removed duplicated setting (#2091) There is no need of specifying --parallel explicitly as it is Gradle's default. --- check_reproducibility.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/check_reproducibility.sh b/check_reproducibility.sh index 9352def942..d4aab96f6c 100755 --- a/check_reproducibility.sh +++ b/check_reproducibility.sh @@ -10,7 +10,7 @@ export SOURCE_DATE_EPOCH=$(date +%s) function calculate_checksums() { OUTPUT=checksums/$1 - ./gradlew --no-build-cache clean assemble --parallel + ./gradlew --no-build-cache clean assemble find ./build -name '*.jar' \ | grep '/build/libs/' \ @@ -23,4 +23,4 @@ function calculate_checksums() { calculate_checksums checksums-1.txt calculate_checksums checksums-2.txt -diff checksums/checksums-1.txt checksums/checksums-2.txt \ No newline at end of file +diff checksums/checksums-1.txt checksums/checksums-2.txt From be15bfb8d7c98edfe92da6ccd50554764966fd24 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Thu, 12 Nov 2020 10:03:32 -0600 Subject: [PATCH 156/963] Commit message directives for CI workflow Added standard idioms for avoiding unnecessary jobs: [skip ci] and [skip release] directives can be added in the commit message, bypassing the CI or release from CI. --- .github/workflows/ci.yml | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8a3b831f6..db9a46240d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,3 +1,10 @@ +# +# CI build that assembles artifacts and runs tests. +# If validation is successful this workflow releases from the main dev branch. +# +# - skipping CI: add [skip ci] to the commit message +# - skipping release: add [skip release] to the commit message +# name: CI on: @@ -14,6 +21,7 @@ jobs: # build: runs-on: ubuntu-latest + if: "! contains(toJSON(github.event.commits.*.message), '[skip ci]')" # Definition of the build matrix strategy: @@ -61,10 +69,15 @@ jobs: # Release job, only for pushes to the main development branch # release: - runs-on: ubuntu-latest + runs-on: ubuntu-latest needs: [build] # build job must pass before we can release - if: github.event_name == 'push' && github.ref == 'refs/heads/release/3.x' + + if: github.event_name == 'push' + && github.ref == 'refs/heads/release/3.x' + && !contains(toJSON(github.event.commits.*.message), '[skip release]') + steps: + - name: Check out code uses: actions/checkout@v2 # https://github.com/actions/checkout with: From e54b63f76295713dfe2f8a48f1d33320c7394bd7 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 13 Nov 2020 23:24:30 -0600 Subject: [PATCH 157/963] Avoided parallel workflow execution Avoided parallel execution of the workflow so that: - we get better UX (the "checks" view in PR does not have duplicated jobs) - we run less builds (conserves build quota) We *no longer* run CI for ordinary push to any remote branch. We run CI for pushes to the main dev branch or PRs. Preventing parallel workflows is reported to GitHub: https://github.community/t/prevent-parallel-workflows/16370 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db9a46240d..bf41083077 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ name: CI on: push: - branches: ['**'] + branches: ['release/3.x'] tags-ignore: [v*] # release tags are automatically generated after a successful CI build, no need to run CI against them pull_request: branches: ['**'] From 3a263deb4c868cb76fe0720adddac5d13ba56751 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Sun, 15 Nov 2020 21:59:05 +0100 Subject: [PATCH 158/963] Update src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java Co-authored-by: Marcono1234 --- .../bytebuddy/InlineBytecodeGenerator.java | 38 +++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) 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 5b95e9f493..5fc47cd7cb 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -4,18 +4,6 @@ */ package org.mockito.internal.creation.bytebuddy; -import java.lang.instrument.ClassFileTransformer; -import java.lang.instrument.Instrumentation; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.security.ProtectionDomain; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; - import net.bytebuddy.ByteBuddy; import net.bytebuddy.ClassFileVersion; import net.bytebuddy.asm.Advice; @@ -44,10 +32,18 @@ import org.mockito.internal.util.concurrent.WeakConcurrentSet; import org.mockito.mock.SerializableMode; -import static net.bytebuddy.implementation.MethodDelegation.*; -import static net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.*; +import java.lang.instrument.ClassFileTransformer; +import java.lang.instrument.Instrumentation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.ProtectionDomain; +import java.util.*; +import java.util.function.Predicate; + +import static net.bytebuddy.implementation.MethodDelegation.withDefaultConfiguration; +import static net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of; import static net.bytebuddy.matcher.ElementMatchers.*; -import static org.mockito.internal.util.StringUtil.*; +import static org.mockito.internal.util.StringUtil.join; @SuppressSignatureCheck public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTransformer { @@ -70,9 +66,13 @@ public class InlineBytecodeGenerator implements BytecodeGenerator, ClassFileTran String.class)); private final Instrumentation instrumentation; + private final ByteBuddy byteBuddy; + private final WeakConcurrentSet> mocked, flatMocked; + private final BytecodeGenerator subclassEngine; + private final AsmVisitorWrapper mockTransformer; private final Method getModule, canRead, redefineModule; @@ -230,11 +230,9 @@ private static void assureInitialization(Class type) { Class.forName(type.getName(), true, type.getClassLoader()); } catch (ExceptionInInitializerError e) { throw new MockitoException( - join( - "Cannot instrument class that could not be initialized.", - "", - "A class that is not initializable would always fail during instrumentation.", - "Static initializers are never mocked by Mockito to avoid permanent disintegration of classes."), + "Cannot instrument " + + type + + " because it or one of its supertypes could not be initialized", e.getException()); } catch (Throwable ignored) { } From 717992c82d4d4d398dd2bbe5adff2ff18cd6e07b Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Sat, 19 Sep 2020 00:43:59 +0200 Subject: [PATCH 159/963] Update to OpenJDK 15. --- gradle/root/coverage.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/root/coverage.gradle b/gradle/root/coverage.gradle index a161b87f19..772de84b1b 100644 --- a/gradle/root/coverage.gradle +++ b/gradle/root/coverage.gradle @@ -19,7 +19,7 @@ task mockitoCoverage(type: JacocoReport) { apply plugin: "jacoco" jacoco { - toolVersion = '0.8.5' + toolVersion = '0.8.6' if (currentProject != rootProject) { //already automatically enhanced in mockito main project as "java" plugin was applied before applyTo test From f4c59f58980210f62a8c797d876a352533d56279 Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Wed, 21 Oct 2020 23:11:43 +0100 Subject: [PATCH 160/963] Upgrade ByteBuddy to 1.10.17 --- .github/workflows/ci.yml | 32 +++++++++---------- .../matchers/InvalidUseOfMatchersTest.java | 3 +- .../DeepStubsSerializableTest.java | 18 ++++------- .../stubbing/StubbingWithDelegateTest.java | 15 +++++---- 4 files changed, 31 insertions(+), 37 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf41083077..b67cd75e35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,20 +15,20 @@ on: branches: ['**'] jobs: - - # - # Main build job + + # + # Main build job # build: runs-on: ubuntu-latest if: "! contains(toJSON(github.event.commits.*.message), '[skip ci]')" - + # Definition of the build matrix strategy: matrix: - java: [8, 11, 14] + java: [8, 11, 15] mock-maker: ['mock-maker-default', 'mock-maker-inline'] - + # All build steps # SINGLE-MATRIX-JOB means that the step does not need to be executed on every job in the matrix steps: @@ -45,7 +45,7 @@ jobs: - name: 3. Validate Gradle wrapper if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' # SINGLE-MATRIX-JOB - uses: gradle/wrapper-validation-action@v1 # https://github.com/gradle/wrapper-validation-action + uses: gradle/wrapper-validation-action@v1 # https://github.com/gradle/wrapper-validation-action - name: 4. Build and check reproducibility of artifacts (single job only) if: matrix.java == 8 && matrix.mock-maker == 'mock-maker-default' # SINGLE-MATRIX-JOB @@ -65,29 +65,29 @@ jobs: ./gradlew coverageReport -s --scan && cp build/reports/jacoco/mockitoCoverage/mockitoCoverage.xml jacoco.xml || echo "Code coverage failed" bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" - # + # # Release job, only for pushes to the main development branch - # + # release: - runs-on: ubuntu-latest + runs-on: ubuntu-latest needs: [build] # build job must pass before we can release - - if: github.event_name == 'push' + + if: github.event_name == 'push' && github.ref == 'refs/heads/release/3.x' && !contains(toJSON(github.event.commits.*.message), '[skip release]') - + steps: - + - name: Check out code uses: actions/checkout@v2 # https://github.com/actions/checkout with: fetch-depth: '0' # https://github.com/shipkit/shipkit-changelog#fetch-depth-on-ci - + - name: Set up Java 8 uses: actions/setup-java@v1 with: java-version: 8 - + - name: Build and publish run: ./gradlew bintrayUpload githubRelease --scan env: diff --git a/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java b/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java index ebcb08871c..338c072324 100644 --- a/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/InvalidUseOfMatchersTest.java @@ -105,8 +105,7 @@ public void should_mention_matcher_when_misuse_detected() { assertThat(run.getFailures()).hasSize(2); assertThat(run.getFailures().get(0).getException()) - .isInstanceOf(NullPointerException.class) - .hasMessage(null); + .isInstanceOf(NullPointerException.class); assertThat(run.getFailures().get(1).getException()) .isInstanceOf(InvalidUseOfMatchersException.class) .hasMessageContaining("primitive alternatives"); diff --git a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java index 06f74b9854..8d73463a65 100644 --- a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java +++ b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java @@ -4,8 +4,7 @@ */ package org.mockitousage.serialization; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -74,16 +73,11 @@ public void should_serialize_and_deserialize_parameterized_class_mocked_with_dee 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 - 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"); - } catch (NullPointerException e) { - assertThat(e).hasMessage(null); - } + assertThatThrownBy( + () -> + when(deserialized_deep_stub.iterator().next().get(42)) + .thenReturn("no")) + .isInstanceOf(NullPointerException.class); } static class SampleClass implements Serializable { diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java index 5d21e71630..72ebfbbc6f 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java @@ -5,6 +5,7 @@ package org.mockitousage.stubbing; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.AdditionalAnswers.delegatesTo; @@ -97,15 +98,15 @@ public void delegate_should_not_be_called_when_stubbed2() { } @Test - public void null_wrapper_dont_throw_exception_from_org_mockito_package() throws Exception { + public void null_wrapper_dont_throw_exception_from_org_mockito_package() { IMethods methods = mock(IMethods.class, delegatesTo(new MethodsImpl())); - try { - byte b = methods.byteObjectReturningMethod(); // real method returns null - fail(); - } catch (Exception e) { - assertThat(e.toString()).doesNotContain("org.mockito"); - } + assertThatThrownBy( + () -> { + @SuppressWarnings("unused") + byte b = methods.byteObjectReturningMethod(); + }) + .isInstanceOf(NullPointerException.class); } @Test From b8bb0f0905eb5434a35c8511fb4738548a9c9114 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Tue, 10 Nov 2020 23:50:21 +0100 Subject: [PATCH 161/963] Adjust build to support Java 15. --- .travis.yml | 6 +++--- .../serialization/DeepStubsSerializableTest.java | 6 +----- .../mockitousage/stubbing/StubbingWithDelegateTest.java | 8 +------- 3 files changed, 5 insertions(+), 15 deletions(-) diff --git a/.travis.yml b/.travis.yml index c1b99c2136..8cbbd48314 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,9 +32,9 @@ matrix: env: SKIP_RELEASE=true - jdk: openjdk11 env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk14 + - jdk: openjdk15 env: SKIP_RELEASE=true - - jdk: openjdk14 + - jdk: openjdk15 env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) - jdk: openjdk11 @@ -63,4 +63,4 @@ script: # To validate changes, we run building and bintray upload in dry run, and idea task. This happens on every build, even PRs. # To publish, we perform github release and perform bintray upload (no dry run). This only for main branch builds. - > - ./gradlew build bintrayUpload idea --scan -PbintrayDryRun \ No newline at end of file + ./gradlew build bintrayUpload idea --scan -PbintrayDryRun diff --git a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java index 8d73463a65..856e89b8d4 100644 --- a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java +++ b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java @@ -73,11 +73,7 @@ public void should_serialize_and_deserialize_parameterized_class_mocked_with_dee ListContainer deserialized_deep_stub = serializeAndBack(deep_stubbed); - assertThatThrownBy( - () -> - when(deserialized_deep_stub.iterator().next().get(42)) - .thenReturn("no")) - .isInstanceOf(NullPointerException.class); + assertThat(deserialized_deep_stub.iterator().next()).isNull(); } static class SampleClass implements Serializable { diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java index 72ebfbbc6f..245fa788ee 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java @@ -5,7 +5,6 @@ package org.mockitousage.stubbing; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.AdditionalAnswers.delegatesTo; @@ -101,12 +100,7 @@ public void delegate_should_not_be_called_when_stubbed2() { public void null_wrapper_dont_throw_exception_from_org_mockito_package() { IMethods methods = mock(IMethods.class, delegatesTo(new MethodsImpl())); - assertThatThrownBy( - () -> { - @SuppressWarnings("unused") - byte b = methods.byteObjectReturningMethod(); - }) - .isInstanceOf(NullPointerException.class); + assertThat(methods.byteObjectReturningMethod()).isNull(); } @Test From f5419b0638b6b517a7d29991bf29639988242335 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Fri, 20 Nov 2020 23:27:01 -0600 Subject: [PATCH 162/963] Avoid CI failures in forks When contributors fork the repo, they get GH actions that run when they push code to their forks. This change prevents GH Action "release" job failures. Example failure: https://github.com/shestee/mockito/actions/runs/375185562 --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b67cd75e35..b9c42ee2b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,7 @@ jobs: if: github.event_name == 'push' && github.ref == 'refs/heads/release/3.x' + && github.repository == 'mockito/mockito' && !contains(toJSON(github.event.commits.*.message), '[skip release]') steps: From 2e4c214bd2e6660b1047c254ab13af7560f97372 Mon Sep 17 00:00:00 2001 From: shestee <53140474+shestee@users.noreply.github.com> Date: Sat, 21 Nov 2020 11:16:17 +0100 Subject: [PATCH 163/963] Fix incorrect comment type in properties file (#2107) *.properties file uses '#' for comments, not '//' [skip release] --- version.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.properties b/version.properties index 08fdb9c84c..68dab810c7 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -//Used by Shipkit Auto Version Gradle plugin: https://github.com/shipkit/shipkit-auto-version -version=3.6.* +# Used by Shipkit Auto Version Gradle plugin: https://github.com/shipkit/shipkit-auto-version +version=3.6.* \ No newline at end of file From fde5abb9f044a6b614eeb6a8c63d25fffe2df210 Mon Sep 17 00:00:00 2001 From: Holger Date: Tue, 24 Nov 2020 12:43:23 +0100 Subject: [PATCH 164/963] Keep META-INF folder at top of published mockito-core jar (#2109) Fixes #2108 [ci maven-central-release] --- gradle/mockito-core/osgi.gradle | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle index f44ea9c18b..2fa0b78354 100644 --- a/gradle/mockito-core/osgi.gradle +++ b/gradle/mockito-core/osgi.gradle @@ -71,7 +71,8 @@ class RemoveOsgiLastModifiedHeader { this.artifact .entries() - .sort { it.name } + // Keep META-INF folder at the beginning to avoid https://github.com/mockito/mockito/issues/2108 + .sort { (it.name.startsWith("META-INF") ? "A/" + it.name : "B/" + it.name) } .each { JarEntry entry -> stream.putNextEntry(newJarEntry(entry)) From 3213b49313749da62ee6ed75999161d629ca7292 Mon Sep 17 00:00:00 2001 From: sfaber Date: Tue, 24 Nov 2020 20:39:21 -0600 Subject: [PATCH 165/963] Enabled releases to Maven Central Fixed the bug with how we controlled Maven Central releases via commit messages. Testing done: Ran the workflow in a forked repository and b) observed that the information from the commit message is passed to the environment variable. --- .github/workflows/ci.yml | 1 + gradle/shipkit.gradle | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b67cd75e35..236a08feab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,5 +91,6 @@ jobs: - name: Build and publish run: ./gradlew bintrayUpload githubRelease --scan env: + MAVEN_CENTRAL_RELEASE: ${{contains(toJSON(github.event.commits.*.message), '[ci maven-central-release]')}} GH_WRITE_TOKEN: ${{secrets.GH_WRITE_TOKEN}} BINTRAY_API_KEY: ${{secrets.BINTRAY_API_KEY}} diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index 1dd2f1cc23..2a430fe6f8 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -28,7 +28,7 @@ ext.mavenCentralRelease = shouldReleaseToCentral(project) * To test this logic, run build with '-i' (info logging) and inspect the build output. */ static boolean shouldReleaseToCentral(project) { - boolean centralReleaseByCommit = System.getenv("TRAVIS_COMMIT_MESSAGE")?.contains("[ci maven-central-release]") + boolean centralReleaseByCommit = 'true' == System.getenv("MAVEN_CENTRAL_RELEASE") boolean centralReleaseByProjectProperty = project.hasProperty("maven-central-release") boolean centralRelease = centralReleaseByCommit || centralReleaseByProjectProperty def message = """Bintray publish was using following settings: From ce2f0b63aa97f0fbf726b4f0928662c6e5fd387d Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Tue, 24 Nov 2020 22:07:36 -0600 Subject: [PATCH 166/963] Fixed maven central releases Added missing environmental variables. This should publish a new version to Maven Central. --- .github/workflows/ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 15a847360e..b236027a1e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,3 +95,5 @@ jobs: MAVEN_CENTRAL_RELEASE: ${{contains(toJSON(github.event.commits.*.message), '[ci maven-central-release]')}} GH_WRITE_TOKEN: ${{secrets.GH_WRITE_TOKEN}} BINTRAY_API_KEY: ${{secrets.BINTRAY_API_KEY}} + NEXUS_TOKEN_USER: ${{secrets.NEXUS_TOKEN_USER}} + NEXUS_TOKEN_PWD: ${{secrets.NEXUS_TOKEN_PWD}} From 3e036f87d268af86e4aade24d2d67f1be391989d Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Tue, 24 Nov 2020 22:21:34 -0600 Subject: [PATCH 167/963] Force maven central release Changed a comment to force the build that will also publish to maven central [ci maven-central-release] --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b236027a1e..5813dfbc77 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,7 +89,7 @@ jobs: with: java-version: 8 - - name: Build and publish + - name: Build and publish to Bintray/MavenCentral run: ./gradlew bintrayUpload githubRelease --scan env: MAVEN_CENTRAL_RELEASE: ${{contains(toJSON(github.event.commits.*.message), '[ci maven-central-release]')}} From 4df06a6a0e44a6d95748f0a325f1c93a1fb758df Mon Sep 17 00:00:00 2001 From: sullis Date: Mon, 30 Nov 2020 13:55:48 -0800 Subject: [PATCH 168/963] Upgrade Dependabot to version 2 (#1956) https://github.blog/2020-06-01-keep-all-your-packages-up-to-date-with-dependabot/ --- .dependabot/config.yml | 8 -------- .github/dependabot.yml | 10 ++++++++++ 2 files changed, 10 insertions(+), 8 deletions(-) delete mode 100644 .dependabot/config.yml create mode 100644 .github/dependabot.yml diff --git a/.dependabot/config.yml b/.dependabot/config.yml deleted file mode 100644 index 16be16a270..0000000000 --- a/.dependabot/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -version: 1 - -update_configs: - - package_manager: "java:gradle" - directory: "/" - update_schedule: "daily" - # Redundant - default repository branch by default - target_branch: "release/3.x" diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..1ef0730a67 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "daily" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" From e95d15daa6d5030dfa38c5c3db0c102eaf50ddda Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 22:08:16 +0000 Subject: [PATCH 169/963] Bump com.github.ben-manes.versions from 0.28.0 to 0.36.0 (#2114) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 64b4fe7581..56259b4542 100644 --- a/build.gradle +++ b/build.gradle @@ -21,7 +21,7 @@ buildscript { plugins { id "com.diffplug.gradle.spotless" version "3.24.3" id 'eclipse' - id 'com.github.ben-manes.versions' version '0.28.0' + id 'com.github.ben-manes.versions' version '0.36.0' id 'biz.aQute.bnd.builder' version '5.1.0' id 'ru.vyarus.animalsniffer' version '1.5.2' } From 331ef0df377b32b4de34a2b93b128ac41f63d79c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 23:38:08 +0000 Subject: [PATCH 170/963] Bump auto-service from 1.0-rc5 to 1.0-rc7 (#2117) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 7c62a4d000..072eb158ae 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -23,7 +23,7 @@ libraries.bytebuddyandroid = "net.bytebuddy:byte-buddy-android:${versions.bytebu libraries.errorprone = "com.google.errorprone:error_prone_core:${versions.errorprone}" libraries.errorproneTestApi = "com.google.errorprone:error_prone_test_helpers:${versions.errorprone}" -libraries.autoservice = "com.google.auto.service:auto-service:1.0-rc5" +libraries.autoservice = "com.google.auto.service:auto-service:1.0-rc7" // objenesis 3.x fails on android instrumentation test compile. https://github.com/mockito/mockito/issues/2007 libraries.objenesis2 = 'org.objenesis:objenesis:2.6' From cfa551370587207648d27b374a098735bcbe3c00 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 23:38:47 +0000 Subject: [PATCH 171/963] Bump org.eclipse.osgi from 3.15.0 to 3.16.0 (#2116) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 072eb158ae..33b6f18f26 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -32,7 +32,7 @@ libraries.objenesis3 = 'org.objenesis:objenesis:3.1' libraries.asm = 'org.ow2.asm:asm:7.0' libraries.osgi = 'org.osgi:osgi.core:7.0.0' -libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.15.0' +libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.0' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.1.1' def kotlinVersion = '1.3.72' From e9b0a41e346d1f26e10207519b6d40b22d0aa621 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 23:57:37 +0000 Subject: [PATCH 172/963] Bump opentest4j from 1.1.1 to 1.2.0 (#2118) Bumps [opentest4j](https://github.com/ota4j-team/opentest4j) from 1.1.1 to 1.2.0. - [Release notes](https://github.com/ota4j-team/opentest4j/releases) - [Commits](https://github.com/ota4j-team/opentest4j/compare/r1.1.1...r1.2.0) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 33b6f18f26..8b1284e3d0 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -14,7 +14,7 @@ libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1. libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" libraries.assertj = 'org.assertj:assertj-core:3.16.1' libraries.hamcrest = 'org.hamcrest:hamcrest-core:1.3' -libraries.opentest4j = 'org.opentest4j:opentest4j:1.1.1' +libraries.opentest4j = 'org.opentest4j:opentest4j:1.2.0' libraries.bytebuddy = "net.bytebuddy:byte-buddy:${versions.bytebuddy}" libraries.bytebuddyagent = "net.bytebuddy:byte-buddy-agent:${versions.bytebuddy}" From 8c3164b8334c319913379d3099d7de5e54c35e4a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2020 23:57:54 +0000 Subject: [PATCH 173/963] Bump junit-platform-launcher from 1.1.0 to 1.7.0 (#2115) Bumps [junit-platform-launcher](https://github.com/junit-team/junit5) from 1.1.0 to 1.7.0. - [Release notes](https://github.com/junit-team/junit5/releases) - [Commits](https://github.com/junit-team/junit5/commits) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 8b1284e3d0..292086e991 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -10,7 +10,7 @@ versions.errorprone = '2.4.0' libraries.junit4 = 'junit:junit:4.12' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" -libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.1.0' +libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.0' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" libraries.assertj = 'org.assertj:assertj-core:3.16.1' libraries.hamcrest = 'org.hamcrest:hamcrest-core:1.3' From 8718fc2e3363dc924aa45152c845b00a15a31a4b Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Tue, 1 Dec 2020 19:13:59 +0100 Subject: [PATCH 174/963] Use HTTPS for links in documentation (#2087) --- .github/CONTRIBUTING.md | 8 ++++---- .github/ISSUE_TEMPLATE.md | 2 +- README.md | 16 ++++++++-------- src/main/java/org/mockito/BDDMockito.java | 2 +- src/main/java/org/mockito/CheckReturnValue.java | 2 +- src/main/java/org/mockito/Mockito.java | 16 ++++++++-------- .../bytebuddy/InlineByteBuddyMockMaker.java | 2 +- .../java/org/mockito/internal/util/Platform.java | 2 +- .../util/reflection/GenericMetadataSupport.java | 10 +++++----- .../org/mockito/junit/MockitoJUnitRunner.java | 2 +- src/main/java/org/mockito/junit/MockitoRule.java | 2 +- .../apachecommons/EqualsBuilderTest.java | 4 ++-- .../org/mockito/internal/util/PlatformTest.java | 12 ++++++------ .../java/org/mockitousage/JunitJupiterTest.java | 2 +- 14 files changed, 41 insertions(+), 41 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index dcb6481825..b9b8948882 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -6,8 +6,8 @@ **If looking for support** -* Search / Ask question on [stackoverflow](http://stackoverflow.com/questions/tagged/mockito) -* Go to the [mockito mailing-list](http://groups.google.com/group/mockito) (moderated) +* Search / Ask question on [stackoverflow](https://stackoverflow.com/questions/tagged/mockito) +* Go to the [mockito mailing-list](https://groups.google.com/group/mockito) (moderated) * Issues should always have a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) (same as any question on stackoverflow.com) # Contributing to Mockito @@ -46,7 +46,7 @@ Things we pay attention in a PR : * On pull requests, please document the change, what it brings, what is the benefit. * **Clean commit history** in the topic branch in your fork of the repository, even during review. That means that commits are _rebased_ and _squashed_ if necessary, so that each commit clearly changes one things and there are no extraneous fix-ups. - For that matter it's possible to commit [_semantic_ changes](http://lemike-de.tumblr.com/post/79041908218/semantic-commits). _Tests are an asset, so is history_. + For that matter it's possible to commit [_semantic_ changes](https://lemike-de.tumblr.com/post/79041908218/semantic-commits). _Tests are an asset, so is history_. _Example gratia_: @@ -80,7 +80,7 @@ But first of all, make sure that : * Line ending character is unix-style **`LF`** * New line is added at end of file: `IntelliJ setting > Editor > General > Ensure line feed at file end on save` -For most editors, this should be automatically enforced by [EditorConfig](http://editorconfig.org/). +For most editors, this should be automatically enforced by [EditorConfig](https://editorconfig.org/). Check if your editor has a built-in plugin or if you need to download one. IntelliJ has a built-in plugin, for Eclipse you need to download [this plugin](https://github.com/ncjones/editorconfig-eclipse#readme). diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 467f81e489..058a562f95 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -4,7 +4,7 @@ > > If this is about mockito usage, the better way is to reach out to > -> - stackoverflow : http://stackoverflow.com/questions/tagged/mockito +> - stackoverflow : https://stackoverflow.com/questions/tagged/mockito > - the mailing-list : https://groups.google.com/forum/#!forum/mockito / mockito@googlegroups.com > (Note mailing-list is moderated to avoid spam) > diff --git a/README.md b/README.md index 6774bc92bd..69cd1d4450 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ - + Mockito @@ -27,16 +27,16 @@ The maintainers of org.mockito:mockito-core and thousands of other packages are ## Development -Mockito [continuously delivers](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview) improvements using Shipkit library (http://shipkit.org). See the [latest release notes](https://github.com/mockito/mockito/blob/release/3.x/doc/release-notes/official.md) and [latest documentation](http://javadoc.io/page/org.mockito/mockito-core/latest/org/mockito/Mockito.html). Docs in javadoc.io are available 24h after release. Read also about [semantic versioning in Mockito](https://github.com/mockito/mockito/wiki/Semantic-Versioning). **Note: not every version is published to Maven Central.** +Mockito [continuously delivers](https://github.com/mockito/mockito/wiki/Continuous-Delivery-Overview) improvements using Shipkit library (http://shipkit.org). See the [latest release notes](https://github.com/mockito/mockito/blob/release/3.x/doc/release-notes/official.md) and [latest documentation](https://javadoc.io/page/org.mockito/mockito-core/latest/org/mockito/Mockito.html). Docs in javadoc.io are available 24h after release. Read also about [semantic versioning in Mockito](https://github.com/mockito/mockito/wiki/Semantic-Versioning). **Note: not every version is published to Maven Central.** Older 1.x and 2.x releases are available in -[Central Repository](http://search.maven.org/#artifactdetails|org.mockito|mockito-core|1.10.19|jar) +[Central Repository](https://search.maven.org/artifact/org.mockito/mockito-core/1.10.19/jar) , [Bintray](https://bintray.com/mockito/maven/mockito/1.10.19/view) -and [javadoc.io](http://javadoc.io/doc/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html) (documentation). +and [javadoc.io](https://javadoc.io/doc/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html) (documentation). ## More information -All you want to know about Mockito is hosted at [The Mockito Site](http://site.mockito.org) which is [Open Source](https://github.com/mockito/mockito.github.io) and likes [pull requests](https://github.com/mockito/mockito.github.io/pulls), too. +All you want to know about Mockito is hosted at [The Mockito Site](https://site.mockito.org) which is [Open Source](https://github.com/mockito/mockito.github.io) and likes [pull requests](https://github.com/mockito/mockito.github.io/pulls), too. Want to contribute? Take a look at the [Contributing Guide](https://github.com/mockito/mockito/blob/release/3.x/.github/CONTRIBUTING.md). @@ -44,8 +44,8 @@ Enjoy Mockito! ## Need help? -* Search / Ask question on [stackoverflow](http://stackoverflow.com/questions/tagged/mockito) -* Go to the [mockito mailing-list](http://groups.google.com/group/mockito) (moderated) +* Search / Ask question on [stackoverflow](https://stackoverflow.com/questions/tagged/mockito) +* Go to the [mockito mailing-list](https://groups.google.com/group/mockito) (moderated) * Open a ticket in GitHub [issue tracker](https://github.com/mockito/mockito/issues) ## How to develop Mockito? @@ -67,7 +67,7 @@ Mockito [implements Continuous Delivery model](https://github.com/mockito/mockit Every change on the main branch (for example merging a pull request) triggers a release build on CI. The build publishes new version if specific criteria are met: all tests green, no 'ci skip release' used in commit message, see the build log for more information. Every new version is published to ["mockito/maven" Bintray repository](https://bintray.com/mockito/maven). -New versions that Mockito team deems "notable" are additionally published to [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.mockito%22) and [JCenter](https://bintray.com/bintray/jcenter). +New versions that Mockito team deems "notable" are additionally published to [Maven Central](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.mockito%22) and [JCenter](https://bintray.com/bintray/jcenter). We used to publish every version to Maven Central but we changed this strategy based on feedback from the community ([#911](https://github.com/mockito/mockito/issues/911)). * Q: What's new in Mockito release model? diff --git a/src/main/java/org/mockito/BDDMockito.java b/src/main/java/org/mockito/BDDMockito.java index c4861ba4a9..1f249b4595 100644 --- a/src/main/java/org/mockito/BDDMockito.java +++ b/src/main/java/org/mockito/BDDMockito.java @@ -13,7 +13,7 @@ * Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods. * This is exactly how we write our tests and we warmly encourage you to do so! *

    - * Start learning about BDD here: http://en.wikipedia.org/wiki/Behavior_Driven_Development + * Start learning about BDD here: https://en.wikipedia.org/wiki/Behavior-driven_development *

    * The problem is that current stubbing api with canonical role of when word does not integrate nicely with //given //when //then comments. * It's because stubbing belongs to given component of the test and not to the when component of the test. diff --git a/src/main/java/org/mockito/CheckReturnValue.java b/src/main/java/org/mockito/CheckReturnValue.java index 7bc3b257bf..935b3207f6 100644 --- a/src/main/java/org/mockito/CheckReturnValue.java +++ b/src/main/java/org/mockito/CheckReturnValue.java @@ -17,7 +17,7 @@ * This annotation is public, because we have to use it in multiple packages. * * @see Findbugs source code - * @see ErrorProne check + * @see ErrorProne check * @since 2.11.4 */ @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 64df8b8db7..5ed4527680 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -38,7 +38,7 @@ * The Mockito library enables mock creation, verification and stubbing. * *

    - * This javadoc content is also available on the http://mockito.org web page. + * This javadoc content is also available on the https://site.mockito.org/ web page. * All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code. * It allows access to documentation straight from the IDE even if you work offline. * It motivates Mockito developers to keep documentation up-to-date with the code that they write, @@ -104,7 +104,7 @@ *

    0. Migrating to Mockito 2

    * * In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0! - * Mockito follows semantic versioning and contains breaking changes only on major version upgrades. + * Mockito follows semantic versioning and contains breaking changes only on major version upgrades. * In the lifecycle of a library, breaking changes are necessary * to roll out a set of brand new features that alter the existing behavior or even change the API. * For a comprehensive guide on the new release including incompatible changes, @@ -767,7 +767,7 @@ * https://github.com/mockito/mockito/wiki/FAQ *

    * In case of questions you may also post to mockito mailing list: - * http://groups.google.com/group/mockito + * https://groups.google.com/group/mockito *

    * Next, you should know that Mockito validates if you use it correctly all the time. * However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()} @@ -780,7 +780,7 @@ * Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods. * This is exactly how we write our tests and we warmly encourage you to do so! *

    - * Start learning about BDD here: http://en.wikipedia.org/wiki/Behavior_Driven_Development + * Start learning about BDD here: https://en.wikipedia.org/wiki/Behavior-driven_development *

    * The problem is that current stubbing api with canonical role of when word does not integrate nicely with //given //when //then comments. * It's because stubbing belongs to given component of the test and not to the when component of the test. @@ -823,7 +823,7 @@ * List serializableMock = mock(List.class, withSettings().serializable()); * *

    - * The mock can be serialized assuming all the normal + * The mock can be serialized assuming all the normal * serialization requirements are met by the class. *

    * Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version @@ -1357,7 +1357,7 @@ * *

  • This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM, * that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to - * manually add the Byte Buddy Java agent jar using the -javaagent + * manually add the Byte Buddy Java agent jar using the -javaagent * parameter upon starting the JVM. *
  • * @@ -1506,7 +1506,7 @@ *

    45. New JUnit Jupiter (JUnit5+) extension

    * * For integration with JUnit Jupiter (JUnit5+), use the `org.mockito:mockito-junit-jupiter` artifact. - * For more information about the usage of the integration, see the JavaDoc of MockitoExtension. + * For more information about the usage of the integration, see the JavaDoc of MockitoExtension. * *

    46. * New Mockito.lenient() and MockSettings.lenient() methods (Since 2.20.0)

    @@ -3189,7 +3189,7 @@ public static VerificationAfterDelay after(long millis) { /** * First of all, in case of any trouble, I encourage you to read the Mockito FAQ: https://github.com/mockito/mockito/wiki/FAQ *

    - * In case of questions you may also post to mockito mailing list: http://groups.google.com/group/mockito + * In case of questions you may also post to mockito mailing list: https://groups.google.com/group/mockito *

    * validateMockitoUsage() explicitly validates the framework state to detect invalid use of Mockito. * However, this feature is optional because Mockito validates the usage all the time... but there is a gotcha so read on. 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 96477f4776..9c0aa9362f 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java @@ -95,7 +95,7 @@ * Note that inline mocks require a Java agent to be attached. Mockito will attempt an attachment of a Java agent upon * loading the mock maker for creating inline mocks. Such runtime attachment is only possible when using a JVM that * is part of a JDK or when using a Java 9 VM. When running on a non-JDK VM prior to Java 9, it is however possible to - * manually add the Byte Buddy Java agent jar using the -javaagent + * manually add the Byte Buddy Java agent jar using the -javaagent * parameter upon starting the JVM. Furthermore, the inlining mock maker requires the VM to support class retransformation * (also known as HotSwap). All major VM distributions such as HotSpot (OpenJDK), J9 (IBM/Websphere) or Zing (Azul) * support this feature. diff --git a/src/main/java/org/mockito/internal/util/Platform.java b/src/main/java/org/mockito/internal/util/Platform.java index 200fc511d6..946e4ff3be 100644 --- a/src/main/java/org/mockito/internal/util/Platform.java +++ b/src/main/java/org/mockito/internal/util/Platform.java @@ -61,7 +61,7 @@ public static String describe() { "", "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", + "https://search.maven.org/artifact/org.mockito/mockito-android", "", description); } 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 17265c883a..ae54e6aebe 100644 --- a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java +++ b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java @@ -197,7 +197,7 @@ private BoundedType boundsOf(TypeVariable typeParameter) { */ private BoundedType boundsOf(WildcardType wildCard) { /* - * According to JLS(http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.5.1): + * According to JLS(https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1): * - Lower and upper can't coexist: (for instance, this is not allowed: * & super MyInterface>) * - Multiple concrete type bounds are not supported (for instance, this is not allowed: @@ -594,9 +594,9 @@ public Class rawType() { * Type representing bounds of a type * * @see TypeVarBoundedType - * @see http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4 + * @see https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.4 * @see WildCardBoundedType - * @see http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.5.1 + * @see https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1 */ public interface BoundedType extends Type { Type firstBound(); @@ -622,7 +622,7 @@ public interface BoundedType extends Type { * *

    * - * @see http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4 + * @see https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.4 */ public static class TypeVarBoundedType implements BoundedType { private final TypeVariable typeVariable; @@ -689,7 +689,7 @@ public TypeVariable typeVariable() { *

    The JLS says that lower bound and upper bound are mutually exclusive, and that multiple bounds * are not allowed. * - * @see http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4 + * @see https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.4 */ public static class WildCardBoundedType implements BoundedType { private final WildcardType wildcard; diff --git a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java index 3d2e8675e5..6951868e68 100644 --- a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java +++ b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java @@ -46,7 +46,7 @@ * It drives cleaner tests and improves debugging experience. * The only reason this feature is not turned on by default * is because it would have been an incompatible change - * and Mockito strictly follows semantic versioning. + * and Mockito strictly follows semantic versioning. * * * Runner is completely optional - there are other ways you can get @Mock working, for example by writing a base class. diff --git a/src/main/java/org/mockito/junit/MockitoRule.java b/src/main/java/org/mockito/junit/MockitoRule.java index 276d7ce7e9..a45314ecc9 100644 --- a/src/main/java/org/mockito/junit/MockitoRule.java +++ b/src/main/java/org/mockito/junit/MockitoRule.java @@ -46,7 +46,7 @@ * It drives cleaner tests and improves debugging experience. * The only reason this feature is not turned on by default * is because it would have been an incompatible change - * and Mockito strictly follows semantic versioning. + * and Mockito strictly follows semantic versioning. * * * Example use: 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 5e2bd696bb..53f34109ba 100644 --- a/src/test/java/org/mockito/internal/matchers/apachecommons/EqualsBuilderTest.java +++ b/src/test/java/org/mockito/internal/matchers/apachecommons/EqualsBuilderTest.java @@ -1064,7 +1064,7 @@ public void testUnrelatedClasses() { } /** - * Test from http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 + * Test from https://issues.apache.org/jira/browse/LANG-42 */ @Test public void testNpeForNullElement() { @@ -1072,7 +1072,7 @@ public void testNpeForNullElement() { 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 + // https://issues.apache.org/jira/browse/LANG-42 new EqualsBuilder().append(x1, x2); } diff --git a/src/test/java/org/mockito/internal/util/PlatformTest.java b/src/test/java/org/mockito/internal/util/PlatformTest.java index eef773dd64..b72c71d398 100644 --- a/src/test/java/org/mockito/internal/util/PlatformTest.java +++ b/src/test/java/org/mockito/internal/util/PlatformTest.java @@ -68,13 +68,13 @@ public void should_warn_for_jvm() throws Exception { public void should_parse_open_jdk_string_and_report_wether_below_or_nut_update_45() { // Given // Sources : - // - 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 + // - https://www.oracle.com/java/technologies/javase/versioning-naming.html + // - https://www.oracle.com/java/technologies/javase/jdk7-naming.html + // - https://www.oracle.com/java/technologies/javase/jdk8-naming.html // - - // http://stackoverflow.com/questions/35844985/how-do-we-get-sr-and-fp-of-ibm-jre-using-java + // https://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 + // https://www.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.80.doc/user/build_number.html Map versions = new HashMap() { { @@ -103,7 +103,7 @@ public void should_parse_open_jdk9_string() { // Given // Sources : - // - http://openjdk.java.net/jeps/223 (Java 9) + // - https://openjdk.java.net/jeps/223 (Java 9) // // System Property Existing Proposed // ------------------------------- ------------ -------- diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java index df9fce5e88..31abe2e610 100644 --- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java +++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java @@ -80,7 +80,7 @@ void rootMockCreated() { @Nested @ExtendWith(MockitoExtension.class) // ^^ duplicate registration should be ignored by JUnit - // see http://junit.org/junit5/docs/current/user-guide/#extensions-registration-inherita + // see https://junit.org/junit5/docs/current/user-guide/#extensions-registration-inheritance class DuplicateExtensionOnNestedTest { @Mock From 74388ed76d8bb58939eb9492f6276ef860621b6a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2020 18:14:28 +0000 Subject: [PATCH 175/963] Bump com.diffplug.gradle.spotless from 3.24.3 to 4.5.1 (#2122) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 56259b4542..4b9d861ef7 100644 --- a/build.gradle +++ b/build.gradle @@ -19,7 +19,7 @@ buildscript { } plugins { - id "com.diffplug.gradle.spotless" version "3.24.3" + id "com.diffplug.gradle.spotless" version "4.5.1" id 'eclipse' id 'com.github.ben-manes.versions' version '0.36.0' id 'biz.aQute.bnd.builder' version '5.1.0' From a5676ffba38d2c02cd13fc0c1b63707e29fb5834 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2020 18:15:06 +0000 Subject: [PATCH 176/963] Bump biz.aQute.bnd.gradle from 5.1.1 to 5.2.0 (#2123) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 292086e991..c6cd2e86cc 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -33,7 +33,7 @@ libraries.asm = 'org.ow2.asm:asm:7.0' libraries.osgi = 'org.osgi:osgi.core:7.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.0' -libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.1.1' +libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' def kotlinVersion = '1.3.72' libraries.kotlin = [ From ac76cdfc35a8c41eb612a1c63e26939b3b2fedbe Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2020 18:15:10 +0000 Subject: [PATCH 177/963] Bump junit from 4.12 to 4.13.1 (#2124) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index c6cd2e86cc..874cac812d 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -8,7 +8,7 @@ versions.bytebuddy = '1.10.18' versions.junitJupiter = '5.4.2' versions.errorprone = '2.4.0' -libraries.junit4 = 'junit:junit:4.12' +libraries.junit4 = 'junit:junit:4.13.1' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.0' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" From dca584b15e89eefbcc5c43019229e2de898c5ddc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2020 18:15:22 +0000 Subject: [PATCH 178/963] Bump versions.junitJupiter from 5.4.2 to 5.7.0 (#2125) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 874cac812d..32c3b8f6b2 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -5,7 +5,7 @@ ext { def versions = [:] versions.bytebuddy = '1.10.18' -versions.junitJupiter = '5.4.2' +versions.junitJupiter = '5.7.0' versions.errorprone = '2.4.0' libraries.junit4 = 'junit:junit:4.13.1' From ad6a9151b9070d950315115b304b962b8d56426f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2020 18:47:37 +0000 Subject: [PATCH 179/963] Bump kotlin-stdlib from 1.3.72 to 1.4.20 (#2130) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 32c3b8f6b2..ff12cd9cc4 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -35,7 +35,7 @@ libraries.osgi = 'org.osgi:osgi.core:7.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.0' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' -def kotlinVersion = '1.3.72' +def kotlinVersion = '1.4.20' libraries.kotlin = [ version: kotlinVersion, From 897da59c3c8dc5d93c71d10102a7a4a626cc0338 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2020 18:47:52 +0000 Subject: [PATCH 180/963] Bump gradle-errorprone-plugin from 1.2.1 to 1.3.0 (#2128) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 4b9d861ef7..48f8ad72f5 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { dependencies { classpath 'gradle.plugin.nl.javadude.gradle.plugins:license-gradle-plugin:0.14.0' - classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.2.1' + classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.3.0' //Using buildscript.classpath so that we can resolve plugins from maven local, during local testing classpath "org.shipkit:shipkit-auto-version:0.0.+" From b5523023af894594d462121a3c51acab79b95f88 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2020 18:48:06 +0000 Subject: [PATCH 181/963] Bump google-java-format from 1.8 to 1.9 (#2127) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 48f8ad72f5..ad2d392db5 100644 --- a/build.gradle +++ b/build.gradle @@ -14,7 +14,7 @@ buildscript { classpath "org.shipkit:shipkit-changelog:0.0.+" classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+" - classpath 'com.google.googlejavaformat:google-java-format:1.8' + classpath 'com.google.googlejavaformat:google-java-format:1.9' } } From 1bc6420ee372638a393ceded843ca9a5db5d0170 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2020 18:48:14 +0000 Subject: [PATCH 182/963] Bump kotlinx-coroutines-core from 1.3.7 to 1.4.2-native-mt (#2126) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index ff12cd9cc4..fb77d105e0 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -40,5 +40,5 @@ libraries.kotlin = [ version: kotlinVersion, stdlib: "org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}", - coroutines: 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7', + coroutines: 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2-native-mt', ] From 3b06fccad61e5058ad3113612dca916662f69bc2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2020 19:40:40 +0000 Subject: [PATCH 183/963] Bump biz.aQute.bnd.builder from 5.1.0 to 5.2.0 (#2131) Bumps biz.aQute.bnd.builder from 5.1.0 to 5.2.0. Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index ad2d392db5..ce3945ce5f 100644 --- a/build.gradle +++ b/build.gradle @@ -22,7 +22,7 @@ plugins { id "com.diffplug.gradle.spotless" version "4.5.1" id 'eclipse' id 'com.github.ben-manes.versions' version '0.36.0' - id 'biz.aQute.bnd.builder' version '5.1.0' + id 'biz.aQute.bnd.builder' version '5.2.0' id 'ru.vyarus.animalsniffer' version '1.5.2' } From 14d1952dd874f78903bfbaf196e6f4ec0d35d1ba Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2020 19:41:02 +0000 Subject: [PATCH 184/963] Bump assertj-core from 3.16.1 to 3.18.1 (#2132) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index fb77d105e0..1c15f98758 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -12,7 +12,7 @@ libraries.junit4 = 'junit:junit:4.13.1' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.0' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" -libraries.assertj = 'org.assertj:assertj-core:3.16.1' +libraries.assertj = 'org.assertj:assertj-core:3.18.1' libraries.hamcrest = 'org.hamcrest:hamcrest-core:1.3' libraries.opentest4j = 'org.opentest4j:opentest4j:1.2.0' From d9d5a3270162165f12268a45b977ee144b3dabac Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2020 19:48:08 +0000 Subject: [PATCH 185/963] Bump hamcrest-core from 1.3 to 2.2 (#2129) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 1c15f98758..04387c49a0 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -13,7 +13,7 @@ libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.juni libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.0' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" libraries.assertj = 'org.assertj:assertj-core:3.18.1' -libraries.hamcrest = 'org.hamcrest:hamcrest-core:1.3' +libraries.hamcrest = 'org.hamcrest:hamcrest-core:2.2' libraries.opentest4j = 'org.opentest4j:opentest4j:1.2.0' libraries.bytebuddy = "net.bytebuddy:byte-buddy:${versions.bytebuddy}" From d3795e03d26b34e482606648d35f20456dc8551c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Dec 2020 11:14:15 +0000 Subject: [PATCH 186/963] Bump kotlin-stdlib from 1.4.20 to 1.4.21 (#2137) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 04387c49a0..11a2f22e22 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -35,7 +35,7 @@ libraries.osgi = 'org.osgi:osgi.core:7.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.0' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' -def kotlinVersion = '1.4.20' +def kotlinVersion = '1.4.21' libraries.kotlin = [ version: kotlinVersion, From b34b58b07274cfc77e6673f1ecb8fcd4d5f4278a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Dec 2020 11:15:38 +0000 Subject: [PATCH 187/963] Bump osgi.core from 7.0.0 to 8.0.0 (#2136) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 11a2f22e22..4aaaf431f9 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -31,7 +31,7 @@ libraries.objenesis3 = 'org.objenesis:objenesis:3.1' libraries.asm = 'org.ow2.asm:asm:7.0' -libraries.osgi = 'org.osgi:osgi.core:7.0.0' +libraries.osgi = 'org.osgi:osgi.core:8.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.0' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' From 0b49df76cc43b7c0242dcea132ab30916828fb16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A1bor=20Lipt=C3=A1k?= Date: Tue, 8 Dec 2020 06:18:10 -0500 Subject: [PATCH 188/963] Add void static method mocking example (#2135) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Related to #2027 Signed-off-by: Gábor Lipták --- .../java/org/mockitoinline/StaticMockTest.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java index 2dde8d4a9b..4516583b96 100644 --- a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java @@ -166,10 +166,27 @@ public void testStaticMockMustBeExclusiveInScopeWithinThread() { } } + @Test + public void testStaticMockVoid() { + try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { + Dummy.fooVoid("bar"); + assertNull(Dummy.var1); + dummy.verify(()->Dummy.fooVoid("bar")); + } + Dummy.fooVoid("bar"); + assertEquals("bar", Dummy.var1); + } + static class Dummy { + static String var1 = null; + static String foo() { return "foo"; } + + static void fooVoid(String var2) { + var1 = var2; + } } } From 379e8a5a751002e1ae89685f99c5baaf9f2ec9a1 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Tue, 8 Dec 2020 18:48:12 +0100 Subject: [PATCH 189/963] use GITHUB_TOKEN for shipkit replace hardcoded key and GH_WRITE_TOKEN by built-in GITHUB_TOKEN --- .github/workflows/ci.yml | 2 +- gradle/shipkit.gradle | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5813dfbc77..8eca81f58c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -93,7 +93,7 @@ jobs: run: ./gradlew bintrayUpload githubRelease --scan env: MAVEN_CENTRAL_RELEASE: ${{contains(toJSON(github.event.commits.*.message), '[ci maven-central-release]')}} - GH_WRITE_TOKEN: ${{secrets.GH_WRITE_TOKEN}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} BINTRAY_API_KEY: ${{secrets.BINTRAY_API_KEY}} NEXUS_TOKEN_USER: ${{secrets.NEXUS_TOKEN_USER}} NEXUS_TOKEN_PWD: ${{secrets.NEXUS_TOKEN_PWD}} diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index 2a430fe6f8..eb1dff615c 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -4,7 +4,7 @@ apply plugin: "org.shipkit.shipkit-gh-release" tasks.named("generateChangelog") { previousRevision = "v" + project.ext.'shipkit-auto-version.previous-version' - readOnlyToken = "a0a4c0f41c200f7c653323014d6a72a127764e17" + readOnlyToken = System.getenv("GITHUB_TOKEN") repository = "mockito/mockito" } @@ -13,7 +13,7 @@ tasks.named("githubRelease") { dependsOn genTask repository = genTask.repository changelog = genTask.outputFile - writeToken = System.getenv("GH_WRITE_TOKEN") + writeToken = System.getenv("GITHUB_TOKEN") } /** @@ -40,4 +40,4 @@ static boolean shouldReleaseToCentral(project) { project.tasks.bintrayPublish.doLast { logger.lifecycle(message) } } return centralRelease -} \ No newline at end of file +} From dddcc0a5a73b5dcac9157c591b803b685ca8e167 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Fri, 11 Dec 2020 20:51:51 +0100 Subject: [PATCH 190/963] A little MockitoTestNGListener promotion --- src/main/java/org/mockito/Mockito.java | 8 +++++--- src/main/java/org/mockito/MockitoSession.java | 3 +-- src/main/java/org/mockito/junit/MockitoJUnitRunner.java | 2 +- src/main/java/org/mockito/junit/MockitoRule.java | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 5ed4527680..d0e1a59453 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -1371,9 +1371,11 @@ * * To quickly find out how "stricter" Mockito can make you more productive and get your tests cleaner, see: *

      - *
    • Strict stubbing with JUnit Rules - {@link MockitoRule#strictness(Strictness)} with {@link Strictness#STRICT_STUBS}
    • - *
    • Strict stubbing with JUnit Runner - {@link MockitoJUnitRunner.StrictStubs}
    • - *
    • Strict stubbing if you cannot use runner/rule (like TestNG) - {@link MockitoSession}
    • + *
    • Strict stubbing with JUnit4 Rules - {@link MockitoRule#strictness(Strictness)} with {@link Strictness#STRICT_STUBS}
    • + *
    • Strict stubbing with JUnit4 Runner - {@link MockitoJUnitRunner.Strict}
    • + *
    • Strict stubbing with JUnit5 Extension - org.mockito.junit.jupiter.MockitoExtension
    • + *
    • Strict stubbing with TestNG Listener MockitoTestNGListener
    • + *
    • Strict stubbing if you cannot use runner/rule - {@link MockitoSession}
    • *
    • Unnecessary stubbing detection with {@link MockitoJUnitRunner}
    • *
    • Stubbing argument mismatch warnings, documented in {@link MockitoHint}
    • *
    diff --git a/src/main/java/org/mockito/MockitoSession.java b/src/main/java/org/mockito/MockitoSession.java index 903fd0fdd0..c7989be1fc 100644 --- a/src/main/java/org/mockito/MockitoSession.java +++ b/src/main/java/org/mockito/MockitoSession.java @@ -27,7 +27,6 @@ * otherwise {@link UnfinishedMockingSessionException} is triggered when the next session is created. *

    * {@code MockitoSession} is useful when you cannot use {@link MockitoJUnitRunner} or {@link MockitoRule}. - * For example, you work with TestNG instead of JUnit. * Another example is when different JUnit runner is in use (Jukito, Springockito) * and it cannot be combined with Mockito's own runner. *

    @@ -74,7 +73,7 @@ * If you are JUnit user who does not leverage Mockito rule or runner we strongly recommend to do so. * Both the runner and the rule support strict stubbing which can really help driving cleaner tests. * See {@link MockitoJUnitRunner.StrictStubs} and {@link MockitoRule#strictness(Strictness)}. - * If you cannot use Mockito's JUnit support (for example, you are on TestNG) {@code MockitoSession} exactly is for you! + * If you cannot use Mockito's JUnit support {@code MockitoSession} exactly is for you! * You can automatically take advantage of strict stubbing ({@link Strictness}), * automatic initialization of annotated mocks ({@link MockitoAnnotations}), * and extra validation ({@link Mockito#validateMockitoUsage()}). diff --git a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java index 6951868e68..e41156db2f 100644 --- a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java +++ b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java @@ -69,7 +69,7 @@ * * * If you would like to take advantage of Mockito JUnit runner features - * but you cannot use the runner because, for example, you use TestNG, there is a solution! + * but you cannot use the runner there is a solution! * {@link MockitoSession} API is intended to offer cleaner tests and improved debuggability * to users that cannot use Mockito's built-in JUnit support (runner or the rule). */ diff --git a/src/main/java/org/mockito/junit/MockitoRule.java b/src/main/java/org/mockito/junit/MockitoRule.java index a45314ecc9..0869d012ac 100644 --- a/src/main/java/org/mockito/junit/MockitoRule.java +++ b/src/main/java/org/mockito/junit/MockitoRule.java @@ -67,7 +67,7 @@ * * * If you would like to take advantage of Mockito JUnit rule features - * but you cannot use the rule because, for example, you use TestNG, there is a solution! + * but you cannot use the rule there is a solution! * {@link MockitoSession} API is intended to offer cleaner tests and improved debuggability * to users that cannot use Mockito's built-in JUnit support (runner or the rule). * From 7b7bfb6a785c291a0266f633cf2f961a907b1dee Mon Sep 17 00:00:00 2001 From: Michal Date: Wed, 16 Dec 2020 22:11:30 +0100 Subject: [PATCH 191/963] Applied new Shipkit Auto Version plugin property Shipkit Auto Version Gradle plugin exposes new 'ext' property for getting previous revision: project.ext.'shipkit-auto-version.previous-tag'. This property is easier to use than earlier used 'shipkit-auto-version.previous-version'; using it makes also code clearer. Earlier to get previous revision (e.g. for generating chengelog with Shipkit Changelog plugin) concatenation and possible conditional had to be used. Now it requires just to refer to 'shipkit-auto-version.previous-tag' alone. --- gradle/shipkit.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index eb1dff615c..1c6bbcc99e 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -3,7 +3,7 @@ apply plugin: "org.shipkit.shipkit-changelog" apply plugin: "org.shipkit.shipkit-gh-release" tasks.named("generateChangelog") { - previousRevision = "v" + project.ext.'shipkit-auto-version.previous-version' + previousRevision = project.ext.'shipkit-auto-version.previous-tag' readOnlyToken = System.getenv("GITHUB_TOKEN") repository = "mockito/mockito" } From 6f6a9b8332cc567e93316b064dad3b84b0f92c42 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Dec 2020 07:39:29 +0000 Subject: [PATCH 192/963] Bump org.eclipse.osgi from 3.16.0 to 3.16.100 (#2150) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 4aaaf431f9..ae2e0f3ac1 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -32,7 +32,7 @@ libraries.objenesis3 = 'org.objenesis:objenesis:3.1' libraries.asm = 'org.ow2.asm:asm:7.0' libraries.osgi = 'org.osgi:osgi.core:8.0.0' -libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.0' +libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.100' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' def kotlinVersion = '1.4.21' From a6b0e7cfa4b6045c7c216af038ca394fd6c950a3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 21 Dec 2020 08:15:54 +0000 Subject: [PATCH 193/963] Bump versions.bytebuddy from 1.10.18 to 1.10.19 (#2152) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index ae2e0f3ac1..be1fe57b81 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -4,7 +4,7 @@ ext { def versions = [:] -versions.bytebuddy = '1.10.18' +versions.bytebuddy = '1.10.19' versions.junitJupiter = '5.7.0' versions.errorprone = '2.4.0' From 2e66d086d026b2deef07ea3c979fd972efab960c Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Wed, 30 Dec 2020 13:29:43 -0600 Subject: [PATCH 194/963] Avoid Gradle module files Avoid Gradle module files until there is a use case for them. The less we publish the less complexity. Fixes: #2159 --- gradle/java-publication.gradle | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gradle/java-publication.gradle b/gradle/java-publication.gradle index e7e03d444c..9fa7d62a5c 100644 --- a/gradle/java-publication.gradle +++ b/gradle/java-publication.gradle @@ -25,6 +25,10 @@ artifacts { archives javadocJar } +tasks.withType(GenerateModuleMetadata) { + enabled = false +} + //Gradle Maven publishing plugin configuration (https://docs.gradle.org/current/userguide/publishing_maven.html) apply plugin: "maven-publish" publishing { From e53dd8e7019a5d45c0f69b789595230836c0b1a1 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Wed, 30 Dec 2020 13:37:59 -0600 Subject: [PATCH 195/963] Fixed build on Java 15 Attempted to fix the build by removing dead link that Javadoc generation was complaining about. --- gradle/mockito-core/javadoc.gradle | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/gradle/mockito-core/javadoc.gradle b/gradle/mockito-core/javadoc.gradle index 0ed36bb960..3171895693 100644 --- a/gradle/mockito-core/javadoc.gradle +++ b/gradle/mockito-core/javadoc.gradle @@ -41,8 +41,7 @@ javadoc { options.noNavBar = false options.noTree = false options.links = ['https://docs.oracle.com/javase/6/docs/api/', - 'http://junit.org/junit4/javadoc/4.12/', - 'http://hamcrest.org/JavaHamcrest/javadoc/1.3/'] + 'http://junit.org/junit4/javadoc/4.12/'] options.header("""Mockito ${project.version} API""") options.footer("""Mockito ${project.version} API""") options.bottom(""" From 5f05808bc5f62391ecf1a541747c3a10d91c588b Mon Sep 17 00:00:00 2001 From: Michal Date: Wed, 30 Dec 2020 22:46:57 +0100 Subject: [PATCH 196/963] Apply new Shipkit Changelog plugin properties Two new properties has been recently added to Shipkit Changelog plugin: 1. 'newTagRevision' eliminates problem with wrong tagging, when release is tagged with revision reference that the release doesn't come from, but is the latest one on master branch. To get the commit SHA that triggered the workflow 'GITHUB_SHA' env var is used. 2. 'githubToken' is used to both to fetch and post, instead of 'readOnlyToken' and 'writeToken'. As the token grants write access to the repository to keep things safe it should be supplied by the env variable. Using this property simplifies configuration. Deprecated properties should be replaced with the new one. --- gradle/shipkit.gradle | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index 1c6bbcc99e..7957191ac8 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -4,7 +4,7 @@ apply plugin: "org.shipkit.shipkit-gh-release" tasks.named("generateChangelog") { previousRevision = project.ext.'shipkit-auto-version.previous-tag' - readOnlyToken = System.getenv("GITHUB_TOKEN") + githubToken = System.getenv("GITHUB_TOKEN") repository = "mockito/mockito" } @@ -13,7 +13,8 @@ tasks.named("githubRelease") { dependsOn genTask repository = genTask.repository changelog = genTask.outputFile - writeToken = System.getenv("GITHUB_TOKEN") + newTagRevision = System.getenv("GITHUB_SHA") + githubToken = System.getenv("GITHUB_TOKEN") } /** From 72d3a1002d9684ec2e332fbb2b8c5a18cce20173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotrek=20=C5=BBygie=C5=82o?= Date: Wed, 30 Dec 2020 15:11:17 +0100 Subject: [PATCH 197/963] Add field type in @Mock example --- src/main/java/org/mockito/Mock.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/Mock.java b/src/main/java/org/mockito/Mock.java index cb5bfba157..8b8132000e 100644 --- a/src/main/java/org/mockito/Mock.java +++ b/src/main/java/org/mockito/Mock.java @@ -32,7 +32,7 @@ * @Mock private ArticleCalculator calculator; * @Mock(name = "database") private ArticleDatabase dbMock; * @Mock(answer = RETURNS_MOCKS) private UserProvider userProvider; - * @Mock(extraInterfaces = {Queue.class, Observer.class}) private articleMonitor; + * @Mock(extraInterfaces = {Queue.class, Observer.class}) private ArticleMonitor articleMonitor; * @Mock(stubOnly = true) private Logger logger; * * private ArticleManager manager; From 6ade10a7963976d0440de8a738f0e947d6577937 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Wed, 30 Dec 2020 17:42:31 -0600 Subject: [PATCH 198/963] Bumped version of Shipkit plugins --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index ce3945ce5f..c53b0554d9 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,8 @@ buildscript { classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.3.0' //Using buildscript.classpath so that we can resolve plugins from maven local, during local testing - classpath "org.shipkit:shipkit-auto-version:0.0.+" - classpath "org.shipkit:shipkit-changelog:0.0.+" + classpath "org.shipkit:shipkit-auto-version:0.+" + classpath "org.shipkit:shipkit-changelog:0.+" classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+" classpath 'com.google.googlejavaformat:google-java-format:1.9' From 1da75c2d6b4d42d751c31441f8bba4651e106a10 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 3 Jan 2021 19:14:46 +0000 Subject: [PATCH 199/963] Fix in the Javadoc for "Mocking object construction" (#2145) This is a suggestion for changing the documentation for "Mocking object construction". Previously, the documentation has suggested that MockedConstruction can define mock behavior and to verify static method invocations. However, it is meant for defining mock behavior and verifying non-static method invocations. --- src/main/java/org/mockito/Mockito.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 5ed4527680..e14af0c654 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -1582,7 +1582,7 @@ * * * Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is - * released. To define mock behavior and to verify static method invocations, use the MockedConstruction that is returned. + * released. To define mock behavior and to verify method invocations, use the MockedConstruction that is returned. *

    */ @SuppressWarnings("unchecked") From 240d6e4b8eb3954cdd3285e345c6f8982bb76796 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Raymond=20Aug=C3=A9?= Date: Sun, 3 Jan 2021 14:18:14 -0500 Subject: [PATCH 200/963] Make mockito-junit-jupiter work with JUnit 5 in OSGi integration tests (#2047) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This solution does not: a) give up the internal nature of some packages b) resort to substandard solutions like OSGi fragments Fixes #1997 Signed-off-by: Raymond Augé --- gradle/mockito-core/osgi.gradle | 99 +------------------ .../junit-jupiter/junit-jupiter.gradle | 45 +++++++++ 2 files changed, 49 insertions(+), 95 deletions(-) diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle index 2fa0b78354..0c6f395e8b 100644 --- a/gradle/mockito-core/osgi.gradle +++ b/gradle/mockito-core/osgi.gradle @@ -1,12 +1,3 @@ -import java.nio.file.attribute.FileTime -import java.util.jar.Attributes -import java.util.jar.JarEntry -import java.util.jar.JarFile -import java.util.jar.JarOutputStream -import java.util.jar.Manifest - -import static java.util.Calendar.FEBRUARY - apply plugin: 'biz.aQute.bnd.builder' jar { @@ -14,9 +5,9 @@ jar { bnd( 'Bundle-Name': 'Mockito Mock Library for Java. Core bundle requires Byte Buddy and Objenesis.', 'Bundle-SymbolicName': 'org.mockito.mockito-core', - 'Bundle-Version': project.version.replace('-', '.'), + 'Bundle-Version': "\${version_cleanup;${project.version}}", '-versionpolicy': '[${version;==;${@}},${version;+;${@}})', - 'Export-Package': "!org.mockito.internal.*,org.mockito.*;version=${version}", + 'Export-Package': "org.mockito.internal.*;status=INTERNAL;mandatory:=status;version=${version},org.mockito.*;version=${version}", 'Import-Package': [ 'net.bytebuddy.*;version="[1.6.0,2.0)"', 'junit.*;resolution:=optional', @@ -27,89 +18,7 @@ jar { 'org.mockito.*' ].join(','), '-removeheaders': 'Private-Package', - 'Automatic-Module-Name': 'org.mockito' + 'Automatic-Module-Name': 'org.mockito', + '-noextraheaders': 'true' ) } - -jar.doLast { - JarFile originalJar = new JarFile(jar.archivePath) - - new RemoveOsgiLastModifiedHeader(originalJar) - .transform() - .renameTo jar.archivePath -} - - -/* - * The OSGi plugin in Gradle 5.3 has a known issue (https://github.com/gradle/gradle/issues/6187) where it embeds - * a Manifest entry "Bnd-LastModified" (set to the last modified time of the build directory) even if you ask it not to - * using `-noextraheaders` or `-removeheaders`. - * - * It cannot be pinned or removed, and is a source of non-determinism in the build. - * - * This class addresses the problem by rewriting the JAR and removing that entry from the Manifest. A side-effect of this - * is having to set `lastModifiedTime` for each entry to a fixed value, else this would also introduce non-determinism. - * - * The fixed value is the same as the default value for Gradle's fixed timestamps, and the rationale behind it is detailed - * in https://github.com/gradle/gradle/blob/58538513a3bff3b7015718976fe1304e23f40694/subprojects/core/src/main/java/org/gradle/api/internal/file/archive/ZipCopyAction.java#L42-L57 - */ - -class RemoveOsgiLastModifiedHeader { - private final long CONSTANT_TIME_FOR_ZIP_ENTRIES = new GregorianCalendar(1980, FEBRUARY, 1, 0, 0, 0).timeInMillis - - private final JarFile artifact - - RemoveOsgiLastModifiedHeader(JarFile artifact) { - this.artifact = artifact - } - - File transform() { - File temp = File.createTempFile("temp",".jar") - - temp.withOutputStream { os -> - JarOutputStream stream = new JarOutputStream(os) - - this.artifact - .entries() - // Keep META-INF folder at the beginning to avoid https://github.com/mockito/mockito/issues/2108 - .sort { (it.name.startsWith("META-INF") ? "A/" + it.name : "B/" + it.name) } - .each { JarEntry entry -> - - stream.putNextEntry(newJarEntry(entry)) - - if (entry.name == "META-INF/MANIFEST.MF") { - newManifest(entry).write(stream) - } else { - stream << this.artifact.getInputStream(entry) - } - - stream.closeEntry() - } - - stream.finish() - } - - temp - } - - Manifest newManifest(JarEntry entry) { - Manifest manifest = new Manifest() - - manifest.read(this.artifact.getInputStream(entry)) - - manifest - .getMainAttributes() - .remove(new Attributes.Name("Bnd-LastModified")) - - manifest - } - - JarEntry newJarEntry(JarEntry original) { - JarEntry newEntry = new JarEntry(original.name) - - newEntry.setLastModifiedTime(FileTime.fromMillis(CONSTANT_TIME_FOR_ZIP_ENTRIES)) - - newEntry - } - -} diff --git a/subprojects/junit-jupiter/junit-jupiter.gradle b/subprojects/junit-jupiter/junit-jupiter.gradle index 7cfc0b7de1..6e24b6a861 100644 --- a/subprojects/junit-jupiter/junit-jupiter.gradle +++ b/subprojects/junit-jupiter/junit-jupiter.gradle @@ -1,6 +1,11 @@ +import aQute.bnd.gradle.BundleTaskConvention +import aQute.bnd.gradle.FileSetRepositoryConvention +import aQute.bnd.gradle.Resolve + description = "Mockito JUnit 5 support" apply from: "$rootDir/gradle/java-library.gradle" +apply plugin: 'biz.aQute.bnd.builder' dependencies { compile project.rootProject @@ -13,3 +18,43 @@ dependencies { tasks.withType(Test) { useJUnitPlatform() } + +jar { + classpath = project.configurations.runtimeClasspath + bnd( + 'Bundle-Name': 'Mockito Extension Library for JUnit 5.', + 'Bundle-SymbolicName': 'org.mockito.junit-jupiter', + 'Bundle-Version': "\${version_cleanup;${project.version}}", + '-versionpolicy': '[${version;==;${@}},${version;+;${@}})', + 'Export-Package': "org.mockito.junit.jupiter.*;version=${version}", + '-removeheaders': 'Private-Package', + 'Automatic-Module-Name': 'org.mockito.junit.jupiter', + '-noextraheaders': 'true', + '-export-apiguardian': 'org.mockito.internal.*' + ) +} + +def osgiPropertiesFile = file("$buildDir/verifyOSGiProperties.bndrun") + +// Bnd's Resolve task uses a properties file for its configuration. This +// task writes out the properties necessary for it to verify the OSGi +// metadata. +tasks.register('osgiProperties', WriteProperties) { + outputFile = osgiPropertiesFile + property('-standalone', true) + property('-runee', "JavaSE-${targetCompatibility}") + property('-runrequires', 'osgi.identity;filter:="(osgi.identity=org.mockito.junit-jupiter)"') +} + +// Bnd's Resolve task is what verifies that a jar can be used in OSGi and +// that its metadata is valid. If the metadata is invalid this task will +// fail. +tasks.register('verifyOSGi', Resolve) { + dependsOn(osgiProperties) + setBndrun(osgiPropertiesFile) + reportOptional = false +} + +tasks.check { + dependsOn(verifyOSGi) +} From 32eb7e490233ac36d54fe1d79975f8df704f756e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 3 Jan 2021 19:18:43 +0000 Subject: [PATCH 201/963] Bump kotlin-stdlib from 1.4.21 to 1.4.21-2 (#2157) Bumps [kotlin-stdlib](https://github.com/JetBrains/kotlin) from 1.4.21 to 1.4.21-2. - [Release notes](https://github.com/JetBrains/kotlin/releases) - [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog-1.3.X.md) - [Commits](https://github.com/JetBrains/kotlin/commits) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index be1fe57b81..79808ad5ab 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -35,7 +35,7 @@ libraries.osgi = 'org.osgi:osgi.core:8.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.100' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' -def kotlinVersion = '1.4.21' +def kotlinVersion = '1.4.21-2' libraries.kotlin = [ version: kotlinVersion, From 0fb7ef58fbe46044ce76c42f37ee8234a3379d6a Mon Sep 17 00:00:00 2001 From: Tim van der Lippe Date: Mon, 4 Jan 2021 12:55:18 +0000 Subject: [PATCH 202/963] Publish new minor version to Maven central [ci maven-central-release] --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index 68dab810c7..84772019f6 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ # Used by Shipkit Auto Version Gradle plugin: https://github.com/shipkit/shipkit-auto-version -version=3.6.* \ No newline at end of file +version=3.7.* From b90c3da04db60be226396f94473f31e5d11b40c1 Mon Sep 17 00:00:00 2001 From: Michal Szestowicki Date: Tue, 5 Jan 2021 16:33:19 +0100 Subject: [PATCH 203/963] Apply renamed plugin package Due to recent Github related naming convention applied in Shipkit Changelog plugin, the referenced 'org.shipkit.shipkit-gh-release' package should be changed for 'org.shipkit.shipkit-github-release'. --- gradle/shipkit.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle index 7957191ac8..f14617aad8 100644 --- a/gradle/shipkit.gradle +++ b/gradle/shipkit.gradle @@ -1,6 +1,6 @@ apply plugin: "org.shipkit.shipkit-auto-version" apply plugin: "org.shipkit.shipkit-changelog" -apply plugin: "org.shipkit.shipkit-gh-release" +apply plugin: "org.shipkit.shipkit-github-release" tasks.named("generateChangelog") { previousRevision = project.ext.'shipkit-auto-version.previous-tag' From 2cbd284469bf4c6f6e8f7bd3aeb00024575e6b7c Mon Sep 17 00:00:00 2001 From: Michal Szestowicki Date: Sun, 10 Jan 2021 19:36:59 +0100 Subject: [PATCH 204/963] Bumped Shipkit plugins versions Recently new versions of Shipkit Auto Version and Shipkit Changelog were published. The plugins' versions in the project can now be bumped. --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index c53b0554d9..97ad8e7d39 100644 --- a/build.gradle +++ b/build.gradle @@ -10,8 +10,8 @@ buildscript { classpath 'net.ltgt.gradle:gradle-errorprone-plugin:1.3.0' //Using buildscript.classpath so that we can resolve plugins from maven local, during local testing - classpath "org.shipkit:shipkit-auto-version:0.+" - classpath "org.shipkit:shipkit-changelog:0.+" + classpath "org.shipkit:shipkit-auto-version:1.1.1" + classpath "org.shipkit:shipkit-changelog:1.1.1" classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+" classpath 'com.google.googlejavaformat:google-java-format:1.9' From 5bf62a389c242364ec87d200ae845aba0ea5a721 Mon Sep 17 00:00:00 2001 From: Szczepan Faber Date: Mon, 11 Jan 2021 10:19:41 -0600 Subject: [PATCH 205/963] Travis -> GH Actions Removed Travis configuration file as we have moved to GH Actions --- .travis.yml | 66 ----------------------------------------------------- 1 file changed, 66 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 8cbbd48314..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,66 +0,0 @@ -# -# TRAVIS BUILD IS DEPRECATED -# -# WE ARE MOVING TO GH ACTIONS -# -# PLEASE DO NOT UPDATE THIS FILE ANY MORE -# -# This file can be removed once we have enough builds with GH Actions, likely Jan'21 -# See: https://github.com/mockito/mockito/issues/2080 -# - -# Speed up build by leveraging travis caches -cache: - directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ - -# Enabling container based infrastructure hoping it will help the build speed <= this didn't work well, so it's reverted -# see https://docs.travis-ci.com/user/migrating-from-legacy/ and https://docs.travis-ci.com/user/ci-environment -sudo: true - -language: java - -dist: trusty - -matrix: - include: - - jdk: openjdk8 - - jdk: openjdk8 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk11 - env: SKIP_RELEASE=true - - jdk: openjdk11 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - - jdk: openjdk15 - env: SKIP_RELEASE=true - - jdk: openjdk15 - env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline - # Run Spotless as a separate job on JDK 11 (which is required for google-java-format) - - jdk: openjdk11 - name: "Verify code formatting with Spotless. Run './gradlew spotlessApply' locally if this job fails." - script: ./gradlew spotlessCheck - # Do not upload a coverage report, as we don't run the tests for this job - after_success: true - - jdk: openjdk8 - name: "Check reproducibility of jars" - script: ./check_reproducibility.sh - # Do not upload a coverage report, as we don't run the tests for this job - after_success: true - -branches: - #Don't build tags - except: - - /^v\d/ - -#Below skips the installation step completely (https://docs.travis-ci.com/user/customizing-the-build/#Skipping-the-Installation-Step) -#We need it because otherwise Travis CI injects an awkward './gradlew assemble' step into the CI workflow -#We want to control and decide what Gradle tasks are executed -install: - - true - -script: - # To validate changes, we run building and bintray upload in dry run, and idea task. This happens on every build, even PRs. - # To publish, we perform github release and perform bintray upload (no dry run). This only for main branch builds. - - > - ./gradlew build bintrayUpload idea --scan -PbintrayDryRun From 09bfe5ba2b2acbbd484bb16b989516e9a346b2c0 Mon Sep 17 00:00:00 2001 From: Per Lundberg Date: Fri, 15 Jan 2021 13:03:37 +0200 Subject: [PATCH 206/963] Fix grammar in ArgumentMatchers JavaDoc (#2175) --- .../java/org/mockito/ArgumentMatchers.java | 40 +++++++++---------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java index cb75e2cf16..7d6184d1db 100644 --- a/src/main/java/org/mockito/ArgumentMatchers.java +++ b/src/main/java/org/mockito/ArgumentMatchers.java @@ -181,7 +181,7 @@ public static T anyObject() { *

    * Since Mockito 2.1.0, only allow non-null instance of , thus null is not anymore a valid value. * As reference are nullable, the suggested API to match null - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -268,7 +268,7 @@ public static T anyVararg() { *

    * Since Mockito 2.1.0, only allow valued Boolean, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -291,7 +291,7 @@ public static boolean anyBoolean() { *

    * Since Mockito 2.1.0, only allow valued Byte, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -314,7 +314,7 @@ public static byte anyByte() { *

    * Since Mockito 2.1.0, only allow valued Character, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -337,7 +337,7 @@ public static char anyChar() { *

    * Since Mockito 2.1.0, only allow valued Integer, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -360,7 +360,7 @@ public static int anyInt() { *

    * Since Mockito 2.1.0, only allow valued Long, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -383,7 +383,7 @@ public static long anyLong() { *

    * Since Mockito 2.1.0, only allow valued Float, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -406,7 +406,7 @@ public static float anyFloat() { *

    * Since Mockito 2.1.0, only allow valued Double, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -429,7 +429,7 @@ public static double anyDouble() { *

    * Since Mockito 2.1.0, only allow valued Short, thus null is not anymore a valid value. * As primitive wrappers are nullable, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -452,7 +452,7 @@ public static short anyShort() { *

    * Since Mockito 2.1.0, only allow non-null String. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -475,7 +475,7 @@ public static String anyString() { *

    * Since Mockito 2.1.0, only allow non-null List. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -507,7 +507,7 @@ public static List anyList() { *

    * Since Mockito 2.1.0, only allow non-null List. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -534,7 +534,7 @@ public static List anyListOf(Class clazz) { *

    * Since Mockito 2.1.0, only allow non-null Set. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -568,7 +568,7 @@ public static Set anySet() { *

    * Since Mockito 2.1.0, only allow non-null Set. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -595,7 +595,7 @@ public static Set anySetOf(Class clazz) { *

    * Since Mockito 2.1.0, only allow non-null Map. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -629,7 +629,7 @@ public static Map anyMap() { *

    * Since Mockito 2.1.0, only allow non-null Map. * As this is a nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -657,7 +657,7 @@ public static Map anyMapOf(Class keyClazz, Class valueClazz) *

    * Since Mockito 2.1.0, only allow non-null Collection. * As this is a nullable reference, the suggested API to match null - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -691,7 +691,7 @@ public static Collection anyCollection() { *

    * Since Mockito 2.1.0, only allow non-null Collection. * As this is a nullable reference, the suggested API to match null - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -718,7 +718,7 @@ public static Collection anyCollectionOf(Class clazz) { *

    * Since Mockito 2.1.0, only allow non-null Iterable. * As this is a nullable reference, the suggested API to match null - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * @@ -753,7 +753,7 @@ public static Iterable anyIterable() { *

    * Since Mockito 2.1.0, only allow non-null String. * As strings are nullable reference, the suggested API to match null wrapper - * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito + * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. *

    * From 79f06bae95074c7c6d8ce862db100ab74edddf6e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 15 Jan 2021 12:08:26 +0000 Subject: [PATCH 207/963] Bump versions.errorprone from 2.4.0 to 2.5.1 (#2176) * Bump versions.errorprone from 2.4.0 to 2.5.1 Bumps `versions.errorprone` from 2.4.0 to 2.5.1. Updates `error_prone_core` from 2.4.0 to 2.5.1 - [Release notes](https://github.com/google/error-prone/releases) - [Commits](https://github.com/google/error-prone/compare/v2.4.0...v2.5.1) Updates `error_prone_test_helpers` from 2.4.0 to 2.5.1 - [Release notes](https://github.com/google/error-prone/releases) - [Commits](https://github.com/google/error-prone/compare/v2.4.0...v2.5.1) Signed-off-by: dependabot[bot] * Fix ErrorProne compilation errors Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Tim van der Lippe --- gradle/dependencies.gradle | 2 +- .../ByteBuddyCrossClassLoaderSerializationSupport.java | 2 ++ .../mockito/internal/creation/bytebuddy/MockMethodAdvice.java | 2 +- .../bugpatterns/AbstractMockitoAnyForPrimitiveType.java | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 79808ad5ab..25a41b3311 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -6,7 +6,7 @@ def versions = [:] versions.bytebuddy = '1.10.19' versions.junitJupiter = '5.7.0' -versions.errorprone = '2.4.0' +versions.errorprone = '2.5.1' libraries.junit4 = 'junit:junit:4.13.1' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" 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 90ccee882c..76aadc80e5 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyCrossClassLoaderSerializationSupport.java @@ -193,6 +193,7 @@ public CrossClassLoaderSerializationProxy(Object mockitoMock) throws IOException * @return A deserialized instance of the Mockito mock. * @throws java.io.ObjectStreamException */ + @SuppressWarnings("BanSerializableRead") private Object readResolve() throws ObjectStreamException { try { ByteArrayInputStream bis = new ByteArrayInputStream(serializedMock); @@ -267,6 +268,7 @@ public MockitoMockObjectInputStream( * @throws ClassNotFoundException */ @Override + @SuppressWarnings("BanSerializableRead") protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (notMarkedAsAMockitoMock(readObject())) { 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 9323368a14..1d9dcba590 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java @@ -744,7 +744,7 @@ private static void exit( public static class ForReadObject { - @SuppressWarnings("unused") + @SuppressWarnings({"unused", "BanSerializableRead"}) public static void doReadObject( @Identifier String identifier, @This MockAccess thiz, diff --git a/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/AbstractMockitoAnyForPrimitiveType.java b/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/AbstractMockitoAnyForPrimitiveType.java index 3d14b4eaad..f23f9ed836 100644 --- a/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/AbstractMockitoAnyForPrimitiveType.java +++ b/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/AbstractMockitoAnyForPrimitiveType.java @@ -70,7 +70,7 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState } if (argumentIndex == -1) { throw new IllegalStateException( - "Cannot find argument " + tree + " in argument list from " + parentTree); + "Cannot find argument " + state.getSourceForNode(tree) + " in argument list from " + state.getSourceForNode(parentTree)); } Type parameterType = getParameterType(parentMethod, argumentIndex); From 7b940bcead5240bd030bbe7acbb51c10be0a452b Mon Sep 17 00:00:00 2001 From: Stefan Bohn Date: Sat, 16 Jan 2021 11:14:06 +0100 Subject: [PATCH 208/963] Fix reversed order of verify parameters (#2179) For consistency, the parameters of the method `MockedStatic.verify(VerificationMode, Verification)` have been swapped to `MockedStatic.verify(Verification, VerificationMode)` as this order is already used in `Mockito.verify(T, VerificationMode)`. Fixes: #2173 [ci maven-central-release] --- src/main/java/org/mockito/MockedStatic.java | 9 ++++++++- src/main/java/org/mockito/internal/MockedStaticImpl.java | 5 +++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/mockito/MockedStatic.java b/src/main/java/org/mockito/MockedStatic.java index ac291ba33c..b1089cdbf0 100644 --- a/src/main/java/org/mockito/MockedStatic.java +++ b/src/main/java/org/mockito/MockedStatic.java @@ -35,14 +35,21 @@ public interface MockedStatic extends ScopedMock { * See {@link Mockito#verify(Object)}. */ default void verify(Verification verification) { - verify(times(1), verification); + verify(verification, times(1)); } /** * See {@link Mockito#verify(Object, VerificationMode)}. + * + * @deprecated Please use {@link MockedStatic#verify(Verification, VerificationMode) instead */ void verify(VerificationMode mode, Verification verification); + /** + * See {@link Mockito#verify(Object, VerificationMode)}. + */ + void verify(Verification verification, VerificationMode mode); + /** * See {@link Mockito#reset(Object[])}. */ diff --git a/src/main/java/org/mockito/internal/MockedStaticImpl.java b/src/main/java/org/mockito/internal/MockedStaticImpl.java index 7c3af584eb..0c9456e030 100644 --- a/src/main/java/org/mockito/internal/MockedStaticImpl.java +++ b/src/main/java/org/mockito/internal/MockedStaticImpl.java @@ -61,6 +61,11 @@ public OngoingStubbing when(Verification verification) { @Override public void verify(VerificationMode mode, Verification verification) { + verify(verification, mode); + } + + @Override + public void verify(Verification verification, VerificationMode mode) { assertNotClosed(); MockingDetails mockingDetails = Mockito.mockingDetails(control.getType()); From 0630886363bb657d965cfa318ea205c79733afee Mon Sep 17 00:00:00 2001 From: Kim In Hoi <31230862+hotire@users.noreply.github.com> Date: Sun, 17 Jan 2021 22:52:45 +0900 Subject: [PATCH 209/963] Fix typo in Javadocs of MockedConstruction (#2180) --- src/main/java/org/mockito/Mockito.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 000577b4ad..9d20b43bae 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -1573,14 +1573,14 @@ * In the following example, the Foo type's construction would generate a mock: * *
    
    - * assertEquals("foo", Foo.method());
    + * assertEquals("foo", new Foo().method());
      * try (MockedConstruction mocked = mockConstruction(Foo.class)) {
      * Foo foo = new Foo();
      * when(foo.method()).thenReturn("bar");
      * assertEquals("bar", foo.method());
      * verify(foo).method();
      * }
    - * assertEquals("foo", foo.method());
    + * assertEquals("foo", new Foo().method());
      * 
    * * Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is From fbe50583ad5e66087be58d0a8ad28a079ffc72d6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 27 Jan 2021 19:35:37 +0000 Subject: [PATCH 210/963] Bump assertj-core from 3.18.1 to 3.19.0 (#2189) Bumps [assertj-core](https://github.com/assertj/assertj-core) from 3.18.1 to 3.19.0. - [Release notes](https://github.com/assertj/assertj-core/releases) - [Commits](https://github.com/assertj/assertj-core/compare/assertj-core-3.18.1...assertj-core-3.19.0) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 25a41b3311..519aed70f1 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -12,7 +12,7 @@ libraries.junit4 = 'junit:junit:4.13.1' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.0' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" -libraries.assertj = 'org.assertj:assertj-core:3.18.1' +libraries.assertj = 'org.assertj:assertj-core:3.19.0' libraries.hamcrest = 'org.hamcrest:hamcrest-core:2.2' libraries.opentest4j = 'org.opentest4j:opentest4j:1.2.0' From 8a19d46c19fc00c56bfcaa01274bb2195d9ac6fe Mon Sep 17 00:00:00 2001 From: Jan Mosig Date: Mon, 1 Feb 2021 20:25:14 +0100 Subject: [PATCH 211/963] Fixes #2154 : instrument java.lang.Object to fix toString invocations on inline mocks (#2193) --- .../bytebuddy/InlineBytecodeGenerator.java | 3 --- .../bytebuddy/InlineByteBuddyMockMakerTest.java | 14 ++++++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) 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 5fc47cd7cb..7db8afe97f 100644 --- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java +++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java @@ -269,9 +269,6 @@ private void triggerRetransformation(Set> types, boolean flat) { throw t; } - // The object type does not ever need instrumentation. - targets.remove(Object.class); - if (!targets.isEmpty()) { try { assureCanReadMockito(targets); 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 bfc16b4d15..dfa6d8192f 100644 --- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java +++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java @@ -220,6 +220,20 @@ public void should_mock_interface_to_string() { assertThat(proxy.toString()).isEqualTo("foo"); } + /** + * @see https://github.com/mockito/mockito/issues/2154 + */ + @Test + public void should_mock_class_to_string() { + MockSettingsImpl mockSettings = new MockSettingsImpl(); + mockSettings.setTypeToMock(Object.class); + mockSettings.defaultAnswer(new Returns("foo")); + Object proxy = + mockMaker.createMock(mockSettings, new MockHandlerImpl(mockSettings)); + + assertThat(proxy.toString()).isEqualTo("foo"); + } + @Test public void should_remove_recursive_self_call_from_stack_trace() throws Exception { StackTraceElement[] stack = From 780cfc18b06e82cf6592fc5f250b2e52f6f6a9e6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 Feb 2021 22:35:39 +0000 Subject: [PATCH 212/963] Bump shipkit-changelog from 1.1.1 to 1.1.4 (#2190) --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 97ad8e7d39..e672d9ec75 100644 --- a/build.gradle +++ b/build.gradle @@ -11,7 +11,7 @@ buildscript { //Using buildscript.classpath so that we can resolve plugins from maven local, during local testing classpath "org.shipkit:shipkit-auto-version:1.1.1" - classpath "org.shipkit:shipkit-changelog:1.1.1" + classpath "org.shipkit:shipkit-changelog:1.1.4" classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.+" classpath 'com.google.googlejavaformat:google-java-format:1.9' From 7745992ae91751df134b7ea09e1ef1ca4d39242a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 4 Feb 2021 15:31:14 +0000 Subject: [PATCH 213/963] Bump kotlin-stdlib from 1.4.21-2 to 1.4.30 (#2196) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 519aed70f1..4decd82a02 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -35,7 +35,7 @@ libraries.osgi = 'org.osgi:osgi.core:8.0.0' libraries.equinox = 'org.eclipse.platform:org.eclipse.osgi:3.16.100' libraries.bndGradle = 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.2.0' -def kotlinVersion = '1.4.21-2' +def kotlinVersion = '1.4.30' libraries.kotlin = [ version: kotlinVersion, From 43facffb6861bb73c41560c39ba5aaa592a452fc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 4 Feb 2021 15:31:32 +0000 Subject: [PATCH 214/963] Bump versions.bytebuddy from 1.10.19 to 1.10.20 (#2195) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 4decd82a02..49791c1a63 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -4,7 +4,7 @@ ext { def versions = [:] -versions.bytebuddy = '1.10.19' +versions.bytebuddy = '1.10.20' versions.junitJupiter = '5.7.0' versions.errorprone = '2.5.1' From 632a0c829a9d9fe6f55d89e4f4593a3d76a6d4cc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 5 Feb 2021 11:43:56 +0000 Subject: [PATCH 215/963] Bump versions.junitJupiter from 5.7.0 to 5.7.1 (#2199) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 49791c1a63..ca6963a0d3 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -5,7 +5,7 @@ ext { def versions = [:] versions.bytebuddy = '1.10.20' -versions.junitJupiter = '5.7.0' +versions.junitJupiter = '5.7.1' versions.errorprone = '2.5.1' libraries.junit4 = 'junit:junit:4.13.1' From 3bffcd0e8f9e1e0fe5678a99e7e9f37426e10635 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 5 Feb 2021 11:44:09 +0000 Subject: [PATCH 216/963] Bump junit-platform-launcher from 1.7.0 to 1.7.1 (#2198) --- gradle/dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index ca6963a0d3..7d996e9b1b 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -10,7 +10,7 @@ versions.errorprone = '2.5.1' libraries.junit4 = 'junit:junit:4.13.1' libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}" -libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.0' +libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.7.1' libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}" libraries.assertj = 'org.assertj:assertj-core:3.19.0' libraries.hamcrest = 'org.hamcrest:hamcrest-core:2.2' From e88fe26110afd6641c464cb0e87bd898b41bf457 Mon Sep 17 00:00:00 2001 From: Rafael Winterhalter Date: Thu, 11 Feb 2021 20:12:41 +0100 Subject: [PATCH 217/963] Add API for clearing mocks. (#2194) By clearing mocks, caches are emptied and instrumentations are reversed. --- src/main/java/org/mockito/Mockito.java | 11 +++++++++ .../org/mockito/internal/MockitoCore.java | 5 ++++ .../bytebuddy/ByteBuddyMockMaker.java | 5 ++++ .../creation/bytebuddy/BytecodeGenerator.java | 2 ++ .../bytebuddy/InlineByteBuddyMockMaker.java | 6 +++++ .../bytebuddy/InlineBytecodeGenerator.java | 23 ++++++++++++++++++ .../bytebuddy/SubclassByteBuddyMockMaker.java | 5 ++++ .../TypeCachingBytecodeGenerator.java | 18 ++++++++++++++ .../org/mockito/internal/util/MockUtil.java | 4 ++++ .../java/org/mockito/plugins/MockMaker.java | 6 +++++ .../java/org/mockito/MockitoClearTest.java | 24 +++++++++++++++++++ .../creation/AndroidByteBuddyMockMaker.java | 5 ++++ 12 files changed, 114 insertions(+) create mode 100644 src/test/java/org/mockito/MockitoClearTest.java diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java index 9d20b43bae..336251e0ae 100644 --- a/src/main/java/org/mockito/Mockito.java +++ b/src/main/java/org/mockito/Mockito.java @@ -2461,6 +2461,17 @@ public static void reset(T... mocks) { MOCKITO_CORE.reset(mocks); } + /** + * Clears all mocks, type caches and instrumentations. + *

    + * By clearing Mockito's state, previously created mocks might begin to malfunction. This option can be used if + * Mockito's caches take up too much space or if the inline mock maker's instrumentation is causing performance + * issues in code where mocks are no longer used. Normally, you would not need to use this option. + */ + public static void clearAllCaches() { + MOCKITO_CORE.clearAllCaches(); + } + /** * Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be: *