Revert "Update to Mockito v2.25.7." am: 49ce6eaa60
am: 3cd6a51d47
Change-Id: I758d908273580a00d1fdb273ab27de0df65225e7
diff --git a/Android.bp b/Android.bp
index d03df66..6ddcead 100644
--- a/Android.bp
+++ b/Android.bp
@@ -28,10 +28,6 @@
"objenesis",
],
- static_libs: [
- "mockito-opentest4j",
- ],
-
target: {
android: {
// Exclude source used to dynamically create classes since target builds use
@@ -78,23 +74,15 @@
java_resource_dirs: ["subprojects/inline/src/main/resources"],
}
-// Common dependencies for both target and host.
-// ===========================================================
-java_import {
- name: "mockito-opentest4j",
- host_supported: true,
- jars: ["lib/opentest4j-1.1.1.jar"],
-}
-
// Host prebuilt dependencies.
// ============================================================
java_import_host {
name: "mockito-byte-buddy",
- jars: ["lib/byte-buddy-1.9.10.jar"],
+ jars: ["lib/byte-buddy-1.8.15.jar"],
}
java_import_host {
name: "mockito-byte-buddy-agent",
- jars: ["lib/byte-buddy-agent-1.9.10.jar"],
+ jars: ["lib/byte-buddy-agent-1.8.15.jar"],
}
diff --git a/README.version b/README.version
index 5946c24..35f650c 100644
--- a/README.version
+++ b/README.version
@@ -1,5 +1,5 @@
URL: https://github.com/mockito/mockito
-Version: v2.25.7
+Version: v2.21.0
License: Apache 2.0
Description: Mockito is a mocking framework with a clean and simple API.
diff --git a/lib/byte-buddy-1.8.15-sources.jar b/lib/byte-buddy-1.8.15-sources.jar
new file mode 100644
index 0000000..523015e
--- /dev/null
+++ b/lib/byte-buddy-1.8.15-sources.jar
Binary files differ
diff --git a/lib/byte-buddy-1.8.15.jar b/lib/byte-buddy-1.8.15.jar
new file mode 100644
index 0000000..b8c8379
--- /dev/null
+++ b/lib/byte-buddy-1.8.15.jar
Binary files differ
diff --git a/lib/byte-buddy-1.9.10.jar.txt b/lib/byte-buddy-1.8.15.jar.txt
similarity index 100%
rename from lib/byte-buddy-1.9.10.jar.txt
rename to lib/byte-buddy-1.8.15.jar.txt
diff --git a/lib/byte-buddy-1.9.10-sources.jar b/lib/byte-buddy-1.9.10-sources.jar
deleted file mode 100644
index 8ceb22e..0000000
--- a/lib/byte-buddy-1.9.10-sources.jar
+++ /dev/null
Binary files differ
diff --git a/lib/byte-buddy-1.9.10.jar b/lib/byte-buddy-1.9.10.jar
deleted file mode 100644
index 239fc80..0000000
--- a/lib/byte-buddy-1.9.10.jar
+++ /dev/null
Binary files differ
diff --git a/lib/byte-buddy-agent-1.8.15-sources.jar b/lib/byte-buddy-agent-1.8.15-sources.jar
new file mode 100644
index 0000000..24ab2ee
--- /dev/null
+++ b/lib/byte-buddy-agent-1.8.15-sources.jar
Binary files differ
diff --git a/lib/byte-buddy-agent-1.8.15.jar b/lib/byte-buddy-agent-1.8.15.jar
new file mode 100644
index 0000000..1709e55
--- /dev/null
+++ b/lib/byte-buddy-agent-1.8.15.jar
Binary files differ
diff --git a/lib/byte-buddy-1.9.10.jar.txt b/lib/byte-buddy-agent-1.8.15.jar.txt
similarity index 100%
copy from lib/byte-buddy-1.9.10.jar.txt
copy to lib/byte-buddy-agent-1.8.15.jar.txt
diff --git a/lib/byte-buddy-agent-1.9.10-sources.jar b/lib/byte-buddy-agent-1.9.10-sources.jar
deleted file mode 100644
index 9b2d60a..0000000
--- a/lib/byte-buddy-agent-1.9.10-sources.jar
+++ /dev/null
Binary files differ
diff --git a/lib/byte-buddy-agent-1.9.10.jar b/lib/byte-buddy-agent-1.9.10.jar
deleted file mode 100644
index 8dfab05..0000000
--- a/lib/byte-buddy-agent-1.9.10.jar
+++ /dev/null
Binary files differ
diff --git a/lib/byte-buddy-agent-1.9.10.jar.txt b/lib/byte-buddy-agent-1.9.10.jar.txt
deleted file mode 100644
index e06d208..0000000
--- a/lib/byte-buddy-agent-1.9.10.jar.txt
+++ /dev/null
@@ -1,202 +0,0 @@
-Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- 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.
-
diff --git a/lib/opentest4j-1.1.1-sources.jar b/lib/opentest4j-1.1.1-sources.jar
deleted file mode 100644
index 7cb1de7..0000000
--- a/lib/opentest4j-1.1.1-sources.jar
+++ /dev/null
Binary files differ
diff --git a/lib/opentest4j-1.1.1.jar b/lib/opentest4j-1.1.1.jar
deleted file mode 100644
index 3f35529..0000000
--- a/lib/opentest4j-1.1.1.jar
+++ /dev/null
Binary files differ
diff --git a/lib/opentest4j-1.1.1.jar.txt b/lib/opentest4j-1.1.1.jar.txt
deleted file mode 100644
index 8f71f43..0000000
--- a/lib/opentest4j-1.1.1.jar.txt
+++ /dev/null
@@ -1,202 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- 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.
-
diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java
index 6274fd7..214eaa5 100644
--- a/src/main/java/org/mockito/AdditionalAnswers.java
+++ b/src/main/java/org/mockito/AdditionalAnswers.java
@@ -16,13 +16,11 @@
import org.mockito.stubbing.Answer3;
import org.mockito.stubbing.Answer4;
import org.mockito.stubbing.Answer5;
-import org.mockito.stubbing.Answer6;
import org.mockito.stubbing.VoidAnswer1;
import org.mockito.stubbing.VoidAnswer2;
import org.mockito.stubbing.VoidAnswer3;
import org.mockito.stubbing.VoidAnswer4;
import org.mockito.stubbing.VoidAnswer5;
-import org.mockito.stubbing.VoidAnswer6;
import static org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces.toAnswer;
@@ -490,43 +488,4 @@
public static <A, B, C, D, E> Answer<Void> answerVoid(VoidAnswer5<A, B, C, D, E> answer) {
return toAnswer(answer);
}
-
- /**
- * Creates an answer from a functional interface - allows for a strongly typed answer to be created
- * idiomatically in Java 8
- *
- * @param answer interface to the answer - which is expected to return something
- * @param <T> return type
- * @param <A> input parameter type 1
- * @param <B> input parameter type 2
- * @param <C> input parameter type 3
- * @param <D> input parameter type 4
- * @param <E> input parameter type 5
- * @param <F> input parameter type 6
- * @return the answer object to use
- * @since 2.26.0
- */
- @Incubating
- public static <T, A, B, C, D, E, F> Answer<T> answer(Answer6<T, A, B, C, D, E, F> answer) {
- return toAnswer(answer);
- }
-
- /**
- * Creates an answer from a functional interface - allows for a strongly typed answer to be created
- * idiomatically in Java 8
- *
- * @param answer interface to the answer - a void method
- * @param <A> input parameter type 1
- * @param <B> input parameter type 2
- * @param <C> input parameter type 3
- * @param <D> input parameter type 4
- * @param <E> input parameter type 5
- * @param <F> input parameter type 6
- * @return the answer object to use
- * @since 2.26.0
- */
- @Incubating
- public static <A, B, C, D, E, F> Answer<Void> answerVoid(VoidAnswer6<A, B, C, D, E, F> answer) {
- return toAnswer(answer);
- }
}
diff --git a/src/main/java/org/mockito/ArgumentCaptor.java b/src/main/java/org/mockito/ArgumentCaptor.java
index 7011c92..1104de9 100644
--- a/src/main/java/org/mockito/ArgumentCaptor.java
+++ b/src/main/java/org/mockito/ArgumentCaptor.java
@@ -49,7 +49,7 @@
* Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
*
* <p>
- * This utility class <strong>*doesn't do any type checks*</strong>. The generic signatures are only there to avoid casting
+ * This utility class <strong>*don't do any type checks*</strong>, the generic signatures are only there to avoid casting
* in your code.
* <p>
* There is an <strong>annotation</strong> that you might find useful: @{@link Captor}
@@ -136,7 +136,7 @@
/**
* Build a new <code>ArgumentCaptor</code>.
* <p>
- * Note that an <code>ArgumentCaptor</code> <b>*doesn't do any type checks*</b>. It is only there to avoid casting
+ * Note that an <code>ArgumentCaptor</code> <b>*don't do any type checks*</b>, it is only there to avoid casting
* in your code. This might however change (type checks could be added) in a
* future major release.
*
diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java
index e2b83c8..4a6c84d 100644
--- a/src/main/java/org/mockito/ArgumentMatchers.java
+++ b/src/main/java/org/mockito/ArgumentMatchers.java
@@ -521,7 +521,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> List<T> anyListOf(Class<T> clazz) {
return anyList();
}
@@ -582,7 +581,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> Set<T> anySetOf(Class<T> clazz) {
return anySet();
}
@@ -644,7 +642,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) {
return anyMap();
}
@@ -705,7 +702,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {
return anyCollection();
}
@@ -768,7 +764,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> Iterable<T> anyIterableOf(Class<T> clazz) {
return anyIterable();
}
@@ -993,7 +988,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> T isNull(Class<T> clazz) {
return isNull();
}
@@ -1037,7 +1031,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> T notNull(Class<T> clazz) {
return notNull();
}
@@ -1079,7 +1072,6 @@
* @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
* friendliness to avoid casting, this is not anymore needed in Java 8.
*/
- @Deprecated
public static <T> T isNotNull(Class<T> clazz) {
return notNull(clazz);
}
diff --git a/src/main/java/org/mockito/Mock.java b/src/main/java/org/mockito/Mock.java
index 1c6cbb8..909432f 100644
--- a/src/main/java/org/mockito/Mock.java
+++ b/src/main/java/org/mockito/Mock.java
@@ -9,7 +9,6 @@
import java.lang.annotation.Target;
import org.mockito.junit.MockitoJUnitRunner;
-import org.mockito.stubbing.Answer;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
@@ -68,41 +67,13 @@
@Documented
public @interface Mock {
- /**
- * Mock will have custom answer, see {@link MockSettings#defaultAnswer(Answer)}.
- * For examples how to use 'Mock' annotation and parameters see {@link Mock}.
- */
Answers answer() default Answers.RETURNS_DEFAULTS;
- /**
- * Mock will be 'stubOnly', see {@link MockSettings#stubOnly()}.
- * For examples how to use 'Mock' annotation and parameters see {@link Mock}.
- */
boolean stubOnly() default false;
- /**
- * Mock will have custom name (shown in verification errors), see {@link MockSettings#name(String)}.
- * For examples how to use 'Mock' annotation and parameters see {@link Mock}.
- */
String name() default "";
- /**
- * Mock will have extra interfaces, see {@link MockSettings#extraInterfaces(Class[])}.
- * For examples how to use 'Mock' annotation and parameters see {@link Mock}.
- */
Class<?>[] extraInterfaces() default {};
- /**
- * Mock will be serializable, see {@link MockSettings#serializable()}.
- * For examples how to use 'Mock' annotation and parameters see {@link Mock}.
- */
boolean serializable() default false;
-
- /**
- * Mock will be lenient, see {@link MockSettings#lenient()}.
- * For examples how to use 'Mock' annotation and parameters see {@link Mock}.
- *
- * @since 2.23.3
- */
- boolean lenient() default false;
}
diff --git a/src/main/java/org/mockito/MockSettings.java b/src/main/java/org/mockito/MockSettings.java
index 07af55e..c79c243 100644
--- a/src/main/java/org/mockito/MockSettings.java
+++ b/src/main/java/org/mockito/MockSettings.java
@@ -9,7 +9,6 @@
import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.MockHandler;
import org.mockito.listeners.InvocationListener;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.SerializableMode;
@@ -44,7 +43,6 @@
* Firstly, to make it easy to add another mock setting when the demand comes.
* Secondly, to enable combining together different mock settings without introducing zillions of overloaded mock() methods.
*/
-@NotExtensible
public interface MockSettings extends Serializable {
/**
@@ -206,24 +204,6 @@
MockSettings verboseLogging();
/**
- * Add stubbing lookup listener to the mock object.
- *
- * Multiple listeners may be added and they will be notified orderly.
- *
- * For use cases and more info see {@link StubbingLookupListener}.
- *
- * Example:
- * <pre class="code"><code class="java">
- * List mockWithListener = mock(List.class, withSettings().stubbingLookupListeners(new YourStubbingLookupListener()));
- * </code></pre>
- *
- * @param listeners The stubbing lookup listeners to add. May not be null.
- * @return settings instance so that you can fluently specify other settings
- * @since 2.24.6
- */
- MockSettings stubbingLookupListeners(StubbingLookupListener... listeners);
-
- /**
* Registers a listener for method invocations on this mock. The listener is
* notified every time a method on this mock is called.
* <p>
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 5066eec..2d06e58 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -103,8 +103,7 @@
* <a href="#43">43. New API for integrations: <code>MockitoSession</code> is usable by testing frameworks (Since 2.15.+)</a><br/>
* <a href="#44">44. Deprecated <code>org.mockito.plugins.InstantiatorProvider</code> as it was leaking internal API. it was replaced by <code>org.mockito.plugins.InstantiatorProvider2 (Since 2.15.4)</code></a><br/>
* <a href="#45">45. New JUnit Jupiter (JUnit5+) extension</a><br/>
- * <a href="#46">46. New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0)</a><br/>
- * <a href="#47">47. New API for clearing mock state in inline mocking (Since 2.25.0)</a><br/>
+ * <a href="#46">46. New <code>Mockito.lenient()</code> and <code>MockSettings.lenient()</code> methods (Since 2.20.0</a><br/>
* </b>
*
* <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3>
@@ -208,7 +207,7 @@
*
* //Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>
* //If your code cares what get(0) returns, then something else breaks (often even before 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 get(0) returns, then it should not be stubbed. Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
* verify(mockedList).get(0);
* </code></pre>
*
@@ -358,7 +357,7 @@
* //create an inOrder verifier for a single mock
* InOrder inOrder = inOrder(singleMock);
*
- * //following will make sure that add is first called with "was added first", then with "was added second"
+ * //following will make sure that add is first called with "was added first, then with "was added second"
* inOrder.verify(singleMock).add("was added first");
* inOrder.verify(singleMock).add("was added second");
*
@@ -427,7 +426,8 @@
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
- * Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests.
+ * Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests. You can find further reading
+ * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
*
* <p>
* See also {@link Mockito#never()} - it is more explicit and
@@ -464,7 +464,6 @@
* </code></pre>
*
* You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
- * For JUnit5 tests, refer to the JUnit5 extension described in <a href="#45">section 45</a>.
* <p>
* Read more here: {@link MockitoAnnotations}
*
@@ -598,7 +597,8 @@
* <b>Before the release 1.8</b>, Mockito spies were not real partial mocks.
* The reason was we thought partial mock is a code smell.
* At some point we found legitimate use cases for partial mocks
- * (3rd party interfaces, interim refactoring of legacy code).
+ * (3rd party interfaces, interim refactoring of legacy code, the full article is
+ * <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>)
* <p>
*
* <pre class="code"><code class="java">
@@ -707,7 +707,8 @@
* <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks" name="partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3>
*
* Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito.
- * Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
+ * Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading:
+ * <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>
* <p>
* <b>Before release 1.8</b> <code>spy()</code> was not producing real partial mocks and it was confusing for some users.
* Read more about spying: <a href="#13">here</a> or in javadoc for {@link Mockito#spy(Object)} method.
@@ -1531,15 +1532,6 @@
*
* For more information refer to {@link Mockito#lenient()}.
* Let us know how do you find the new feature by opening a GitHub issue to discuss!
- *
- * <h3 id="47">47. <a class="meaningful_link" href="#clear_inline_mocks" name="clear_inline_mocks">New API for clearing mock state in inline mocking (Since 2.25.0)</a></h3>
- *
- * In certain specific, rare scenarios (issue <a href="https://github.com/mockito/mockito/pull/1619">#1619</a>)
- * inline mocking causes memory leaks.
- * There is no clean way to mitigate this problem completely.
- * 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.
*/
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
@@ -1692,7 +1684,6 @@
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
- *
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
@@ -1724,11 +1715,8 @@
* </code></pre>
*
* <p>
- * <u>Note 1:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code>
+ * <u>Note:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code>
* syntax will call the real method. For partial mock it's recommended to use <code>doReturn</code> syntax.
- * <p>
- * <u>Note 2:</u> If the mock is serialized then deserialized, then this answer will not be able to understand
- * generics metadata.
*/
public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
@@ -2081,6 +2069,7 @@
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
+ * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
*
* <p>
* See examples in javadoc for {@link Mockito} class
@@ -2112,6 +2101,7 @@
* Let's say you've stubbed <code>foo.bar()</code>.
* If your code cares what <code>foo.bar()</code> returns then something else breaks(often before even <code>verify()</code> gets executed).
* If your code doesn't care what <code>get(0)</code> returns then it should not be stubbed.
+ * Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
*
* <p>
* See examples in javadoc for {@link Mockito} class
@@ -2213,7 +2203,8 @@
* Some users who did a lot of classic, expect-run-verify mocking tend to use <code>verifyNoMoreInteractions()</code> very often, even in every test method.
* <code>verifyNoMoreInteractions()</code> is not recommended to use in every test method.
* <code>verifyNoMoreInteractions()</code> is a handy assertion from the interaction testing toolkit. Use it only when it's relevant.
- * Abusing it leads to overspecified, less maintainable tests.
+ * Abusing it leads to overspecified, less maintainable tests. You can find further reading
+ * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
* <p>
* This method will also detect unverified invocations that occurred before the test method,
* for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
diff --git a/src/main/java/org/mockito/MockitoFramework.java b/src/main/java/org/mockito/MockitoFramework.java
index da03ef4..5ffe272 100644
--- a/src/main/java/org/mockito/MockitoFramework.java
+++ b/src/main/java/org/mockito/MockitoFramework.java
@@ -20,7 +20,6 @@
* @since 2.1.0
*/
@Incubating
-@NotExtensible
public interface MockitoFramework {
/**
@@ -93,55 +92,4 @@
*/
@Incubating
InvocationFactory getInvocationFactory();
-
- /**
- * Clears up internal state of all inline mocks.
- * This method is only meaningful if inline mock maker is in use.
- * Otherwise this method is a no-op and need not be used.
- * <p>
- * This method is useful to tackle subtle memory leaks that are possible due to the nature of inline mocking
- * (issue <a href="https://github.com/mockito/mockito/pull/1619">#1619</a>).
- * If you are facing those problems, call this method at the end of the test (or in "@After" method).
- * See examples of using "clearInlineMocks" in Mockito test code.
- * To find out why inline mock maker keeps track of the mock objects see {@link org.mockito.plugins.InlineMockMaker}.
- * <p>
- * Mockito's "inline mocking" enables mocking final types, enums and final methods
- * (read more in section 39 of {@link Mockito} javadoc).
- * This method is only meaningful when {@link org.mockito.plugins.InlineMockMaker} is in use.
- * If you're using a different {@link org.mockito.plugins.MockMaker} then this method is a no-op.
- *
- * <pre class="code"><code class="java">
- * public class ExampleTest {
- *
- * @After
- * public void clearMocks() {
- * Mockito.framework().clearInlineMocks();
- * }
- *
- * @Test
- * public void someTest() {
- * ...
- * }
- * }
- * </pre>
- *
- * If you have feedback or a better idea how to solve the problem please reach out.
- *
- * @since 2.25.0
- * @see #clearInlineMock(Object)
- */
- @Incubating
- void clearInlineMocks();
-
- /**
- * Clears up internal state of specific inline mock.
- * This method is a single-mock variant of {@link #clearInlineMocks()}.
- * Please read javadoc for {@link #clearInlineMocks()}.
- *
- * @param mock to clear up
- * @since 2.25.0
- * @see #clearInlineMocks()
- */
- @Incubating
- void clearInlineMock(Object mock);
}
diff --git a/src/main/java/org/mockito/MockitoSession.java b/src/main/java/org/mockito/MockitoSession.java
index 6a529fd..9e820f2 100644
--- a/src/main/java/org/mockito/MockitoSession.java
+++ b/src/main/java/org/mockito/MockitoSession.java
@@ -88,7 +88,6 @@
* @since 2.7.0
*/
@Incubating
-@NotExtensible
public interface MockitoSession {
/**
diff --git a/src/main/java/org/mockito/exceptions/misusing/InjectMocksException.java b/src/main/java/org/mockito/exceptions/misusing/InjectMocksException.java
deleted file mode 100644
index 616d4b6..0000000
--- a/src/main/java/org/mockito/exceptions/misusing/InjectMocksException.java
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * Copyright (c) 2018 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.exceptions.misusing;
-
-import org.mockito.exceptions.base.MockitoException;
-
-/**
- * Thrown when creation of test subject annotated with InjectMocks fails.
- */
-public class InjectMocksException extends MockitoException {
- public InjectMocksException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java b/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
index 5a72f20..a44cc6f 100644
--- a/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
+++ b/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
@@ -17,19 +17,6 @@
super(message);
}
- /**
- * Three-arg constructor for compatibility with ExceptionFactory's three-arg
- * create method. This implementation simply ignores the second and third
- * arguments.
- *
- * @param message
- * @param wanted ignored
- * @param actual ignored
- */
- public ArgumentsAreDifferent(String message, String wanted, String actual) {
- this(message);
- }
-
@Override
public String toString() {
return removeFirstLine(super.toString());
diff --git a/src/main/java/org/mockito/exceptions/verification/junit/package-info.java b/src/main/java/org/mockito/exceptions/verification/junit/package-info.java
index ad4ab77..4542d34 100644
--- a/src/main/java/org/mockito/exceptions/verification/junit/package-info.java
+++ b/src/main/java/org/mockito/exceptions/verification/junit/package-info.java
@@ -4,9 +4,6 @@
*/
/**
- * JUnit integration to provide better support for JUnit 4 and
- * earlier in IDEs.
- *
- * @see org.mockito.exceptions.verification.opentest4j
+ * JUnit integration to provide better support for junit runners in IDEs.
*/
package org.mockito.exceptions.verification.junit;
diff --git a/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java b/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java
deleted file mode 100644
index 8f50d00..0000000
--- a/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2019 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.exceptions.verification.opentest4j;
-
-import static org.mockito.internal.util.StringUtil.removeFirstLine;
-
-import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
-import org.opentest4j.AssertionFailedError;
-
-
-public class ArgumentsAreDifferent extends AssertionFailedError {
-
- private static final long serialVersionUID = 1L;
- private final String message;
- private final StackTraceElement[] unfilteredStackTrace;
-
- public ArgumentsAreDifferent(String message, String wanted, String actual) {
- super(message, wanted, actual);
- this.message = message;
-
- unfilteredStackTrace = getStackTrace();
- ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
- filter.filter(this);
- }
-
- @Override
- public String getMessage() {
- return message;
- }
-
- public StackTraceElement[] getUnfilteredStackTrace() {
- return unfilteredStackTrace;
- }
-
- @Override
- public String toString() {
- return removeFirstLine(super.toString());
- }
-}
diff --git a/src/main/java/org/mockito/exceptions/verification/opentest4j/package-info.java b/src/main/java/org/mockito/exceptions/verification/opentest4j/package-info.java
deleted file mode 100644
index 2e84ddd..0000000
--- a/src/main/java/org/mockito/exceptions/verification/opentest4j/package-info.java
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * Copyright (c) 2019 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-/**
- * Integration to provide better support for IDEs that support OpenTest4J.
- *
- * @see org.mocktio.exceptions.verification.junit
- * @see org.mocktio.exceptions.verification.junit4
- */
-package org.mockito.exceptions.verification.opentest4j;
diff --git a/src/main/java/org/mockito/internal/MockitoCore.java b/src/main/java/org/mockito/internal/MockitoCore.java
index 5d39d5e..68b580a 100644
--- a/src/main/java/org/mockito/internal/MockitoCore.java
+++ b/src/main/java/org/mockito/internal/MockitoCore.java
@@ -35,17 +35,24 @@
import java.util.Arrays;
import java.util.List;
-import static org.mockito.internal.exceptions.Reporter.*;
+import static org.mockito.internal.exceptions.Reporter.missingMethodInvocation;
+import static org.mockito.internal.exceptions.Reporter.mocksHaveToBePassedToVerifyNoMoreInteractions;
+import static org.mockito.internal.exceptions.Reporter.mocksHaveToBePassedWhenCreatingInOrder;
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedToVerify;
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedToVerifyNoMoreInteractions;
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedWhenCreatingInOrder;
+import static org.mockito.internal.exceptions.Reporter.nullPassedToVerify;
+import static org.mockito.internal.exceptions.Reporter.nullPassedToVerifyNoMoreInteractions;
+import static org.mockito.internal.exceptions.Reporter.nullPassedWhenCreatingInOrder;
+import static org.mockito.internal.exceptions.Reporter.stubPassedToVerify;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
import static org.mockito.internal.util.MockUtil.createMock;
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.noMoreInteractions;
-
@SuppressWarnings("unchecked")
public class MockitoCore {
@@ -84,8 +91,10 @@
if (!mockingDetails.isMock()) {
throw notAMockPassedToVerify(mock.getClass());
}
- assertNotStubOnlyMock(mock);
MockHandler handler = mockingDetails.getMockHandler();
+ if (handler.getMockSettings().isStubOnly()) {
+ throw stubPassedToVerify();
+ }
mock = (T) VerificationStartedNotifier.notifyVerificationStarted(
handler.getMockSettings().getVerificationStartedListeners(), mockingDetails);
@@ -126,7 +135,6 @@
throw nullPassedToVerifyNoMoreInteractions();
}
InvocationContainerImpl invocations = getInvocationContainer(mock);
- assertNotStubOnlyMock(mock);
VerificationDataImpl data = new VerificationDataImpl(invocations, null);
noMoreInteractions().verify(data);
} catch (NotAMockException e) {
@@ -147,12 +155,6 @@
}
}
- private void assertNotStubOnlyMock(Object mock) {
- if (getMockHandler(mock).getMockSettings().isStubOnly()) {
- throw stubPassedToVerify(mock);
- }
- }
-
public InOrder inOrder(Object... mocks) {
if (mocks == null || mocks.length == 0) {
throw mocksHaveToBePassedWhenCreatingInOrder();
@@ -164,7 +166,6 @@
if (!isMock(mock)) {
throw notAMockPassedWhenCreatingInOrder();
}
- assertNotStubOnlyMock(mock);
}
return new InOrderImpl(Arrays.asList(mocks));
}
diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
index 20d967d..6cb5fb1 100644
--- a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
+++ b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
@@ -39,7 +39,15 @@
*/
public void process(Class<?> clazz, Object testInstance) {
processIndependentAnnotations(testInstance.getClass(), testInstance);
- injectMocks(testInstance);
+ processInjectMocks(testInstance.getClass(), testInstance);
+ }
+
+ private void processInjectMocks(final Class<?> clazz, final Object testInstance) {
+ Class<?> classContext = clazz;
+ while (classContext != Object.class) {
+ injectMocks(testInstance);
+ classContext = classContext.getSuperclass();
+ }
}
private void processIndependentAnnotations(final Class<?> clazz, final Object testInstance) {
diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
index d99b348..91086d2 100644
--- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
+++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
@@ -35,9 +35,6 @@
if(annotation.stubOnly()){
mockSettings.stubOnly();
}
- if(annotation.lenient()){
- mockSettings.lenient();
- }
// see @Mock answer default value
mockSettings.defaultAnswer(annotation.answer());
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 e5aefd9..f80e7c4 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/DefaultMockitoPlugins.java
@@ -9,7 +9,6 @@
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;
@@ -30,7 +29,6 @@
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
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 2e5f069..02e5d66 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/PluginRegistry.java
@@ -9,7 +9,6 @@
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;
@@ -26,12 +25,9 @@
private final InstantiatorProvider2 instantiatorProvider;
- private final AnnotationEngine annotationEngine = new PluginLoader(pluginSwitch)
+ private AnnotationEngine annotationEngine = new PluginLoader(pluginSwitch)
.loadPlugin(AnnotationEngine.class);
- private final MockitoLogger mockitoLogger = new PluginLoader(pluginSwitch)
- .loadPlugin(MockitoLogger.class);
-
PluginRegistry() {
Object impl = new PluginLoader(pluginSwitch).loadPlugin(InstantiatorProvider2.class, InstantiatorProvider.class);
if (impl instanceof InstantiatorProvider) {
@@ -79,14 +75,4 @@
AnnotationEngine getAnnotationEngine() {
return annotationEngine;
}
-
- /**
- * Returns the logger available for the current runtime.
- *
- * <p>Returns {@link org.mockito.internal.util.ConsoleMockitoLogger} if no
- * {@link org.mockito.plugins.MockitoLogger} extension exists or is visible in the current classpath.</p>
- */
- MockitoLogger getMockitoLogger() {
- return mockitoLogger;
- }
}
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 84e3c0d..f65fe89 100644
--- a/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java
+++ b/src/main/java/org/mockito/internal/configuration/plugins/Plugins.java
@@ -4,7 +4,6 @@
*/
package org.mockito.internal.configuration.plugins;
-import org.mockito.plugins.MockitoLogger;
import org.mockito.plugins.AnnotationEngine;
import org.mockito.plugins.InstantiatorProvider2;
import org.mockito.plugins.MockMaker;
@@ -57,16 +56,6 @@
}
/**
- * Returns the logger available for the current runtime.
- *
- * <p>Returns {@link org.mockito.internal.util.ConsoleMockitoLogger} if no
- * {@link org.mockito.plugins.MockitoLogger} extension exists or is visible in the current classpath.</p>
- */
- public static MockitoLogger getMockitoLogger() {
- return registry.getMockitoLogger();
- }
-
- /**
* @return instance of mockito plugins type
*/
public static MockitoPlugins getPlugins() {
diff --git a/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java b/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java
index 50134b4..ca67730 100644
--- a/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java
+++ b/src/main/java/org/mockito/internal/creation/MockSettingsImpl.java
@@ -11,7 +11,6 @@
import org.mockito.internal.util.MockCreationValidator;
import org.mockito.internal.util.MockNameImpl;
import org.mockito.listeners.InvocationListener;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.MockName;
@@ -20,17 +19,17 @@
import java.io.Serializable;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import static java.util.Arrays.asList;
import static org.mockito.internal.exceptions.Reporter.defaultAnswerDoesNotAcceptNullParameter;
import static org.mockito.internal.exceptions.Reporter.extraInterfacesAcceptsOnlyInterfaces;
import static org.mockito.internal.exceptions.Reporter.extraInterfacesDoesNotAcceptNullParameters;
import static org.mockito.internal.exceptions.Reporter.extraInterfacesRequiresAtLeastOneInterface;
+import static org.mockito.internal.exceptions.Reporter.invocationListenersRequiresAtLeastOneListener;
import static org.mockito.internal.exceptions.Reporter.methodDoesNotAcceptParameter;
-import static org.mockito.internal.exceptions.Reporter.requiresAtLeastOneListener;
import static org.mockito.internal.util.collections.Sets.newSet;
@SuppressWarnings("unchecked")
@@ -155,7 +154,7 @@
}
List<Object> resultArgs = new ArrayList<Object>(constructorArgs.length + 1);
resultArgs.add(outerClassInstance);
- resultArgs.addAll(asList(constructorArgs));
+ resultArgs.addAll(Arrays.asList(constructorArgs));
return resultArgs.toArray(new Object[constructorArgs.length + 1]);
}
@@ -174,23 +173,17 @@
@Override
public MockSettings invocationListeners(InvocationListener... listeners) {
+ if (listeners == null || listeners.length == 0) {
+ throw invocationListenersRequiresAtLeastOneListener();
+ }
addListeners(listeners, invocationListeners, "invocationListeners");
return this;
}
- @Override
- public MockSettings stubbingLookupListeners(StubbingLookupListener... listeners) {
- addListeners(listeners, stubbingLookupListeners, "stubbingLookupListeners");
- return this;
- }
-
- static <T> void addListeners(T[] listeners, List<T> container, String method) {
+ private static <T> void addListeners(T[] listeners, List<T> container, String method) {
if (listeners == null) {
throw methodDoesNotAcceptParameter(method, "null vararg array.");
}
- if (listeners.length == 0) {
- throw requiresAtLeastOneListener(method);
- }
for (T listener : listeners) {
if (listener == null) {
throw methodDoesNotAcceptParameter(method, "null listeners.");
@@ -214,8 +207,13 @@
return false;
}
+ @Override
+ public List<InvocationListener> getInvocationListeners() {
+ return this.invocationListeners;
+ }
+
public boolean hasInvocationListeners() {
- return !getInvocationListeners().isEmpty();
+ return !invocationListeners.isEmpty();
}
@Override
diff --git a/src/main/java/org/mockito/internal/creation/SuspendMethod.java b/src/main/java/org/mockito/internal/creation/SuspendMethod.java
index 42ceac6..018bc50 100644
--- a/src/main/java/org/mockito/internal/creation/SuspendMethod.java
+++ b/src/main/java/org/mockito/internal/creation/SuspendMethod.java
@@ -11,18 +11,12 @@
* See <a href="https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#continuation-passing-style">Design docs for details</a>.
*/
public class SuspendMethod {
- private static final String KOTLIN_EXPERIMENTAL_CONTINUATION = "kotlin.coroutines.experimental.Continuation";
- private static final String KOTLIN_CONTINUATION = "kotlin.coroutines.Continuation";
+ private static final String KOTLIN_CONTINUATION = "kotlin.coroutines.experimental.Continuation";
public static Class<?>[] trimSuspendParameterTypes(Class<?>[] parameterTypes) {
int n = parameterTypes.length;
- if (n > 0 && isContinuationType(parameterTypes[n - 1]))
+ if (n > 0 && parameterTypes[n - 1].getName().equals(KOTLIN_CONTINUATION))
return Arrays.copyOf(parameterTypes, n - 1);
return parameterTypes;
}
-
- private static boolean isContinuationType(Class<?> parameterType) {
- String name = parameterType.getName();
- return name.equals(KOTLIN_CONTINUATION) || name.equals(KOTLIN_EXPERIMENTAL_CONTINUATION);
- }
}
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 e99b915..42f10ce 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
@@ -14,7 +14,6 @@
import org.mockito.internal.util.concurrent.WeakConcurrentMap;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
-import org.mockito.plugins.InlineMockMaker;
import java.io.File;
import java.io.FileOutputStream;
@@ -26,8 +25,6 @@
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
-import javax.tools.ToolProvider;
-
import static org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.EXCLUDES;
import static org.mockito.internal.util.StringUtil.join;
@@ -90,7 +87,7 @@
* support this feature.
*/
@Incubating
-public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker, InlineMockMaker {
+public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker {
private static final Instrumentation INSTRUMENTATION;
@@ -112,7 +109,7 @@
boot.deleteOnExit();
JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(boot));
try {
- String source = "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher";
+ String source = "org/mockito/internal/creation/bytebuddy/MockMethodDispatcher";
InputStream inputStream = InlineByteBuddyMockMaker.class.getClassLoader().getResourceAsStream(source + ".raw");
if (inputStream == null) {
throw new IllegalStateException(join(
@@ -137,7 +134,13 @@
}
instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(boot));
try {
- Class.forName("org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher", false, null);
+ Class<?> dispatcher = Class.forName("org.mockito.internal.creation.bytebuddy.MockMethodDispatcher");
+ if (dispatcher.getClassLoader() != null) {
+ throw new IllegalStateException(join(
+ "The MockMethodDispatcher must not be loaded manually but must be injected into the bootstrap class loader.",
+ "",
+ "The dispatcher class was already loaded by: " + dispatcher.getClassLoader()));
+ }
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException(join(
"Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader",
@@ -167,7 +170,7 @@
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);
}
bytecodeGenerator = new TypeCachingBytecodeGenerator(new InlineBytecodeGenerator(INSTRUMENTATION, mocks), true);
@@ -273,16 +276,6 @@
}
@Override
- public void clearMock(Object mock) {
- mocks.remove(mock);
- }
-
- @Override
- public void clearAllMocks() {
- mocks.clear();
- }
-
- @Override
public TypeMockability isTypeMockable(final Class<?> type) {
return new TypeMockability() {
@Override
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 e160e3c..64139c2 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
@@ -26,17 +26,17 @@
import net.bytebuddy.utility.OpenedClassReader;
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.WeakConcurrentMap;
import org.mockito.internal.util.concurrent.WeakConcurrentSet;
import org.mockito.mock.SerializableMode;
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.Arrays;
+import java.util.HashSet;
+import java.util.Set;
import static net.bytebuddy.implementation.MethodDelegation.withDefaultConfiguration;
import static net.bytebuddy.implementation.bind.annotation.TargetMethodAnnotationDrivenBinder.ParameterBinder.ForFixedValue.OfConstant.of;
@@ -60,12 +60,14 @@
String.class));
private final Instrumentation instrumentation;
- private final ByteBuddy byteBuddy;
- private final WeakConcurrentSet<Class<?>> mocked;
- private final BytecodeGenerator subclassEngine;
- private final AsmVisitorWrapper mockTransformer;
- private final Method getModule, canRead, redefineModule;
+ private final ByteBuddy byteBuddy;
+
+ private final WeakConcurrentSet<Class<?>> mocked;
+
+ private final BytecodeGenerator subclassEngine;
+
+ private final AsmVisitorWrapper mockTransformer;
private volatile Throwable lastException;
@@ -96,20 +98,6 @@
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);
- } catch (Exception ignored) {
- getModule = null;
- canRead = null;
- redefineModule = null;
- }
- this.getModule = getModule;
- this.canRead = canRead;
- this.redefineModule = redefineModule;
MockMethodDispatcher.set(identifier, new MockMethodAdvice(mocks, identifier));
instrumentation.addTransformer(this, true);
}
@@ -170,7 +158,6 @@
} while (type != null);
if (!types.isEmpty()) {
try {
- assureCanReadMockito(types);
instrumentation.retransformClasses(types.toArray(new Class<?>[types.size()]));
Throwable throwable = lastException;
if (throwable != null) {
@@ -191,32 +178,6 @@
}
}
- private void assureCanReadMockito(Set<Class<?>> types) {
- if (redefineModule == null) {
- return;
- }
- Set<Object> modules = new HashSet<Object>();
- try {
- 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)) {
- modules.add(module);
- }
- }
- for (Object module : modules) {
- 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);
- }
- }
-
private <T> void checkSupportedCombination(boolean subclassingRequired, MockFeatures<T> features) {
if (subclassingRequired
&& !features.mockedType.isArray()
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 828b848..f39a1a2 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 net.bytebuddy.implementation.bind.annotation.This;
import net.bytebuddy.implementation.bytecode.assign.Assigner;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
import org.mockito.internal.invocation.RealMethod;
@@ -36,7 +35,7 @@
public class MockMethodAdvice extends MockMethodDispatcher {
- private final WeakConcurrentMap<Object, MockMethodInterceptor> interceptors;
+ final WeakConcurrentMap<Object, MockMethodInterceptor> interceptors;
private final String identifier;
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 e57a82e..9066927 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodInterceptor.java
@@ -46,11 +46,13 @@
Method invokedMethod,
Object[] arguments,
RealMethod realMethod) throws Throwable {
- return doIntercept(mock,
- invokedMethod,
- arguments,
- realMethod,
- new LocationImpl());
+ return doIntercept(
+ mock,
+ invokedMethod,
+ arguments,
+ realMethod,
+ new LocationImpl()
+ );
}
Object doIntercept(Object mock,
@@ -106,11 +108,11 @@
return superCall.call();
}
return interceptor.doIntercept(
- mock,
- invokedMethod,
- arguments,
- new RealMethod.FromCallable(superCall)
- );
+ mock,
+ invokedMethod,
+ arguments,
+ new RealMethod.FromCallable(superCall)
+ );
}
@SuppressWarnings("unused")
@@ -124,11 +126,11 @@
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
deleted file mode 100644
index 5be0b95..0000000
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/ModuleHandler.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (c) 2016 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.creation.bytebuddy;
-
-import net.bytebuddy.ByteBuddy;
-import net.bytebuddy.description.modifier.Ownership;
-import net.bytebuddy.description.modifier.Visibility;
-import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
-import net.bytebuddy.implementation.Implementation;
-import net.bytebuddy.implementation.MethodCall;
-import net.bytebuddy.implementation.StubMethod;
-import org.mockito.codegen.InjectionBase;
-import org.mockito.exceptions.base.MockitoException;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.Random;
-
-import static net.bytebuddy.matcher.ElementMatchers.isTypeInitializer;
-import static org.mockito.internal.util.StringUtil.join;
-
-abstract class ModuleHandler {
-
- abstract boolean isOpened(Class<?> source, Class<?> target);
-
- abstract boolean canRead(Class<?> source, Class<?> target);
-
- abstract boolean isExported(Class<?> source);
-
- abstract boolean isExported(Class<?> source, Class<?> target);
-
- abstract Class<?> injectionBase(ClassLoader classLoader, String tyoeName);
-
- abstract void adjustModuleGraph(Class<?> source, Class<?> target, boolean export, boolean read);
-
- static ModuleHandler make(ByteBuddy byteBuddy, SubclassLoader loader, Random random) {
- try {
- return new ModuleSystemFound(
- byteBuddy, loader, random
- );
- } catch (Exception ignored) {
- return new NoModuleSystemFound();
- }
- }
-
- private static class ModuleSystemFound extends ModuleHandler {
-
- private final ByteBuddy byteBuddy;
- private final SubclassLoader loader;
- private final Random random;
-
- private final int injectonBaseSuffix;
-
- private final Method getModule, isOpen, isExported, isExportedUnqualified, canRead, addExports, addReads, addOpens, forName;
-
- private ModuleSystemFound(ByteBuddy byteBuddy, SubclassLoader loader, Random random) throws Exception {
- this.byteBuddy = byteBuddy;
- this.loader = loader;
- this.random = random;
- injectonBaseSuffix = Math.abs(random.nextInt());
- Class<?> moduleType = Class.forName("java.lang.Module");
- getModule = Class.class.getMethod("getModule");
- isOpen = moduleType.getMethod("isOpen", String.class, moduleType);
- isExported = moduleType.getMethod("isExported", String.class, moduleType);
- isExportedUnqualified = moduleType.getMethod("isExported", String.class);
- canRead = moduleType.getMethod("canRead", moduleType);
- addExports = moduleType.getMethod("addExports", String.class, moduleType);
- addReads = moduleType.getMethod("addReads", moduleType);
- addOpens = moduleType.getMethod("addOpens", String.class, moduleType);
- forName = Class.class.getMethod("forName", String.class);
- }
-
- @Override
- 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));
- }
-
- @Override
- boolean canRead(Class<?> source, Class<?> target) {
- return (Boolean) invoke(canRead, invoke(getModule, source), invoke(getModule, target));
- }
-
- @Override
- boolean isExported(Class<?> source) {
- if (source.getPackage() == null) {
- return true;
- }
- return (Boolean) invoke(isExportedUnqualified, invoke(getModule, source), source.getPackage().getName());
- }
-
- @Override
- 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));
- }
-
- @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)) {
- return InjectionBase.class;
- } else {
- synchronized (this) {
- String name;
- int suffix = injectonBaseSuffix;
- do {
- 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.
- if (type.getClassLoader() == classLoader) {
- return type;
- }
- } catch (ClassNotFoundException ignored) {
- break;
- }
- } while (true);
- return byteBuddy.subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
- .name(name)
- .make()
- .load(classLoader, loader.resolveStrategy(InjectionBase.class, classLoader, false))
- .getLoaded();
- }
- }
- }
-
- @Override
- void adjustModuleGraph(Class<?> source, Class<?> target, boolean export, boolean read) {
- boolean needsExport = export && !isExported(source, target);
- boolean needsRead = read && !canRead(source, target);
- if (!needsExport && !needsRead) {
- return;
- }
- 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));
- }
- boolean targetVisible = classLoader == target.getClassLoader();
- while (!targetVisible && classLoader != null) {
- classLoader = classLoader.getParent();
- targetVisible = classLoader == target.getClassLoader();
- }
- MethodCall targetLookup;
- Implementation.Composable implementation;
- if (targetVisible) {
- 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();
- 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);
- }
- targetLookup = MethodCall.invoke(getModule).onField(field);
- implementation = MethodCall.invoke(getModule).onMethodCall(MethodCall.invoke(forName).with(intermediate.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));
- }
- if (needsRead) {
- 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());
- } 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);
- }
- }
-
- 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);
- }
- }
- }
-
- private static class NoModuleSystemFound extends ModuleHandler {
-
- @Override
- boolean isOpened(Class<?> source, Class<?> target) {
- return true;
- }
-
- @Override
- boolean canRead(Class<?> source, Class<?> target) {
- return true;
- }
-
- @Override
- boolean isExported(Class<?> source) {
- return true;
- }
-
- @Override
- boolean isExported(Class<?> source, Class<?> target) {
- return true;
- }
-
- @Override
- Class<?> injectionBase(ClassLoader classLoader, String tyoeName) {
- return InjectionBase.class;
- }
-
- @Override
- void adjustModuleGraph(Class<?> source, Class<?> target, boolean export, boolean read) {
- // empty
- }
- }
-}
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 093978d..b659c73 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
@@ -15,7 +15,6 @@
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.attribute.MethodAttributeAppender;
import net.bytebuddy.matcher.ElementMatcher;
-import org.mockito.codegen.InjectionBase;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.creation.bytebuddy.ByteBuddyCrossClassLoaderSerializationSupport.CrossClassLoaderSerializableMock;
import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.DispatcherDefaultingToRealMethod;
@@ -27,9 +26,6 @@
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
import java.util.Random;
import static java.lang.Thread.currentThread;
@@ -45,9 +41,10 @@
private static final String CODEGEN_PACKAGE = "org.mockito.codegen.";
private final SubclassLoader loader;
- private final ModuleHandler handler;
+
private final ByteBuddy byteBuddy;
private final Random random;
+
private final Implementation readReplace;
private final ElementMatcher<? super MethodDescription> matcher;
@@ -74,128 +71,95 @@
this.matcher = matcher;
byteBuddy = new ByteBuddy().with(TypeValidation.DISABLED);
random = new Random();
- handler = ModuleHandler.make(byteBuddy, loader, random);
}
@Override
public <T> Class<? extends T> mockClass(MockFeatures<T> 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
- // 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));
- String typeName;
- if (localMock || loader instanceof MultipleParentClassLoader && !isComingFromJDK(features.mockedType)) {
- typeName = features.mockedType.getName();
- } else {
- typeName = InjectionBase.class.getPackage().getName() + "." + features.mockedType.getSimpleName();
- }
- String name = String.format("%s$%s$%d", typeName, "MockitoMock", Math.abs(random.nextInt()));
-
- if (localMock) {
- handler.adjustModuleGraph(features.mockedType, MockAccess.class, false, true);
- for (Class<?> iFace : features.interfaces) {
- handler.adjustModuleGraph(iFace, features.mockedType, true, false);
- handler.adjustModuleGraph(features.mockedType, iFace, false, true);
- }
- } else {
- boolean exported = handler.isExported(features.mockedType);
- Iterator<Class<?>> it = features.interfaces.iterator();
- 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
- // worthy performance optimization.
- if (exported) {
- assertVisibility(features.mockedType);
- for (Class<?> iFace : features.interfaces) {
- assertVisibility(iFace);
- }
- } else {
- Class<?> hook = handler.injectionBase(classLoader, typeName);
- assertVisibility(features.mockedType);
- handler.adjustModuleGraph(features.mockedType, hook, true, false);
- for (Class<?> iFace : features.interfaces) {
- assertVisibility(iFace);
- handler.adjustModuleGraph(iFace, hook, true, false);
- }
- }
- }
-
- DynamicType.Builder<T> builder = byteBuddy.subclass(features.mockedType)
- .name(name)
- .ignoreAlso(isGroovyMethod())
- .annotateType(features.stripAnnotations
- ? new Annotation[0]
- : features.mockedType.getAnnotations())
- .implement(new ArrayList<Type>(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());
+ String name = nameFor(features.mockedType);
+ DynamicType.Builder<T> builder =
+ byteBuddy.subclass(features.mockedType)
+ .name(name)
+ .ignoreAlso(isGroovyMethod())
+ .annotateType(features.stripAnnotations
+ ? new Annotation[0]
+ : features.mockedType.getAnnotations())
+ .implement(new ArrayList<Type>(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);
+ .intercept(writeReplace);
}
if (readReplace != null) {
builder = builder.defineMethod("readObject", void.class, Visibility.PRIVATE)
- .withParameters(ObjectInputStream.class)
- .throwing(ClassNotFoundException.class, IOException.class)
- .intercept(readReplace);
+ .withParameters(ObjectInputStream.class)
+ .throwing(ClassNotFoundException.class, IOException.class)
+ .intercept(readReplace);
}
- if (name.startsWith(CODEGEN_PACKAGE) || classLoader instanceof MultipleParentClassLoader) {
+ ClassLoader classLoader = new MultipleParentClassLoader.Builder()
+ .append(features.mockedType)
+ .append(features.interfaces)
+ .append(currentThread().getContextClassLoader())
+ .append(MockAccess.class, DispatcherDefaultingToRealMethod.class)
+ .append(MockMethodInterceptor.class,
+ MockMethodInterceptor.ForHashCode.class,
+ MockMethodInterceptor.ForEquals.class).build(MockMethodInterceptor.class.getClassLoader());
+ if (classLoader != features.mockedType.getClassLoader()) {
+ assertVisibility(features.mockedType);
+ for (Class<?> iFace : features.interfaces) {
+ assertVisibility(iFace);
+ }
builder = builder.ignoreAlso(isPackagePrivate()
.or(returns(isPackagePrivate()))
.or(hasParameters(whereAny(hasType(isPackagePrivate())))));
}
return builder.make()
- .load(classLoader, loader.resolveStrategy(features.mockedType, classLoader, localMock))
- .getLoaded();
- }
-
- private <T> Collection<Class<? super T>> getAllTypes(Class<T> type) {
- Collection<Class<? super T>> supertypes = new LinkedList<Class<? super T>>();
- supertypes.add(type);
- Class<? super T> superType = type;
- while (superType != null) {
- supertypes.add(superType);
- superType = superType.getSuperclass();
- }
- return supertypes;
+ .load(classLoader, loader.resolveStrategy(features.mockedType, classLoader, name.startsWith(CODEGEN_PACKAGE)))
+ .getLoaded();
}
private static ElementMatcher<MethodDescription> isGroovyMethod() {
return isDeclaredBy(named("groovy.lang.GroovyObjectSupport"));
}
+ // TODO inspect naming strategy (for OSGI, signed package, java.* (and bootstrap classes), etc...)
+ private String nameFor(Class<?> type) {
+ String typeName = type.getName();
+ if (isComingFromJDK(type)
+ || isComingFromSignedJar(type)
+ || isComingFromSealedPackage(type)) {
+ typeName = CODEGEN_PACKAGE + type.getSimpleName();
+ }
+ return String.format("%s$%s$%d", typeName, "MockitoMock", Math.abs(random.nextInt()));
+ }
+
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.");
+ || type.getName().startsWith("java.")
+ || type.getName().startsWith("javax.");
+ }
+
+ private boolean isComingFromSealedPackage(Class<?> type) {
+ return type.getPackage() != null && type.getPackage().isSealed();
+ }
+
+ private boolean isComingFromSignedJar(Class<?> type) {
+ return type.getSigners() != null;
}
private static void assertVisibility(Class<?> type) {
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 89b0a30..454dd8e 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassInjectionLoader.java
@@ -25,7 +25,7 @@
private final SubclassLoader loader;
SubclassInjectionLoader() {
- if (!Boolean.getBoolean("org.mockito.internal.noUnsafeInjection") && ClassInjector.UsingReflection.isAvailable()) {
+ if (!Boolean.getBoolean("org.mockito.internal.simulateJava11") && ClassInjector.UsingReflection.isAvailable()) {
this.loader = new WithReflection();
} else if (ClassInjector.UsingLookup.isAvailable()) {
this.loader = tryLookup();
@@ -49,13 +49,8 @@
private static class WithReflection implements SubclassLoader {
@Override
- public boolean isDisrespectingOpenness() {
- return true;
- }
-
- @Override
- public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean localMock) {
- return ClassLoadingStrategy.Default.INJECTION.with(localMock ? mockedType.getProtectionDomain() : InjectionBase.class.getProtectionDomain());
+ public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean codegen) {
+ return ClassLoadingStrategy.Default.INJECTION.with(codegen ? InjectionBase.class.getProtectionDomain() : mockedType.getProtectionDomain());
}
}
@@ -74,13 +69,12 @@
}
@Override
- public boolean isDisrespectingOpenness() {
- return false;
- }
-
- @Override
- public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean localMock) {
- if (localMock) {
+ public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean codegen) {
+ if (codegen) {
+ return ClassLoadingStrategy.UsingLookup.of(codegenLookup);
+ } else if (classLoader != mockedType.getClassLoader()) {
+ return ClassLoadingStrategy.Default.WRAPPER.with(mockedType.getProtectionDomain());
+ } else {
try {
Object privateLookup;
try {
@@ -102,21 +96,12 @@
exception
));
}
- } else if (classLoader == InjectionBase.class.getClassLoader()) {
- return ClassLoadingStrategy.UsingLookup.of(codegenLookup);
- } else {
- return ClassLoadingStrategy.Default.WRAPPER.with(mockedType.getProtectionDomain());
}
}
}
@Override
- public boolean isDisrespectingOpenness() {
- return loader.isDisrespectingOpenness();
- }
-
- @Override
- public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean localMock) {
- return loader.resolveStrategy(mockedType, classLoader, localMock);
+ public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean codegen) {
+ return loader.resolveStrategy(mockedType, classLoader, codegen);
}
}
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 011504e..194c282 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassLoader.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassLoader.java
@@ -12,19 +12,12 @@
public interface SubclassLoader {
/**
- * Checks if this loader does not require a module to be open.
- *
- * @return {@code true} if this loader is not constraint to a target module being opened for loading a class.
- */
- boolean isDisrespectingOpenness();
-
- /**
* Resolves a class loading strategy.
*
* @param mockedType The type being mocked.
* @param classLoader The class loader being used.
- * @param localMock {@code true} if the mock is loaded within the runtime package of the mocked type.
+ * @param codegen {@code true} if the mock is loaded in the {@code org.mockito.codegen} package.
* @return An appropriate class loading strategy.
*/
- ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean localMock);
+ ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean codegen);
}
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
deleted file mode 100644
index 12e30db..0000000
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2016 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.creation.bytebuddy.inject;
-
-import java.lang.reflect.Method;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public abstract class MockMethodDispatcher {
-
- private static final ConcurrentMap<String, MockMethodDispatcher> INSTANCE = new ConcurrentHashMap<String, MockMethodDispatcher>();
-
- public static MockMethodDispatcher get(String identifier, Object mock) {
- if (mock == INSTANCE) { // Avoid endless loop if ConcurrentHashMap was redefined to check for being a mock.
- return null;
- } else {
- return INSTANCE.get(identifier);
- }
- }
-
- 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 boolean isMock(Object instance);
-
- public abstract boolean isMocked(Object instance);
-
- public abstract boolean isOverridden(Object instance, Method origin);
-}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/inject/package-info.java b/src/main/java/org/mockito/internal/creation/bytebuddy/inject/package-info.java
deleted file mode 100644
index 5abed05..0000000
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/inject/package-info.java
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-/**
- * Internal classes, not to be used by clients. Intended for injection into the bootstrap class loader.
- *
- * Subject to change at any time without notice.
- */
-package org.mockito.internal.creation.bytebuddy.inject;
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 3b45592..03afd80 100644
--- a/src/main/java/org/mockito/internal/creation/settings/CreationSettings.java
+++ b/src/main/java/org/mockito/internal/creation/settings/CreationSettings.java
@@ -4,8 +4,8 @@
*/
package org.mockito.internal.creation.settings;
+import org.mockito.internal.listeners.StubbingLookupListener;
import org.mockito.listeners.InvocationListener;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.MockName;
@@ -18,7 +18,6 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
public class CreationSettings<T> implements MockCreationSettings<T>, Serializable {
private static final long serialVersionUID = -6789800638070123629L;
@@ -31,11 +30,7 @@
protected MockName mockName;
protected SerializableMode serializableMode = SerializableMode.NONE;
protected List<InvocationListener> invocationListeners = new ArrayList<InvocationListener>();
-
- //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<StubbingLookupListener> stubbingLookupListeners = new CopyOnWriteArrayList<StubbingLookupListener>();
-
+ protected final List<StubbingLookupListener> stubbingLookupListeners = new ArrayList<StubbingLookupListener>();
protected List<VerificationStartedListener> verificationStartedListeners = new LinkedList<VerificationStartedListener>();
protected boolean stubOnly;
protected boolean stripAnnotations;
@@ -48,7 +43,6 @@
@SuppressWarnings("unchecked")
public CreationSettings(CreationSettings copy) {
- //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;
@@ -57,14 +51,12 @@
this.mockName = copy.mockName;
this.serializableMode = copy.serializableMode;
this.invocationListeners = copy.invocationListeners;
- this.stubbingLookupListeners = copy.stubbingLookupListeners;
this.verificationStartedListeners = copy.verificationStartedListeners;
this.stubOnly = copy.stubOnly;
this.useConstructor = copy.isUsingConstructor();
this.outerClassInstance = copy.getOuterClassInstance();
this.constructorArgs = copy.getConstructorArgs();
this.lenient = copy.lenient;
- this.stripAnnotations = copy.stripAnnotations;
}
@Override
diff --git a/src/main/java/org/mockito/internal/debugging/LocationImpl.java b/src/main/java/org/mockito/internal/debugging/LocationImpl.java
index f1d14a6..8561b62 100644
--- a/src/main/java/org/mockito/internal/debugging/LocationImpl.java
+++ b/src/main/java/org/mockito/internal/debugging/LocationImpl.java
@@ -16,7 +16,6 @@
private final Throwable stackTraceHolder;
private final StackTraceFilter stackTraceFilter;
- private final String sourceFile;
public LocationImpl() {
this(defaultStackTraceFilter);
@@ -33,13 +32,6 @@
private LocationImpl(StackTraceFilter stackTraceFilter, Throwable stackTraceHolder) {
this.stackTraceFilter = stackTraceFilter;
this.stackTraceHolder = stackTraceHolder;
- if (stackTraceHolder.getStackTrace() == null || stackTraceHolder.getStackTrace().length == 0) {
- //there are corner cases where exception can have a null or empty stack trace
- //for example, a custom exception can override getStackTrace() method
- this.sourceFile = "<unknown source file>";
- } else {
- this.sourceFile = stackTraceFilter.findSourceFile(stackTraceHolder.getStackTrace(), "<unknown source file>");
- }
}
@Override
@@ -51,9 +43,4 @@
}
return "-> at " + filtered[0].toString();
}
-
- @Override
- public String getSourceFile() {
- return sourceFile;
- }
}
diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 1b68fbb..2bc4445 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -26,6 +26,7 @@
import org.mockito.invocation.InvocationOnMock;
import org.mockito.invocation.Location;
import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockName;
import org.mockito.mock.SerializableMode;
import java.lang.reflect.Field;
@@ -83,7 +84,7 @@
"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",
+ " 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed",
""
));
}
@@ -276,10 +277,10 @@
));
}
- public static MockitoException stubPassedToVerify(Object mock) {
+ public static MockitoException stubPassedToVerify() {
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."
+ "Argument passed to verify() is a stubOnly() mock, not a full blown mock!",
+ "If you intend to verify invocations on a mock, don't use stubOnly() in its MockSettings."
));
}
@@ -436,7 +437,7 @@
return new NoInteractionsWanted(join(
"No interactions wanted here:",
new LocationImpl(),
- "But found this interaction on mock '" + MockUtil.getMockName(undesired.getMock()) + "':",
+ "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",
undesired.getLocation(),
scenario
));
@@ -446,7 +447,7 @@
return new VerificationInOrderFailure(join(
"No interactions wanted here:",
new LocationImpl(),
- "But found this interaction on mock '" + MockUtil.getMockName(undesired.getMock()) + "':",
+ "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",
undesired.getLocation()
));
}
@@ -512,7 +513,7 @@
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.",
+ "The default answer of " + safelyGetMockName(mock) + " that was configured on the mock is probably incorrectly implemented.",
""
));
}
@@ -672,7 +673,7 @@
}
public static MockitoException fieldInitialisationThrewException(Field field, Throwable details) {
- return new InjectMocksException(join(
+ return new MockitoException(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(),
@@ -684,8 +685,8 @@
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 invocationListenersRequiresAtLeastOneListener() {
+ return new MockitoException("invocationListeners() requires at least one listener");
}
public static MockitoException invocationListenerThrewException(InvocationListener listener, Throwable listenerThrowable) {
@@ -696,7 +697,7 @@
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 ",
+ "Mockito couldn't inject mock dependency '" + safelyGetMockName(matchingMock) + "' on field ",
"'" + field + "'",
"whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",
"Also I failed because: " + exceptionCauseMessageIfAvailable(details),
@@ -739,7 +740,7 @@
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() + "()",
+ " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
"",
(willReturnLastParameter ?
"Last parameter wanted" :
@@ -773,7 +774,7 @@
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() + "()",
+ " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
"",
"The reason for this error can be :",
"1. The wanted argument position is incorrect.",
@@ -810,7 +811,7 @@
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),
+ "When calling: " + mockMethod + " on mock: " + safelyGetMockName(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() + ")"
@@ -820,7 +821,7 @@
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),
+ "When calling: " + mockMethod + " on mock: " + safelyGetMockName(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() + ")"
@@ -848,6 +849,10 @@
"This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter."));
}
+ private static MockName safelyGetMockName(Object mock) {
+ return MockUtil.getMockName(mock);
+ }
+
public static UnnecessaryStubbingException formatUnncessaryStubbingException(Class<?> testClass, Collection<Invocation> unnecessaryStubbings) {
StringBuilder stubbings = new StringBuilder();
int count = 1;
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 bf11d4c..e8b0cb0 100644
--- a/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
+++ b/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
@@ -37,17 +37,4 @@
StackTraceElement[] result = new StackTraceElement[filtered.size()];
return filtered.toArray(result);
}
-
- /**
- * Finds the source file of the target stack trace.
- * Returns the default value if source file cannot be found.
- */
- public String findSourceFile(StackTraceElement[] target, String defaultValue) {
- for (StackTraceElement e : target) {
- if (CLEANER.isIn(e)) {
- return e.getFileName();
- }
- }
- return defaultValue;
- }
}
diff --git a/src/main/java/org/mockito/internal/framework/DefaultMockitoFramework.java b/src/main/java/org/mockito/internal/framework/DefaultMockitoFramework.java
index d92fc28..69a733c 100644
--- a/src/main/java/org/mockito/internal/framework/DefaultMockitoFramework.java
+++ b/src/main/java/org/mockito/internal/framework/DefaultMockitoFramework.java
@@ -10,8 +10,6 @@
import org.mockito.internal.util.Checks;
import org.mockito.invocation.InvocationFactory;
import org.mockito.listeners.MockitoListener;
-import org.mockito.plugins.InlineMockMaker;
-import org.mockito.plugins.MockMaker;
import org.mockito.plugins.MockitoPlugins;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
@@ -39,25 +37,4 @@
public InvocationFactory getInvocationFactory() {
return new DefaultInvocationFactory();
}
-
- private InlineMockMaker getInlineMockMaker() {
- MockMaker mockMaker = Plugins.getMockMaker();
- return (mockMaker instanceof InlineMockMaker) ? (InlineMockMaker) mockMaker : null;
- }
-
- @Override
- public void clearInlineMocks() {
- InlineMockMaker mockMaker = getInlineMockMaker();
- if (mockMaker != null) {
- mockMaker.clearAllMocks();
- }
- }
-
- @Override
- public void clearInlineMock(Object mock) {
- InlineMockMaker mockMaker = getInlineMockMaker();
- if (mockMaker != null) {
- mockMaker.clearMock(mock);
- }
- }
}
diff --git a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java
index 6483a1c..c900bf7 100644
--- a/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java
+++ b/src/main/java/org/mockito/internal/framework/DefaultMockitoSession.java
@@ -11,17 +11,19 @@
import org.mockito.internal.exceptions.Reporter;
import org.mockito.internal.junit.TestFinishedEvent;
import org.mockito.internal.junit.UniversalTestListener;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.quality.Strictness;
import java.util.List;
public class DefaultMockitoSession implements MockitoSession {
+ private final List<Object> testClassInstances;
private final String name;
private final UniversalTestListener listener;
public DefaultMockitoSession(List<Object> testClassInstances, String name, Strictness strictness, MockitoLogger logger) {
+ this.testClassInstances = testClassInstances;
this.name = name;
listener = new UniversalTestListener(strictness, logger);
try {
@@ -30,14 +32,8 @@
} catch (RedundantListenerException e) {
Reporter.unfinishedMockingSession();
}
- try {
- for (Object testClassInstance : testClassInstances) {
- MockitoAnnotations.initMocks(testClassInstance);
- }
- } catch (RuntimeException e) {
- //clean up in case 'initMocks' fails
- listener.setListenerDirty();
- throw e;
+ for (Object testClassInstance : testClassInstances) {
+ MockitoAnnotations.initMocks(testClassInstance);
}
}
diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
index ec1fcba..b9cf072 100644
--- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
+++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
@@ -4,7 +4,6 @@
*/
package org.mockito.internal.invocation;
-import org.mockito.ArgumentMatcher;
import org.mockito.internal.invocation.mockref.MockReference;
import org.mockito.internal.exceptions.VerificationAwareInvocation;
import org.mockito.internal.reporting.PrintSettings;
@@ -14,10 +13,8 @@
import java.lang.reflect.Method;
import java.util.Arrays;
-import java.util.List;
import static org.mockito.internal.exceptions.Reporter.cannotCallAbstractRealMethod;
-import static org.mockito.internal.invocation.ArgumentsProcessor.argumentsToMatchers;
public class InterceptedInvocation implements Invocation, VerificationAwareInvocation {
@@ -122,28 +119,6 @@
return (T) arguments[index];
}
- public MockReference<Object> getMockRef() {
- return mockRef;
- }
-
- public MockitoMethod getMockitoMethod() {
- return mockitoMethod;
- }
-
- public RealMethod getRealMethod() {
- return realMethod;
- }
-
- @Override
- public List<ArgumentMatcher> getArgumentsAsMatchers() {
- return argumentsToMatchers(getArguments());
- }
-
- @Override
- public <T> T getArgument(int index, Class<T> clazz) {
- return clazz.cast(arguments[index]);
- }
-
@Override
public Object callRealMethod() throws Throwable {
if (!realMethod.isInvokable()) {
@@ -174,7 +149,7 @@
}
public String toString() {
- return new PrintSettings().print(getArgumentsAsMatchers(), this);
+ return new PrintSettings().print(ArgumentsProcessor.argumentsToMatchers(getArguments()), this);
}
public final static RealMethod NO_OP = new RealMethod() {
diff --git a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
index bc14300..83a28ff 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
@@ -5,6 +5,7 @@
package org.mockito.internal.invocation;
+import static org.mockito.internal.invocation.ArgumentsProcessor.argumentsToMatchers;
import static org.mockito.internal.invocation.MatcherApplicationStrategy.getMatcherApplicationStrategyFor;
import static org.mockito.internal.invocation.TypeSafeMatching.matchesTypeSafe;
@@ -35,7 +36,7 @@
public InvocationMatcher(Invocation invocation, List<ArgumentMatcher> matchers) {
this.invocation = invocation;
if (matchers.isEmpty()) {
- this.matchers = (List) invocation.getArgumentsAsMatchers();
+ this.matchers = (List) argumentsToMatchers(invocation.getArguments());
} else {
this.matchers = (List) matchers;
}
diff --git a/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java b/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java
index b5d2022..4885d63 100644
--- a/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java
+++ b/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java
@@ -5,14 +5,13 @@
package org.mockito.internal.junit;
import org.mockito.internal.exceptions.Reporter;
+import org.mockito.internal.listeners.StubbingLookupEvent;
+import org.mockito.internal.listeners.StubbingLookupListener;
import org.mockito.internal.stubbing.UnusedStubbingReporting;
import org.mockito.invocation.Invocation;
-import org.mockito.listeners.StubbingLookupEvent;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.quality.Strictness;
import org.mockito.stubbing.Stubbing;
-import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
@@ -23,9 +22,7 @@
* Default implementation of stubbing lookup listener.
* Fails early if stub called with unexpected arguments, but only if current strictness is set to STRICT_STUBS.
*/
-class DefaultStubbingLookupListener implements StubbingLookupListener, Serializable {
-
- private static final long serialVersionUID = -6789800638070123629L;
+class DefaultStubbingLookupListener implements StubbingLookupListener {
private Strictness currentStrictness;
private boolean mismatchesReported;
@@ -60,11 +57,8 @@
List<Invocation> matchingStubbings = new LinkedList<Invocation>();
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())) {
+ matchingStubbings.add(s.getInvocation());
}
}
return matchingStubbings;
diff --git a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
index 5db296e..3664aea 100644
--- a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
+++ b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
@@ -4,58 +4,49 @@
*/
package org.mockito.internal.junit;
+import junit.framework.ComparisonFailure;
import org.mockito.exceptions.verification.ArgumentsAreDifferent;
public class ExceptionFactory {
+ private final static boolean hasJUnit = canLoadJunitClass();
+
private ExceptionFactory() {
}
- private static interface ExceptionFactoryImpl {
- AssertionError create(String message, String wanted, String actual);
+ /**
+ * If JUnit is used, an AssertionError is returned that extends from JUnit {@link ComparisonFailure} and hence provide a better IDE support as the comparison result is comparable
+ */
+ public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
+ if (hasJUnit) {
+ return createJUnitArgumentsAreDifferent(message, wanted, actual);
+ }
+ return new ArgumentsAreDifferent(message);
}
- private final static ExceptionFactoryImpl factory;
+ private static AssertionError createJUnitArgumentsAreDifferent(String message, String wanted, String actual) {
+ return JUnitArgsAreDifferent.create(message, wanted, actual);
+ }
- static {
- ExceptionFactoryImpl theFactory = null;
-
+ private static boolean canLoadJunitClass() {
try {
- theFactory = new ExceptionFactoryImpl() {
- @Override
- public AssertionError create(String message, String wanted, String actual) {
- return new org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent(message, wanted, actual);
- }
- };
- } catch (Throwable onlyIfOpenTestIsNotAvailable) {
- try {
- theFactory = new ExceptionFactoryImpl() {
- @Override
- public AssertionError create(String message, String wanted, String actual) {
- return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual);
- }
- };
- } catch (Throwable onlyIfJUnitIsNotAvailable) {
- }
+ JUnitArgsAreDifferent.create("message", "wanted", "actual");
+ } catch (NoClassDefFoundError onlyIfJUnitIsNotAvailable) {
+ return false;
}
- factory = (theFactory == null) ? new ExceptionFactoryImpl() {
- @Override
- public AssertionError create(String message, String wanted, String actual) {
- return new ArgumentsAreDifferent(message, wanted, actual);
- }
- } : theFactory;
+ return true;
}
/**
- * Returns an AssertionError that describes the fact that the arguments of an invocation are different.
- * If {@link org.opentest4j.AssertionFailedError} is on the class path (used by JUnit 5 and others),
- * it returns a class that extends it. Otherwise, if {@link junit.framework.ComparisonFailure} is on the
- * class path (shipped with JUnit 3 and 4), it will return a class that extends that. This provides
- * better IDE support as the comparison result can be opened in a visual diff. If neither are available,
- * it returns an instance of
- * {@link org.mockito.exceptions.verification.ArgumentsAreDifferent}.
+ * Don't inline this class! It allows create the JUnit-ArgumentsAreDifferent exception without the need to use reflection.
+ * <p>
+ * If JUnit is not available a call to {@link #create(String, String, String)} will throw a {@link NoClassDefFoundError}.
+ * The {@link NoClassDefFoundError} will be thrown by the class loader cause the JUnit class {@link ComparisonFailure}
+ * can't be loaded which is a upper class of ArgumentsAreDifferent.
*/
- public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
- return factory.create(message, wanted, actual);
+ private static class JUnitArgsAreDifferent {
+ static AssertionError create(String message, String wanted, String actual) {
+ return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(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 3bd3dac..b825416 100644
--- a/src/main/java/org/mockito/internal/junit/JUnitRule.java
+++ b/src/main/java/org/mockito/internal/junit/JUnitRule.java
@@ -7,10 +7,9 @@
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
import org.mockito.internal.session.MockitoSessionLoggerAdapter;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.quality.Strictness;
import org.mockito.junit.MockitoRule;
@@ -35,16 +34,12 @@
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
return new Statement() {
public void evaluate() throws Throwable {
- if (session == null) {
- session = Mockito.mockitoSession()
- .name(target.getClass().getSimpleName() + "." + method.getName())
- .strictness(strictness)
- .logger(new MockitoSessionLoggerAdapter(logger))
- .initMocks(target)
- .startMocking();
- } else {
- MockitoAnnotations.initMocks(target);
- }
+ session = Mockito.mockitoSession()
+ .name(target.getClass().getSimpleName() + "." + method.getName())
+ .strictness(strictness)
+ .logger(new MockitoSessionLoggerAdapter(logger))
+ .initMocks(target)
+ .startMocking();
Throwable testFailure = evaluateSafely(base);
session.finishMocking(testFailure);
if (testFailure != null) {
diff --git a/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java b/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java
index d705396..26d4e4e 100644
--- a/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java
+++ b/src/main/java/org/mockito/internal/junit/MismatchReportingTestListener.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.junit;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.mock.MockCreationSettings;
import java.util.Collection;
diff --git a/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java b/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java
index d23431b..9e60c31 100644
--- a/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java
+++ b/src/main/java/org/mockito/internal/junit/StrictStubsRunnerTestListener.java
@@ -4,6 +4,7 @@
*/
package org.mockito.internal.junit;
+import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.mock.MockCreationSettings;
import org.mockito.quality.Strictness;
@@ -21,8 +22,8 @@
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.
- settings.getStubbingLookupListeners().add(stubbingLookupListener);
+ //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/StubbingArgMismatches.java b/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java
index f125f60..3d6342c 100644
--- a/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java
+++ b/src/main/java/org/mockito/internal/junit/StubbingArgMismatches.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.junit;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.invocation.Invocation;
import java.util.LinkedHashMap;
diff --git a/src/main/java/org/mockito/internal/junit/UniversalTestListener.java b/src/main/java/org/mockito/internal/junit/UniversalTestListener.java
index d681823..66c9dee 100644
--- a/src/main/java/org/mockito/internal/junit/UniversalTestListener.java
+++ b/src/main/java/org/mockito/internal/junit/UniversalTestListener.java
@@ -5,8 +5,7 @@
package org.mockito.internal.junit;
import org.mockito.internal.creation.settings.CreationSettings;
-import org.mockito.internal.listeners.AutoCleanableListener;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.mock.MockCreationSettings;
import org.mockito.quality.Strictness;
@@ -19,14 +18,13 @@
* Will come handy when we offer tweaking strictness at the method level with annotation.
* Should be relatively easy to improve and offer tweaking strictness per mock.
*/
-public class UniversalTestListener implements MockitoTestListener, AutoCleanableListener {
+public class UniversalTestListener implements MockitoTestListener {
private Strictness currentStrictness;
private final MockitoLogger logger;
private Map<Object, MockCreationSettings> mocks = new IdentityHashMap<Object, MockCreationSettings>();
private DefaultStubbingLookupListener stubbingLookupListener;
- private boolean listenerDirty;
public UniversalTestListener(Strictness initialStrictness, MockitoLogger logger) {
this.currentStrictness = initialStrictness;
@@ -87,19 +85,4 @@
this.currentStrictness = strictness;
this.stubbingLookupListener.setCurrentStrictness(strictness);
}
-
- /**
- * See {@link AutoCleanableListener#isListenerDirty()}
- */
- @Override
- public boolean isListenerDirty() {
- return listenerDirty;
- }
-
- /**
- * Marks listener as dirty, scheduled for cleanup when the next session starts
- */
- public void setListenerDirty() {
- this.listenerDirty = true;
- }
}
diff --git a/src/main/java/org/mockito/internal/junit/UnusedStubbings.java b/src/main/java/org/mockito/internal/junit/UnusedStubbings.java
index d45b13d..3505d2c 100644
--- a/src/main/java/org/mockito/internal/junit/UnusedStubbings.java
+++ b/src/main/java/org/mockito/internal/junit/UnusedStubbings.java
@@ -5,7 +5,7 @@
package org.mockito.internal.junit;
import org.mockito.internal.exceptions.Reporter;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.invocation.Invocation;
import org.mockito.stubbing.Stubbing;
diff --git a/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
index e54d478..7c19d35 100644
--- a/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
+++ b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
@@ -75,7 +75,7 @@
this.numberOfFailures++;
this.builder.append('\n')
.append(this.numberOfFailures).append(". ")
- .append(message.trim()).append('\n');
+ .append(message.substring(1, message.length()));
}
private class VerificationWrapper implements VerificationMode {
@@ -89,7 +89,7 @@
public void verify(VerificationData data) {
try {
this.delegate.verify(data);
- } catch (AssertionError error) {
+ } catch (MockitoAssertionError error) {
VerificationCollectorImpl.this.append(error.getMessage());
}
}
diff --git a/src/main/java/org/mockito/internal/listeners/AutoCleanableListener.java b/src/main/java/org/mockito/internal/listeners/AutoCleanableListener.java
deleted file mode 100644
index cfd2a53..0000000
--- a/src/main/java/org/mockito/internal/listeners/AutoCleanableListener.java
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * Copyright (c) 2018 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.listeners;
-
-/**
- * Listener that is automatically cleaned up (removed from the the global list of subscribers).
- * For now, we don't intend to make this interface public.
- */
-public interface AutoCleanableListener {
-
- /**
- * Indicates that the listener is dirty and should be removed from the subscribers
- */
- boolean isListenerDirty();
-}
diff --git a/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java b/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java
index a0de0c3..3e55001 100644
--- a/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java
+++ b/src/main/java/org/mockito/internal/listeners/StubbingLookupNotifier.java
@@ -6,8 +6,6 @@
import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.invocation.Invocation;
-import org.mockito.listeners.StubbingLookupEvent;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.mock.MockCreationSettings;
import org.mockito.stubbing.Stubbing;
diff --git a/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java b/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java
index 5c4fbbc..2685ddf 100644
--- a/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java
+++ b/src/main/java/org/mockito/internal/progress/MockingProgressImpl.java
@@ -9,7 +9,6 @@
import org.mockito.internal.debugging.Localized;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.exceptions.Reporter;
-import org.mockito.internal.listeners.AutoCleanableListener;
import org.mockito.invocation.Location;
import org.mockito.listeners.MockCreationListener;
import org.mockito.listeners.MockitoListener;
@@ -20,8 +19,6 @@
import org.mockito.verification.VerificationStrategy;
import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
import java.util.Set;
import static org.mockito.internal.exceptions.Reporter.unfinishedStubbing;
@@ -157,28 +154,12 @@
}
public void addListener(MockitoListener listener) {
- addListener(listener, listeners);
- }
-
- static void addListener(MockitoListener listener, Set<MockitoListener> listeners) {
- List<MockitoListener> delete = new LinkedList<MockitoListener>();
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
- delete.add(existing);
- } else {
- Reporter.redundantMockitoListener(listener.getClass().getSimpleName());
- }
+ Reporter.redundantMockitoListener(listener.getClass().getSimpleName());
}
}
- //delete dirty listeners so they don't occupy state/memory and don't receive notifications
- for (MockitoListener toDelete : delete) {
- listeners.remove(toDelete);
- }
- listeners.add(listener);
+ this.listeners.add(listener);
}
public void removeListener(MockitoListener listener) {
diff --git a/src/main/java/org/mockito/internal/reporting/PrintSettings.java b/src/main/java/org/mockito/internal/reporting/PrintSettings.java
index 4fc5992..7986c35 100644
--- a/src/main/java/org/mockito/internal/reporting/PrintSettings.java
+++ b/src/main/java/org/mockito/internal/reporting/PrintSettings.java
@@ -5,6 +5,7 @@
package org.mockito.internal.reporting;
import org.mockito.ArgumentMatcher;
+import org.mockito.internal.invocation.ArgumentsProcessor;
import org.mockito.internal.matchers.text.MatchersPrinter;
import org.mockito.internal.util.MockUtil;
import org.mockito.invocation.Invocation;
@@ -54,7 +55,7 @@
}
public String print(Invocation invocation) {
- return print(invocation.getArgumentsAsMatchers(), invocation);
+ return print(ArgumentsProcessor.argumentsToMatchers(invocation.getArguments()), invocation);
}
public String print(MatchableInvocation invocation) {
diff --git a/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java b/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java
index 93aa32d..2f26ff1 100644
--- a/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java
+++ b/src/main/java/org/mockito/internal/runners/DefaultInternalRunner.java
@@ -30,29 +30,34 @@
public Object target;
private MockitoTestListener mockitoTestListener;
- protected Statement withBefores(FrameworkMethod method, final Object target, Statement statement) {
+ protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) {
this.target = target;
- final Statement base = super.withBefores(method, target, statement);
- return new Statement() {
- @Override
- public void evaluate() throws Throwable {
- // 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();
- }
- };
+ // 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);
+ return super.withBefores(method, target, statement);
}
public void run(final RunNotifier notifier) {
RunListener listener = new RunListener() {
+ private boolean started;
Throwable failure;
@Override
+ public void testStarted(Description description) throws Exception {
+ started = true;
+ }
+
+ @Override
public void testFailure(Failure failure) throws Exception {
this.failure = failure.getException();
+ // If the test fails during the setup, `testFinished` is never invoked
+ // Therefore, if we have not started, cleanup the testlistener
+ if (!started && mockitoTestListener != null) {
+ Mockito.framework().removeListener(mockitoTestListener);
+ }
}
@Override
diff --git a/src/main/java/org/mockito/internal/runners/RunnerFactory.java b/src/main/java/org/mockito/internal/runners/RunnerFactory.java
index efdb6b2..61456dc 100644
--- a/src/main/java/org/mockito/internal/runners/RunnerFactory.java
+++ b/src/main/java/org/mockito/internal/runners/RunnerFactory.java
@@ -5,12 +5,12 @@
package org.mockito.internal.runners;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.junit.MismatchReportingTestListener;
import org.mockito.internal.junit.MockitoTestListener;
import org.mockito.internal.junit.NoOpTestListener;
import org.mockito.internal.junit.StrictStubsRunnerTestListener;
import org.mockito.internal.runners.util.RunnerProvider;
+import org.mockito.internal.util.ConsoleMockitoLogger;
import org.mockito.internal.util.Supplier;
import java.lang.reflect.InvocationTargetException;
@@ -39,7 +39,7 @@
public InternalRunner createStrict(Class<?> klass) throws InvocationTargetException {
return create(klass, new Supplier<MockitoTestListener>() {
public MockitoTestListener get() {
- return new MismatchReportingTestListener(Plugins.getMockitoLogger());
+ return new MismatchReportingTestListener(new ConsoleMockitoLogger());
}
});
}
diff --git a/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java b/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java
index f47ee15..d9b21e5 100644
--- a/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java
+++ b/src/main/java/org/mockito/internal/session/DefaultMockitoSessionBuilder.java
@@ -5,9 +5,9 @@
package org.mockito.internal.session;
import org.mockito.MockitoSession;
-import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.framework.DefaultMockitoSession;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.ConsoleMockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.quality.Strictness;
import org.mockito.session.MockitoSessionBuilder;
import org.mockito.session.MockitoSessionLogger;
@@ -74,7 +74,7 @@
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);
+ MockitoLogger logger = this.logger == null ? new ConsoleMockitoLogger() : new MockitoLoggerAdapter(this.logger);
return new DefaultMockitoSession(effectiveTestClassInstances, effectiveName, effectiveStrictness, logger);
}
}
diff --git a/src/main/java/org/mockito/internal/session/MockitoLoggerAdapter.java b/src/main/java/org/mockito/internal/session/MockitoLoggerAdapter.java
index 2197317..b7329e7 100644
--- a/src/main/java/org/mockito/internal/session/MockitoLoggerAdapter.java
+++ b/src/main/java/org/mockito/internal/session/MockitoLoggerAdapter.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.session;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.session.MockitoSessionLogger;
class MockitoLoggerAdapter implements MockitoLogger {
diff --git a/src/main/java/org/mockito/internal/session/MockitoSessionLoggerAdapter.java b/src/main/java/org/mockito/internal/session/MockitoSessionLoggerAdapter.java
index f4770c5..2e8634b 100644
--- a/src/main/java/org/mockito/internal/session/MockitoSessionLoggerAdapter.java
+++ b/src/main/java/org/mockito/internal/session/MockitoSessionLoggerAdapter.java
@@ -4,7 +4,7 @@
*/
package org.mockito.internal.session;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.session.MockitoSessionLogger;
public class MockitoSessionLoggerAdapter implements MockitoSessionLogger {
diff --git a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
index 4c86cbd..6dd99cd 100644
--- a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
+++ b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
@@ -4,31 +4,17 @@
*/
package org.mockito.internal.stubbing;
-import org.mockito.internal.stubbing.answers.CallsRealMethods;
-import org.mockito.internal.stubbing.answers.Returns;
-import org.mockito.internal.stubbing.answers.ThrowsException;
-import org.mockito.stubbing.Answer;
-import org.mockito.stubbing.OngoingStubbing;
-
import static org.mockito.internal.exceptions.Reporter.notAnException;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
import static org.objenesis.ObjenesisHelper.newInstance;
+import org.mockito.internal.stubbing.answers.CallsRealMethods;
+import org.mockito.internal.stubbing.answers.Returns;
+import org.mockito.internal.stubbing.answers.ThrowsException;
+import org.mockito.stubbing.OngoingStubbing;
+
public abstract class BaseStubbing<T> implements OngoingStubbing<T> {
-
- // Keep strong ref to mock preventing premature garbage collection when using 'One-liner stubs'. See #1541.
- private final Object strongMockRef;
-
- BaseStubbing(Object mock) {
- this.strongMockRef = mock;
- }
-
- @Override
- public OngoingStubbing<T> then(Answer<?> answer) {
- return thenAnswer(answer);
- }
-
@Override
public OngoingStubbing<T> thenReturn(T value) {
return thenAnswer(new Returns(value));
@@ -93,12 +79,6 @@
public OngoingStubbing<T> thenCallRealMethod() {
return thenAnswer(new CallsRealMethods());
}
-
- @Override
- @SuppressWarnings("unchecked")
- public <M> M getMock() {
- return (M) this.strongMockRef;
- }
}
diff --git a/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java b/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java
index 32ef8ee..a5cdc04 100644
--- a/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java
+++ b/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java
@@ -8,17 +8,23 @@
import org.mockito.stubbing.OngoingStubbing;
public class ConsecutiveStubbing<T> extends BaseStubbing<T> {
+ private final InvocationContainerImpl invocationContainerImpl;
- private final InvocationContainerImpl invocationContainer;
-
- ConsecutiveStubbing(InvocationContainerImpl invocationContainer) {
- super(invocationContainer.invokedMock());
- this.invocationContainer = invocationContainer;
+ public ConsecutiveStubbing(InvocationContainerImpl invocationContainerImpl) {
+ this.invocationContainerImpl = invocationContainerImpl;
}
public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
- invocationContainer.addConsecutiveAnswer(answer);
+ invocationContainerImpl.addConsecutiveAnswer(answer);
return this;
}
+ public OngoingStubbing<T> then(Answer<?> answer) {
+ return thenAnswer(answer);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <M> M getMock() {
+ return (M) invocationContainerImpl.invokedMock();
+ }
}
diff --git a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
index 4191604..cd27c39 100644
--- a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
@@ -19,7 +19,6 @@
private Strictness strictness;
public OngoingStubbingImpl(InvocationContainerImpl invocationContainer) {
- super(invocationContainer.invokedMock());
this.invocationContainer = invocationContainer;
}
@@ -33,11 +32,22 @@
return new ConsecutiveStubbing<T>(invocationContainer);
}
+ @Override
+ public OngoingStubbing<T> then(Answer<?> answer) {
+ return thenAnswer(answer);
+ }
+
public List<Invocation> getRegisteredInvocations() {
//TODO interface for tests
return invocationContainer.getInvocations();
}
+ @Override
+ @SuppressWarnings("unchecked")
+ public <M> M getMock() {
+ return (M) invocationContainer.invokedMock();
+ }
+
public void setStrictness(Strictness strictness) {
this.strictness = strictness;
}
diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
index 42795a7..2172809 100644
--- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
@@ -87,16 +87,12 @@
mockingProgress().reset();
throw notAnException();
}
- Throwable e = null;
+ Throwable e;
try {
e = 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();
- }
+ } catch (RuntimeException instantiationError) {
+ mockingProgress().reset();
+ throw instantiationError;
}
return doThrow(e);
}
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 eaa6493..e1a92a4 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java
@@ -11,13 +11,11 @@
import org.mockito.stubbing.Answer3;
import org.mockito.stubbing.Answer4;
import org.mockito.stubbing.Answer5;
-import org.mockito.stubbing.Answer6;
import org.mockito.stubbing.VoidAnswer1;
import org.mockito.stubbing.VoidAnswer2;
import org.mockito.stubbing.VoidAnswer3;
import org.mockito.stubbing.VoidAnswer4;
import org.mockito.stubbing.VoidAnswer5;
-import org.mockito.stubbing.VoidAnswer6;
/**
* Functional interfaces to make it easy to implement answers in Java 8
@@ -238,60 +236,4 @@
}
};
}
-
- /**
- * Construct an answer from a six parameter answer interface
- *
- * @param answer answer interface
- * @param <T> return type
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
- * @param <C> input parameter 3 type
- * @param <D> input parameter 4 type
- * @param <E> input parameter 5 type
- * @param <F> input parameter 6 type
- * @return a new answer object
- */
- public static <T, A, B, C, D, E, F> Answer<T> toAnswer(final Answer6<T, A, B, C, D, E, F> answer) {
- return new Answer<T>() {
- @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));
- }
- };
- }
-
- /**
- * Construct an answer from a five parameter answer interface
-
- * @param answer answer interface
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
- * @param <C> input parameter 3 type
- * @param <D> input parameter 4 type
- * @param <E> input parameter 5 type
- * @param <F> input parameter 6 type
- * @return a new answer object
- */
- public static <A, B, C, D, E, F> Answer<Void> toAnswer(final VoidAnswer6<A, B, C, D, E, F> answer) {
- return new Answer<Void>() {
- @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));
- return null;
- }
- };
- }
}
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 7ef283c..9165142 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
@@ -40,11 +40,6 @@
}
Object[] rawArguments = ((Invocation) invocation).getRawArguments();
- try {
- delegateMethod.setAccessible(true);
- } catch (SecurityException ignore) {
- // try to invoke anyway
- }
return delegateMethod.invoke(delegatedObject, rawArguments);
} catch (NoSuchMethodException e) {
throw delegatedMethodDoesNotExistOnDelegate(mockMethod, invocation.getMock(), delegatedObject);
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java
deleted file mode 100644
index 979c8f7..0000000
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/RetrieveGenericsForDefaultAnswers.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.stubbing.defaultanswers;
-
-import java.lang.reflect.GenericArrayType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import org.mockito.internal.MockitoCore;
-import org.mockito.internal.util.MockUtil;
-import org.mockito.internal.util.reflection.GenericMetadataSupport;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.mock.MockCreationSettings;
-
-class RetrieveGenericsForDefaultAnswers {
-
- private static final MockitoCore MOCKITO_CORE = new MockitoCore();
-
- static Object returnTypeForMockWithCorrectGenerics(
- InvocationOnMock invocation, AnswerCallback answerCallback) {
- Class<?> type = invocation.getMethod().getReturnType();
-
- final Type returnType = invocation.getMethod().getGenericReturnType();
-
- Object defaultReturnValue = null;
-
- if (returnType instanceof TypeVariable) {
- type = findTypeFromGeneric(invocation, (TypeVariable) returnType);
- if (type != null) {
- defaultReturnValue = delegateChains(type);
- }
- }
-
- if (defaultReturnValue != null) {
- return defaultReturnValue;
- }
-
- if (type != null) {
- if (!MOCKITO_CORE.isTypeMockable(type)) {
- return null;
- }
-
- return answerCallback.apply(type);
- }
-
- return answerCallback.apply(null);
- }
-
- /**
- * Try to resolve the result value using {@link ReturnsEmptyValues} and {@link ReturnsMoreEmptyValues}.
- *
- * This will try to use all parent class (superclass & interfaces) to retrieve the value..
- *
- * @param type the return type of the method
- * @return a non-null instance if the type has been resolve. Null otherwise.
- */
- private static Object delegateChains(final Class<?> type) {
- final ReturnsEmptyValues returnsEmptyValues = new ReturnsEmptyValues();
- Object result = returnsEmptyValues.returnValueFor(type);
-
- if (result == null) {
- Class<?> emptyValueForClass = type;
- while (emptyValueForClass != null && result == null) {
- final Class<?>[] classes = emptyValueForClass.getInterfaces();
- for (Class<?> clazz : classes) {
- result = returnsEmptyValues.returnValueFor(clazz);
- if (result != null) {
- break;
- }
- }
- emptyValueForClass = emptyValueForClass.getSuperclass();
- }
- }
-
- if (result == null) {
- result = new ReturnsMoreEmptyValues().returnValueFor(type);
- }
-
- return result;
- }
-
- /**
- * Retrieve the expected type when it came from a primitive. If the type cannot be retrieve, return null.
- *
- * @param invocation the current invocation
- * @param returnType the expected return type
- * @return the type or null if not found
- */
- 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 Class<?> rawType = returnTypeSupport.rawType();
-
- // Method level
- if (rawType == Object.class) {
- return findTypeFromGenericInArguments(invocation, returnType);
- }
- return rawType;
- }
-
- /**
- * Find a return type using generic arguments provided by the calling method.
- *
- * @param invocation the current invocation
- * @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) {
- final Type[] parameterTypes = invocation.getMethod().getGenericParameterTypes();
- for (int i = 0; i < parameterTypes.length; i++) {
- Type argType = parameterTypes[i];
- if (returnType.equals(argType)) {
- Object argument = invocation.getArgument(i);
-
- if (argument == null) {
- return null;
- }
-
- return argument.getClass();
- }
- if (argType instanceof GenericArrayType) {
- argType = ((GenericArrayType) argType).getGenericComponentType();
- if (returnType.equals(argType)) {
- return invocation.getArgument(i).getClass();
- }
- }
- }
- return null;
- }
-
- interface AnswerCallback {
- Object apply(Class<?> type);
- }
-}
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 356b2e6..3909ff0 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
@@ -25,7 +25,7 @@
/**
* Returning deep stub implementation.
*
- * <p>Will return previously created mock if the invocation matches.
+ * Will return previously created mock if the invocation matches.
*
* <p>Supports nested generic information, with this answer you can write code like this :
*
@@ -37,8 +37,6 @@
* </code></pre>
* </p>
*
- * <p>However this answer does not support generics information when the mock has been deserialized.
- *
* @see org.mockito.Mockito#RETURNS_DEEP_STUBS
* @see org.mockito.Answers#RETURNS_DEEP_STUBS
*/
@@ -48,22 +46,13 @@
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)) {
return delegate().returnValueFor(rawType);
}
- // 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
- // 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
- // on runtime.
- if (rawType.equals(Object.class) && !returnTypeGenericMetadata.hasRawExtraInterfaces()) {
- return null;
- }
-
return deepStub(invocation, returnTypeGenericMetadata);
}
@@ -80,9 +69,9 @@
// record deep stub answer
StubbedInvocationMatcher stubbing = recordDeepStubAnswer(
- newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()),
- container
- );
+ newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()),
+ container
+ );
// deep stubbing creates a stubbing and immediately uses it
// so the stubbing is actually used by the same invocation
@@ -99,24 +88,24 @@
* {@link ReturnsDeepStubs} answer in which we will store the returned type generic metadata.
*
* @param returnTypeGenericMetadata The metadata to use to create the new mock.
- * @param parentMock The parent of the current deep stub mock.
+ * @param parentMock The parent of the current deep stub mock.
* @return The mock
*/
private Object newDeepStubMock(GenericMetadataSupport returnTypeGenericMetadata, Object parentMock) {
MockCreationSettings parentMockSettings = MockUtil.getMockSettings(parentMock);
return mockitoCore().mock(
- returnTypeGenericMetadata.rawType(),
- withSettingsUsing(returnTypeGenericMetadata, parentMockSettings)
- );
+ returnTypeGenericMetadata.rawType(),
+ withSettingsUsing(returnTypeGenericMetadata, parentMockSettings)
+ );
}
private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) {
MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ?
- withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
- : withSettings();
+ withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
+ : withSettings();
return propagateSerializationSettings(mockSettings, parentMockSettings)
- .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata));
+ .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata));
}
private MockSettings propagateSerializationSettings(MockSettings mockSettings, MockCreationSettings parentMockSettings) {
@@ -150,15 +139,6 @@
protected GenericMetadataSupport actualParameterizedType(Object mock) {
return returnTypeGenericMetadata;
}
-
- /**
- * Generics support and serialization with deep stubs don't work together.
- * <p>
- * The issue is that GenericMetadataSupport is not serializable because
- * the type elements inferred via reflection are not serializable. Supporting
- * serialization would require to replace all types coming from the Java reflection
- * with our own and still managing type equality with the JDK ones.
- */
private Object writeReplace() throws IOException {
return Mockito.RETURNS_DEEP_STUBS;
}
@@ -172,7 +152,6 @@
DeeplyStubbedAnswer(Object mock) {
this.mock = mock;
}
-
public Object answer(InvocationOnMock invocation) throws Throwable {
return mock;
}
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 5d4befe..302e4df 100755
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java
@@ -4,36 +4,33 @@
*/
package org.mockito.internal.stubbing.defaultanswers;
-import java.io.Serializable;
-import org.mockito.Mockito;
+import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import java.io.Serializable;
+
public class ReturnsMocks implements Answer<Object>, Serializable {
private static final long serialVersionUID = -6755257986994634579L;
+ private final MockitoCore mockitoCore = new MockitoCore();
private final Answer<Object> delegate = new ReturnsMoreEmptyValues();
- @Override
- public Object answer(final InvocationOnMock invocation) throws Throwable {
- Object defaultReturnValue = delegate.answer(invocation);
-
- if (defaultReturnValue != null) {
- return defaultReturnValue;
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Object ret = delegate.answer(invocation);
+ if (ret != null) {
+ return ret;
}
- return RetrieveGenericsForDefaultAnswers.returnTypeForMockWithCorrectGenerics(invocation,
- new RetrieveGenericsForDefaultAnswers.AnswerCallback() {
- @Override
- public Object apply(Class<?> type) {
- if (type == null) {
- type = invocation.getMethod().getReturnType();
- }
+ return returnValueFor(invocation.getMethod().getReturnType());
+ }
- return Mockito
- .mock(type, new MockSettingsImpl<Object>().defaultAnswer(ReturnsMocks.this));
- }
- });
+ Object returnValueFor(Class<?> clazz) {
+ if (!mockitoCore.isTypeMockable(clazz)) {
+ return null;
+ }
+
+ return mockitoCore.mock(clazz, new MockSettingsImpl().defaultAnswer(this));
}
}
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 6cf50c7..7487e89 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
@@ -8,6 +8,8 @@
import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
import java.io.Serializable;
+import java.lang.reflect.Modifier;
+
import org.mockito.Mockito;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.invocation.InvocationOnMock;
@@ -38,34 +40,24 @@
private final Answer<Object> delegate = new ReturnsMoreEmptyValues();
- @Override
public Object answer(final InvocationOnMock invocation) throws Throwable {
Object defaultReturnValue = delegate.answer(invocation);
-
if (defaultReturnValue != null) {
return defaultReturnValue;
}
-
- 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()));
- }
- });
+ Class<?> type = invocation.getMethod().getReturnType();
+ if (!type.isPrimitive() && !Modifier.isFinal(type.getModifiers())) {
+ final Location location = new LocationImpl();
+ return Mockito.mock(type, new ThrowsSmartNullPointer(invocation, location));
+ }
+ return null;
}
private static class ThrowsSmartNullPointer implements Answer {
-
private final InvocationOnMock unstubbedInvocation;
-
private final Location location;
- ThrowsSmartNullPointer(InvocationOnMock unstubbedInvocation, Location location) {
+ public ThrowsSmartNullPointer(InvocationOnMock unstubbedInvocation, Location location) {
this.unstubbedInvocation = unstubbedInvocation;
this.location = location;
}
@@ -73,7 +65,7 @@
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();
+ unstubbedInvocation.toString();
}
throw smartNullPointerException(unstubbedInvocation.toString(), location);
diff --git a/src/main/java/org/mockito/internal/util/ConsoleMockitoLogger.java b/src/main/java/org/mockito/internal/util/ConsoleMockitoLogger.java
index 3eb8939..d8df8eb 100644
--- a/src/main/java/org/mockito/internal/util/ConsoleMockitoLogger.java
+++ b/src/main/java/org/mockito/internal/util/ConsoleMockitoLogger.java
@@ -4,8 +4,6 @@
*/
package org.mockito.internal.util;
-import org.mockito.plugins.MockitoLogger;
-
public class ConsoleMockitoLogger implements MockitoLogger {
/* (non-Javadoc)
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 80cbf65..8efd384 100644
--- a/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
+++ b/src/main/java/org/mockito/internal/util/reflection/GenericMetadataSupport.java
@@ -8,23 +8,8 @@
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.Checks;
-import java.lang.reflect.GenericArrayType;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.lang.reflect.WildcardType;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Set;
+import java.lang.reflect.*;
+import java.util.*;
/**
@@ -32,20 +17,20 @@
* and accessible members.
*
* <p>
- * The main idea of this code is to create a Map that will help to resolve return types.
- * In order to actually work with nested generics, this map will have to be passed along new instances
- * as a type context.
+ * The main idea of this code is to create a Map that will help to resolve return types.
+ * In order to actually work with nested generics, this map will have to be passed along new instances
+ * as a type context.
* </p>
*
* <p>
- * Hence :
- * <ul>
- * <li>A new instance representing the metadata is created using the {@link #inferFrom(Type)} method from a real
- * <code>Class</code> or from a <code>ParameterizedType</code>, other types are not yet supported.</li>
+ * Hence :
+ * <ul>
+ * <li>A new instance representing the metadata is created using the {@link #inferFrom(Type)} method from a real
+ * <code>Class</code> or from a <code>ParameterizedType</code>, other types are not yet supported.</li>
*
- * <li>Then from this metadata, we can extract meta-data for a generic return type of a method, using
- * {@link #resolveGenericReturnType(Method)}.</li>
- * </ul>
+ * <li>Then from this metadata, we can extract meta-data for a generic return type of a method, using
+ * {@link #resolveGenericReturnType(Method)}.</li>
+ * </ul>
* </p>
*
* <p>
@@ -112,9 +97,8 @@
}
if (type instanceof TypeVariable) {
/*
- * If type is a TypeVariable, then it is needed to gather data elsewhere.
- * Usually TypeVariables are declared on the class definition, such as such
- * as List<E>.
+ * If type is a TypeVariable, then it is needed to gather data elsewhere. Usually TypeVariables are declared
+ * on the class definition, such as such as List<E>.
*/
return extractRawTypeOf(contextualActualTypeParameters.get(type));
}
@@ -132,23 +116,6 @@
TypeVariable<?> typeParameter = typeParameters[i];
Type actualTypeArgument = actualTypeArguments[i];
- if (actualTypeArgument instanceof TypeVariable) {
- /*
- * If actualTypeArgument is a TypeVariable, and it is not present in
- * the context map then it is needed to try harder to gather more data
- * from the type argument itself. In some case the type argument do
- * define upper bounds, this allow to look for them if not in the
- * context map.
- */
- 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.
- if (contextualActualTypeParameters.containsKey(typeParameter)) {
- continue;
- }
- }
-
if (actualTypeArgument instanceof WildcardType) {
contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));
} else if (typeParameter != actualTypeArgument) {
@@ -174,7 +141,7 @@
/**
* @param typeParameter The TypeVariable parameter
* @return A {@link BoundedType} for easy bound information, if first bound is a TypeVariable
- * then retrieve BoundedType of this TypeVariable
+ * then retrieve BoundedType of this TypeVariable
*/
private BoundedType boundsOf(TypeVariable<?> typeParameter) {
if (typeParameter.getBounds()[0] instanceof TypeVariable) {
@@ -186,17 +153,13 @@
/**
* @param wildCard The WildCard type
* @return A {@link BoundedType} for easy bound information, if first bound is a TypeVariable
- * then retrieve BoundedType of this TypeVariable
+ * then retrieve BoundedType of this TypeVariable
*/
private BoundedType boundsOf(WildcardType wildCard) {
/*
* According to JLS(http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.5.1):
- * - Lower and upper can't coexist: (for instance, this is not allowed:
- * <? extends List<String> & super MyInterface>)
- * - Multiple concrete type bounds are not supported (for instance, this is not allowed:
- * <? extends ArrayList<String> & MyInterface>)
- * But the following form is possible where there is a single concrete tyep bound followed by interface type bounds
- * <T extends List<String> & Comparable>
+ * - Lower and upper can't coexist: (for instance, this is not allowed: <? extends List<String> & super MyInterface>)
+ * - Multiple bounds are not supported (for instance, this is not allowed: <? extends List<String> & MyInterface>)
*/
WildCardBoundedType wildCardBoundedType = new WildCardBoundedType(wildCard);
@@ -272,7 +235,7 @@
// logger.log("Method '" + method.toGenericString() + "' has return type : " + genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType);
int arity = 0;
- while (genericReturnType instanceof GenericArrayType) {
+ while(genericReturnType instanceof GenericArrayType) {
arity++;
genericReturnType = ((GenericArrayType) genericReturnType).getGenericComponentType();
}
@@ -304,8 +267,8 @@
* Create an new instance of {@link GenericMetadataSupport} inferred from a {@link Type}.
*
* <p>
- * At the moment <code>type</code> can only be a {@link Class} or a {@link ParameterizedType}, otherwise
- * it'll throw a {@link MockitoException}.
+ * At the moment <code>type</code> can only be a {@link Class} or a {@link ParameterizedType}, otherwise
+ * it'll throw a {@link MockitoException}.
* </p>
*
* @param type The class from which the {@link GenericMetadataSupport} should be built.
@@ -331,7 +294,7 @@
/**
* Generic metadata implementation for {@link Class}.
- * <p>
+ *
* Offer support to retrieve generic metadata on a {@link Class} by reading type parameters and type variables on
* the class and its ancestors and interfaces.
*/
@@ -353,10 +316,10 @@
/**
* Generic metadata implementation for "standalone" {@link ParameterizedType}.
- * <p>
+ *
* Offer support to retrieve generic metadata on a {@link ParameterizedType} by reading type variables of
* the related raw type and declared type variable of this parameterized type.
- * <p>
+ *
* This class is not designed to work on ParameterizedType returned by {@link Method#getGenericReturnType()}, as
* the ParameterizedType instance return in these cases could have Type Variables that refer to type declaration(s).
* That's what meant the "standalone" word at the beginning of the Javadoc.
@@ -418,7 +381,6 @@
private final TypeVariable<?> typeVariable;
private final TypeVariable<?>[] typeParameters;
private Class<?> rawType;
- private List<Type> extraInterfaces;
public TypeVariableReturnType(GenericMetadataSupport source, TypeVariable<?>[] typeParameters, TypeVariable<?> typeVariable) {
this.typeParameters = typeParameters;
@@ -437,7 +399,7 @@
for (Type type : typeVariable.getBounds()) {
registerTypeVariablesOn(type);
}
- registerTypeParametersOn(new TypeVariable[]{typeVariable});
+ registerTypeParametersOn(new TypeVariable[] { typeVariable });
registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));
}
@@ -451,18 +413,15 @@
@Override
public List<Type> extraInterfaces() {
- if (extraInterfaces != null) {
- return extraInterfaces;
- }
Type type = extractActualBoundedTypeOf(typeVariable);
if (type instanceof BoundedType) {
- return extraInterfaces = Arrays.asList(((BoundedType) type).interfaceBounds());
+ return Arrays.asList(((BoundedType) type).interfaceBounds());
}
if (type instanceof ParameterizedType) {
- return extraInterfaces = Collections.singletonList(type);
+ return Collections.singletonList(type);
}
if (type instanceof Class) {
- return extraInterfaces = Collections.emptyList();
+ return Collections.emptyList();
}
throw new MockitoException("Cannot extract extra-interfaces from '" + typeVariable + "' : '" + type + "'");
}
@@ -477,7 +436,7 @@
for (Type extraInterface : extraInterfaces) {
Class<?> rawInterface = extractRawTypeOf(extraInterface);
// avoid interface collision with actual raw type (with typevariables, resolution ca be quite aggressive)
- if (!rawType().equals(rawInterface)) {
+ if(!rawType().equals(rawInterface)) {
rawExtraInterfaces.add(rawInterface);
}
}
@@ -549,6 +508,7 @@
}
+
/**
* Type representing bounds of a type
*
@@ -571,7 +531,7 @@
*
* <p>If upper bounds are declared with SomeClass and additional interfaces, then firstBound will be SomeClass and
* interfacesBound will be an array of the additional interfaces.
- * <p>
+ *
* i.e. <code>SomeClass</code>.
* <pre class="code"><code class="java">
* interface UpperBoundedTypeWithClass<E extends Comparable<E> & Cloneable> {
diff --git a/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
index 840efb7..eded985 100644
--- a/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
@@ -47,7 +47,6 @@
}
}
- //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/invocation/Invocation.java b/src/main/java/org/mockito/invocation/Invocation.java
index fa2e324..131db84 100644
--- a/src/main/java/org/mockito/invocation/Invocation.java
+++ b/src/main/java/org/mockito/invocation/Invocation.java
@@ -4,11 +4,8 @@
*/
package org.mockito.invocation;
-import org.mockito.ArgumentMatcher;
import org.mockito.NotExtensible;
-import java.util.List;
-
/**
* A method call on a mock object. Contains all information and state needed for the Mockito framework to operate.
* This API might be useful for developers who extend Mockito.
@@ -51,16 +48,6 @@
Object[] getRawArguments();
/**
- * Wraps each argument using {@link org.mockito.ArgumentMatchers#eq(Object)} or
- * {@link org.mockito.AdditionalMatchers#aryEq(Object[])}
- * Used internally for the purposes of human-readable invocation printing.
- *
- * @return a list of {@link ArgumentMatcher} wrapping each of this invocation arguments
- * @since 2.25.6
- */
- List<ArgumentMatcher> getArgumentsAsMatchers();
-
- /**
* Returns unprocessed arguments whereas {@link #getArguments()} returns
* arguments already processed (e.g. varargs expended, etc.).
*
diff --git a/src/main/java/org/mockito/invocation/InvocationOnMock.java b/src/main/java/org/mockito/invocation/InvocationOnMock.java
index 8fabfa0..345ddb9 100644
--- a/src/main/java/org/mockito/invocation/InvocationOnMock.java
+++ b/src/main/java/org/mockito/invocation/InvocationOnMock.java
@@ -7,7 +7,6 @@
import java.io.Serializable;
import java.lang.reflect.Method;
-import org.mockito.NotExtensible;
/**
* An invocation on a mock.
@@ -15,7 +14,6 @@
* <p>
* A placeholder for mock, the method that was called and the arguments that were passed.
*/
-@NotExtensible
public interface InvocationOnMock extends Serializable {
/**
@@ -46,10 +44,6 @@
*
* Can lookup in expanded arguments form {@link #getArguments()}.
*
- * This method is preferred over {@link #getArgument(int, Class)} for readability. Please read
- * the documentation of {@link #getArgument(int, Class)} for an overview of situations when
- * that method is preferred over this one.
- *
* @param index argument index
* @return casted argument at the given index
* @since 2.1.0
@@ -57,25 +51,6 @@
<T> T getArgument(int index);
/**
- * Returns casted argument at the given index. This method is analogous to
- * {@link #getArgument(int)}, but is necessary to circumvent issues when dealing with generics.
- *
- * In general, {@link #getArgument(int)} is the appropriate function to use. This particular
- * function is only necessary if you are doing one of the following things:
- *
- * 1. You want to directly invoke a method on the result of {@link #getArgument(int)}.
- * 2. You want to directly pas the result of the invocation into a function that accepts a generic parameter.
- *
- * If you prefer to use {@link #getArgument(int)} instead, you can circumvent the compilation
- * issues by storing the intermediate result into a local variable with the correct type.
- *
- * @param index argument index
- * @param clazz clazz to cast the argument to
- * @return casted argument at the given index
- */
- <T> T getArgument(int index, Class<T> clazz);
-
- /**
* calls real method
* <p>
* <b>Warning:</b> depending on the real implementation it might throw exceptions
diff --git a/src/main/java/org/mockito/invocation/Location.java b/src/main/java/org/mockito/invocation/Location.java
index 43b4832..e362704 100644
--- a/src/main/java/org/mockito/invocation/Location.java
+++ b/src/main/java/org/mockito/invocation/Location.java
@@ -4,26 +4,14 @@
*/
package org.mockito.invocation;
-import org.mockito.NotExtensible;
-
/**
* Describes the location of something in the source code.
*/
-@NotExtensible
public interface Location {
/**
- * Human readable location in the source code, see {@link Invocation#getLocation()}
- *
- * @return location
+ * @return the location
*/
String toString();
- /**
- * Source file of this location
- *
- * @return source file
- * @since 2.24.6
- */
- String getSourceFile();
}
diff --git a/src/main/java/org/mockito/junit/MockitoJUnit.java b/src/main/java/org/mockito/junit/MockitoJUnit.java
index c0fb55b..da9428b 100644
--- a/src/main/java/org/mockito/junit/MockitoJUnit.java
+++ b/src/main/java/org/mockito/junit/MockitoJUnit.java
@@ -5,9 +5,9 @@
package org.mockito.junit;
import org.mockito.Incubating;
-import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.junit.JUnitRule;
import org.mockito.internal.junit.VerificationCollectorImpl;
+import org.mockito.internal.util.ConsoleMockitoLogger;
import org.mockito.quality.Strictness;
/**
@@ -30,7 +30,7 @@
* @since 1.10.17
*/
public static MockitoRule rule() {
- return new JUnitRule(Plugins.getMockitoLogger(), Strictness.WARN);
+ return new JUnitRule(new ConsoleMockitoLogger(), Strictness.WARN);
}
/**
diff --git a/src/main/java/org/mockito/listeners/StubbingLookupEvent.java b/src/main/java/org/mockito/listeners/StubbingLookupEvent.java
deleted file mode 100644
index a03fb59..0000000
--- a/src/main/java/org/mockito/listeners/StubbingLookupEvent.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2018 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.listeners;
-
-import org.mockito.invocation.Invocation;
-import org.mockito.mock.MockCreationSettings;
-import org.mockito.stubbing.Stubbing;
-
-import java.util.Collection;
-
-/**
- * Represent an information about the looked up stubbing
- *
- * @since 2.24.6
- */
-public interface StubbingLookupEvent {
-
- /**
- * @return The invocation that causes stubbing lookup
- * @since 2.24.6
- */
- Invocation getInvocation();
-
- /**
- * @return Looked up stubbing. It can be <code>null</code>, which indicates that the invocation was not stubbed
- * @since 2.24.6
- */
- Stubbing getStubbingFound();
-
- /**
- * @return All stubbings declared on the mock object that we are invoking
- * @since 2.24.6
- */
- Collection<Stubbing> getAllStubbings();
-
- /**
- * @return Settings of the mock object that we are invoking
- * @since 2.24.6
- */
- MockCreationSettings getMockSettings();
-}
diff --git a/src/main/java/org/mockito/listeners/StubbingLookupListener.java b/src/main/java/org/mockito/listeners/StubbingLookupListener.java
deleted file mode 100644
index b33e063..0000000
--- a/src/main/java/org/mockito/listeners/StubbingLookupListener.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2017 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.listeners;
-
-import org.mockito.MockSettings;
-import org.mockito.mock.MockCreationSettings;
-
-/**
- * When a method is called on a mock object Mockito looks up any stubbings recorded on that mock.
- * This listener gets notified on stubbing lookup.
- * Register listener via {@link MockSettings#stubbingLookupListeners(StubbingLookupListener...)}.
- * This API is used by Mockito to implement {@link org.mockito.exceptions.misusing.PotentialStubbingProblem}
- * (part of Mockito {@link org.mockito.quality.Strictness}).
- * <p>
- * Details: When method is called on the mock object, Mockito looks for any answer (stubbing) declared on that mock.
- * If the stubbed answer is found, that answer is then invoked (value returned, thrown exception, etc.).
- * If the answer is not found (e.g. that invocation was not stubbed on the mock), mock's default answer is used.
- * This listener implementation is notified when Mockito attempts to find an answer for invocation on a mock.
- * <p>
- * The listeners can be accessed via {@link MockCreationSettings#getStubbingLookupListeners()}.
- *
- * @since 2.24.6
- */
-public interface StubbingLookupListener {
-
- /**
- * Called by the framework when Mockito looked up an answer for invocation on a mock.
- * For details, see {@link StubbingLookupListener}.
- *
- * @param stubbingLookupEvent - Information about the looked up stubbing
- * @since 2.24.6
- */
- void onStubbingLookup(StubbingLookupEvent stubbingLookupEvent);
-}
diff --git a/src/main/java/org/mockito/mock/MockCreationSettings.java b/src/main/java/org/mockito/mock/MockCreationSettings.java
index 2343b0d..7e74be8 100644
--- a/src/main/java/org/mockito/mock/MockCreationSettings.java
+++ b/src/main/java/org/mockito/mock/MockCreationSettings.java
@@ -9,7 +9,6 @@
import org.mockito.MockSettings;
import org.mockito.NotExtensible;
import org.mockito.listeners.InvocationListener;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.quality.Strictness;
import org.mockito.stubbing.Answer;
@@ -71,17 +70,7 @@
boolean isStripAnnotations();
/**
- * Returns {@link StubbingLookupListener} instances attached to this mock via {@link MockSettings#stubbingLookupListeners(StubbingLookupListener...)}.
- * The resulting list is mutable, you can add/remove listeners even after the mock was created.
- * <p>
- * For more details see {@link StubbingLookupListener}.
- *
- * @since 2.24.6
- */
- List<StubbingLookupListener> getStubbingLookupListeners();
-
- /**
- * {@link InvocationListener} instances attached to this mock, see {@link org.mockito.MockSettings#invocationListeners(InvocationListener...)}.
+ * {@link InvocationListener} instances attached to this mock, see {@link org.mockito.MockSettings#invocationListeners}.
*/
List<InvocationListener> getInvocationListeners();
diff --git a/src/main/java/org/mockito/plugins/InlineMockMaker.java b/src/main/java/org/mockito/plugins/InlineMockMaker.java
deleted file mode 100644
index 8771aa7..0000000
--- a/src/main/java/org/mockito/plugins/InlineMockMaker.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2019 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.plugins;
-
-import org.mockito.Incubating;
-import org.mockito.MockitoFramework;
-
-/**
- * Extension to {@link MockMaker} for mock makers that changes inline method implementations
- * and need keep track of created mock objects.
- * <p>
- * Mockito's default inline mock maker keeps track of created mock objects via weak reference map.
- * This poses a risk of memory leaks in certain scenarios
- * (issue <a href="https://github.com/mockito/mockito/pull/1619">#1619</a>).
- * There is no clean way to tackle those problems at the moment.
- * Hence, {@code InlineMockMaker} interface exposes methods to explicitly clear mock references.
- * Those methods are called by {@link MockitoFramework#clearInlineMocks()}.
- * When the user encounters a leak, he can mitigate the problem with {@link MockitoFramework#clearInlineMocks()}.
- * <p>
- * {@code InlineMockMaker} is for expert users and framework integrators, when custom inline mock maker is in use.
- * If you have a custom {@link MockMaker} that keeps track of mock objects,
- * please have your mock maker implement {@code InlineMockMaker} interface.
- * This way, it can participate in {@link MockitoFramework#clearInlineMocks()} API.
- *
- * @since 2.25.0
- */
-@Incubating
-public interface InlineMockMaker extends MockMaker {
-
- /**
- * Clean up internal state for specified {@code mock}. You may assume there won't be any interaction to the specific
- * mock after this is called.
- *
- * @param mock the mock instance whose internal state is to be cleaned.
- * @since 2.25.0
- */
- @Incubating
- void clearMock(Object mock);
-
- /**
- * Cleans up internal state for all existing mocks. You may assume there won't be any interaction to mocks created
- * previously after this is called.
- *
- * @since 2.25.0
- */
- @Incubating
- void clearAllMocks();
-
-}
diff --git a/src/main/java/org/mockito/plugins/MockitoLogger.java b/src/main/java/org/mockito/plugins/MockitoLogger.java
deleted file mode 100644
index 38ca4a8..0000000
--- a/src/main/java/org/mockito/plugins/MockitoLogger.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.plugins;
-
-import org.mockito.Incubating;
-
-/**
- * Mockito logger.
- *
- * <p>By default logs to console</p>
- *
- * <p>All mockito logging goes through this class and could be customized as usual Mockito plugin.</p>
- *
- * <h3>Using the extension point</h3>
- *
- * <p>Suppose you wrote an extension to customize logging, in order to tell Mockito to use it you need to put
- * in your <strong>classpath</strong>:
- * <ol style="list-style-type: lower-alpha">
- * <li>
- * The implementation itself, for example <code>org.awesome.mockito.AwesomeLogger</code> that
- * extends the <code>MockitoLogger</code>.
- * </li>
- * <li>
- * A file "<code>mockito-extensions/org.mockito.plugins.MockitoLogger</code>". The content of this file is
- * exactly a <strong>one</strong> line with the qualified name:
- * <code>org.awesome.mockito.AwesomeLogger</code>.
- * </li>
- * </ol>
- * </p>
- *
- * <p>Note that if several <code>mockito-extensions/org.mockito.plugins.MockitoLogger</code> files exists in the
- * classpath Mockito will only use the first returned by the standard {@link ClassLoader#getResource} mechanism.
- *
- * @since 2.23.19
- */
-@Incubating
-public interface MockitoLogger {
- /**
- * Log specified object.
- *
- * @param what to be logged
- */
- @Incubating
- void log(Object what);
-}
diff --git a/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java b/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java
index b03b098..522b795 100644
--- a/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java
+++ b/src/main/java/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java
@@ -12,11 +12,11 @@
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
-import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.debugging.WarningsCollector;
import org.mockito.internal.runners.RunnerFactory;
import org.mockito.internal.runners.InternalRunner;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.ConsoleMockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import java.lang.reflect.InvocationTargetException;
@@ -33,7 +33,7 @@
private final InternalRunner runner;
public ConsoleSpammingMockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
- this(Plugins.getMockitoLogger(), new RunnerFactory().create(klass));
+ this(new ConsoleMockitoLogger(), new RunnerFactory().create(klass));
}
ConsoleSpammingMockitoJUnitRunner(MockitoLogger logger, InternalRunner runner) {
diff --git a/src/main/java/org/mockito/session/MockitoSessionBuilder.java b/src/main/java/org/mockito/session/MockitoSessionBuilder.java
index b17cfe7..b3a758b 100644
--- a/src/main/java/org/mockito/session/MockitoSessionBuilder.java
+++ b/src/main/java/org/mockito/session/MockitoSessionBuilder.java
@@ -7,7 +7,6 @@
import org.mockito.Incubating;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
-import org.mockito.NotExtensible;
import org.mockito.exceptions.misusing.UnfinishedMockingSessionException;
import org.mockito.quality.Strictness;
@@ -18,7 +17,6 @@
* @since 2.7.0
*/
@Incubating
-@NotExtensible
public interface MockitoSessionBuilder {
/**
diff --git a/src/main/java/org/mockito/session/MockitoSessionLogger.java b/src/main/java/org/mockito/session/MockitoSessionLogger.java
index f876433..e5f40ad 100644
--- a/src/main/java/org/mockito/session/MockitoSessionLogger.java
+++ b/src/main/java/org/mockito/session/MockitoSessionLogger.java
@@ -6,7 +6,6 @@
import org.mockito.Incubating;
import org.mockito.MockitoSession;
-import org.mockito.NotExtensible;
/**
* Logger for {@linkplain org.mockito.quality.MockitoHint hints} emitted when
@@ -18,7 +17,6 @@
* @since 2.15.0
*/
@Incubating
-@NotExtensible
public interface MockitoSessionLogger {
/**
diff --git a/src/main/java/org/mockito/stubbing/Answer6.java b/src/main/java/org/mockito/stubbing/Answer6.java
deleted file mode 100644
index bf668cf..0000000
--- a/src/main/java/org/mockito/stubbing/Answer6.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2016 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.stubbing;
-
-import org.mockito.Incubating;
-
-/**
- * Generic interface to be used for configuring mock's answer for a six argument invocation.
- *
- * Answer specifies an action that is executed and a return value that is returned when you interact with the mock.
- * <p>
- * Example of stubbing a mock with this custom answer:
- *
- * <pre class="code"><code class="java">
- * import static org.mockito.AdditionalAnswers.answer;
- *
- * when(mock.someMethod(anyInt(), anyString(), anyChar(), any(), any(), anyBoolean())).then(answer(
- * new Answer6<StringBuilder, Integer, String, Character, Object, Object, Boolean>() {
- * public StringBuilder answer(Integer i, String s, Character c, Object o1, Object o2, Boolean isIt) {
- * return new StringBuilder().append(i).append(s).append(c).append(o1.hashCode()).append(o2.hashCode()).append(isIt);
- * }
- * }));
- *
- * //Following will print a string like "3xyz131635550true"
- * System.out.println(mock.someMethod(3, "xy", 'z', new Object(), new Object(), true));
- * </code></pre>
- *
- * @param <T> return type
- * @param <A0> type of the first argument
- * @param <A1> type of the second argument
- * @param <A2> type of the third argument
- * @param <A3> type of the fourth argument
- * @param <A4> type of the fifth argument
- * @param <A5> type of the sixth argument
- * @see Answer
- */
-@Incubating
-public interface Answer6<T, A0, A1, A2, A3, A4, A5> {
- /**
- * @param argument0 the first argument.
- * @param argument1 the second argument.
- * @param argument2 the third argument.
- * @param argument3 the fourth argument.
- * @param argument4 the fifth argument.
- * @param argument5 the sixth argument.
- *
- * @return the value to be returned.
- *
- * @throws Throwable the throwable to be thrown
- */
- 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/VoidAnswer6.java b/src/main/java/org/mockito/stubbing/VoidAnswer6.java
deleted file mode 100644
index 5df66a3..0000000
--- a/src/main/java/org/mockito/stubbing/VoidAnswer6.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2016 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.stubbing;
-
-import org.mockito.Incubating;
-
-/**
- * Generic interface to be used for configuring mock's answer for a six argument invocation that returns nothing.
- *
- * Answer specifies an action that is executed when you interact with the mock.
- * <p>
- * Example of stubbing a mock with this custom answer:
- *
- * <pre class="code"><code class="java">
- * import static org.mockito.AdditionalAnswers.answerVoid;
- *
- * doAnswer(answerVoid(
- * new VoidAnswer5<String, Integer, String, Character, Object, String>() {
- * public void answer(String msg, Integer count, String another, Character c, Object o, String subject) throws Exception {
- * throw new Exception(String.format(msg, another, c, o, count, subject));
- * }
- * })).when(mock).someMethod(anyString(), anyInt(), anyString(), anyChar(), any(), anyString());
- *
- * // The following will raise an exception with the message "ka-boom <3 mockito"
- * mock.someMethod("%s-boom %c%d %s", 3, "ka", '<', new Object(), "mockito");
- * </code></pre>
- *
- * @param <A0> type of the first argument
- * @param <A1> type of the second argument
- * @param <A2> type of the third argument
- * @param <A3> type of the fourth argument
- * @param <A4> type of the fifth argument
- * @param <A5> type of the sixth argument
- * @see Answer
- */
-@Incubating
-public interface VoidAnswer6<A0, A1, A2, A3, A4, A5> {
- /**
- * @param argument0 the first argument.
- * @param argument1 the second argument.
- * @param argument2 the third argument.
- * @param argument3 the fourth argument.
- * @param argument4 the fifth argument.
- * @param argument5 the sixth argument.
- *
- * @throws Throwable the throwable to be thrown
- */
- void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4, A5 argument5) throws Throwable;
-}
diff --git a/src/test/java/org/mockito/StaticMockingExperimentTest.java b/src/test/java/org/mockito/StaticMockingExperimentTest.java
index c6312e7..cc8a598 100644
--- a/src/test/java/org/mockito/StaticMockingExperimentTest.java
+++ b/src/test/java/org/mockito/StaticMockingExperimentTest.java
@@ -8,7 +8,7 @@
import org.junit.Test;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.MockHandler;
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 d13f729..5935eae 100644
--- a/src/test/java/org/mockito/internal/configuration/plugins/DefaultMockitoPluginsTest.java
+++ b/src/test/java/org/mockito/internal/configuration/plugins/DefaultMockitoPluginsTest.java
@@ -7,11 +7,9 @@
import org.junit.Test;
import org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker;
import org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker;
-import org.mockito.internal.util.ConsoleMockitoLogger;
import org.mockito.plugins.InstantiatorProvider;
import org.mockito.plugins.InstantiatorProvider2;
import org.mockito.plugins.MockMaker;
-import org.mockito.plugins.MockitoLogger;
import org.mockitoutil.TestBase;
import static org.junit.Assert.*;
@@ -29,6 +27,5 @@
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());
}
}
diff --git a/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java b/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
index 63cb1e7..18911e4 100644
--- a/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
+++ b/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java
@@ -5,31 +5,25 @@
package org.mockito.internal.creation;
import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.debugging.VerboseMockInvocationLogger;
import org.mockito.listeners.InvocationListener;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockitoutil.TestBase;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+import static org.junit.Assert.*;
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.assertFalse;
-import static org.junit.Assert.assertTrue;
public class MockSettingsImplTest extends TestBase {
private MockSettingsImpl<?> mockSettingsImpl = new MockSettingsImpl<Object>();
@Mock private InvocationListener invocationListener;
- @Mock private StubbingLookupListener stubbingLookupListener;
@Test(expected=MockitoException.class)
@SuppressWarnings("unchecked")
@@ -118,6 +112,12 @@
Assertions.assertThat(mockSettingsImpl.getInvocationListeners()).hasSize(1);
}
+ @SuppressWarnings("unchecked")
+ @Test(expected=MockitoException.class)
+ public void shouldNotAllowNullListener() {
+ mockSettingsImpl.invocationListeners((InvocationListener[])null);
+ }
+
@Test
@SuppressWarnings("unchecked")
public void shouldAddInvocationListener() {
@@ -145,98 +145,22 @@
}
@Test
- public void validates_listeners() {
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- mockSettingsImpl.addListeners(new Object[] {}, new LinkedList<Object>(), "myListeners");
- }
- }).hasMessageContaining("myListeners() requires at least one listener");
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- mockSettingsImpl.addListeners(null, new LinkedList<Object>(), "myListeners");
- }
- }).hasMessageContaining("myListeners() does not accept null vararg array");
-
- assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- mockSettingsImpl.addListeners(new Object[] {null}, new LinkedList<Object>(), "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");
+ public void shouldReportErrorWhenAddingNoInvocationListeners() throws Exception {
+ try {
+ mockSettingsImpl.invocationListeners();
+ fail();
+ } catch (Exception e) {
+ Assertions.assertThat(e.getMessage()).contains("at least one listener");
+ }
}
@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");
- }
-
- @Test
- public void addListeners_has_empty_listeners_by_default() {
- assertTrue(mockSettingsImpl.getInvocationListeners().isEmpty());
- assertTrue(mockSettingsImpl.getStubbingLookupListeners().isEmpty());
- }
-
- @Test
- public void addListeners_shouldAddMockObjectListeners() {
- //when
- mockSettingsImpl.invocationListeners(invocationListener);
- mockSettingsImpl.stubbingLookupListeners(stubbingLookupListener);
-
- //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
- assertThat(mockSettingsImpl.getInvocationListeners())
- .containsSequence(invocationListener, invocationListener);
- assertThat(mockSettingsImpl.getStubbingLookupListeners())
- .containsSequence(stubbingLookupListener, stubbingLookupListener);
+ public void shouldReportErrorWhenAddingANullInvocationListener() throws Exception {
+ try {
+ mockSettingsImpl.invocationListeners(invocationListener, null);
+ fail();
+ } catch (Exception e) {
+ Assertions.assertThat(e.getMessage()).contains("does not accept null");
+ }
}
}
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 eebdb96..51c321d 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
@@ -20,11 +20,7 @@
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
-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.regex.Pattern;
import static net.bytebuddy.ClassFileVersion.JAVA_V8;
@@ -291,37 +287,6 @@
.getOnly().getParameters().getOnly().getName()).isEqualTo("bar");
}
- @Test
- public void test_clear_mock_clears_handler() {
- MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);
- GenericSubClass proxy = mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
- assertThat(mockMaker.getHandler(proxy)).isNotNull();
-
- //when
- mockMaker.clearMock(proxy);
-
- //then
- assertThat(mockMaker.getHandler(proxy)).isNull();
- }
-
- @Test
- public void test_clear_all_mock_clears_handler() {
- MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);
- GenericSubClass proxy1 = mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
- assertThat(mockMaker.getHandler(proxy1)).isNotNull();
-
- settings = settingsFor(GenericSubClass.class);
- GenericSubClass proxy2 = mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
- assertThat(mockMaker.getHandler(proxy1)).isNotNull();
-
- //when
- mockMaker.clearAllMocks();
-
- //then
- assertThat(mockMaker.getHandler(proxy1)).isNull();
- assertThat(mockMaker.getHandler(proxy2)).isNull();
- }
-
private static <T> MockCreationSettings<T> settingsFor(Class<T> type, Class<?>... extraInterfaces) {
MockSettingsImpl<T> mockSettings = new MockSettingsImpl<T>();
mockSettings.setTypeToMock(type);
@@ -332,9 +297,7 @@
@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/MockMethodDispatcher.raw")).isNotNull();
}
private static final class FinalClass {
diff --git a/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java b/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
index ae21488..0937b69 100644
--- a/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
+++ b/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java
@@ -10,26 +10,15 @@
import org.mockito.MockSettings;
import org.mockito.StateMaster;
import org.mockito.exceptions.misusing.RedundantListenerException;
-import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.listeners.MockCreationListener;
import org.mockito.listeners.MockitoListener;
import org.mockito.mock.MockCreationSettings;
-import org.mockito.plugins.InlineMockMaker;
import org.mockitoutil.TestBase;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.mockingDetails;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.withSettings;
+import static org.mockito.Mockito.*;
import static org.mockitoutil.ThrowableAssert.assertThat;
public class DefaultMockitoFrameworkTest extends TestBase {
@@ -123,52 +112,5 @@
"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
- assertTrue(mockingDetails(mock).isMock());
- framework.clearInlineMocks();
- }
-
- @Test
- public void clears_all_mocks() {
- //clearing mocks only works with inline mocking
- assumeTrue(Plugins.getMockMaker() instanceof InlineMockMaker);
-
- //given
- List list1 = mock(List.class);
- assertTrue(mockingDetails(list1).isMock());
- List list2 = mock(List.class);
- assertTrue(mockingDetails(list2).isMock());
-
- //when
- framework.clearInlineMocks();
-
- //then
- assertFalse(mockingDetails(list1).isMock());
- assertFalse(mockingDetails(list2).isMock());
- }
-
- @Test
- public void clears_mock() {
- //clearing mocks only works with inline mocking
- assumeTrue(Plugins.getMockMaker() instanceof InlineMockMaker);
-
- //given
- List list1 = mock(List.class);
- assertTrue(mockingDetails(list1).isMock());
- List list2 = mock(List.class);
- assertTrue(mockingDetails(list2).isMock());
-
- //when
- framework.clearInlineMock(list1);
-
- //then
- assertFalse(mockingDetails(list1).isMock());
- assertTrue(mockingDetails(list2).isMock());
- }
-
private static class MyListener implements MockitoListener {}
}
diff --git a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
index 4e01535..b3106a6 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
@@ -6,7 +6,6 @@
package org.mockito.internal.invocation;
import org.mockito.Mockito;
-import org.mockito.internal.invocation.mockref.MockReference;
import org.mockito.internal.invocation.mockref.MockStrongReference;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.invocation.Invocation;
@@ -62,7 +61,7 @@
}
}
- Invocation i = createInvocation(new MockStrongReference<Object>(mock, false),
+ Invocation i = new InterceptedInvocation(new MockStrongReference<Object>(mock, false),
new SerializableMethod(method),
args,
NO_OP,
@@ -74,11 +73,6 @@
return i;
}
- protected Invocation createInvocation(MockReference<Object> 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) {
this.methodName = methodName;
return this;
@@ -136,9 +130,6 @@
public String toString() {
return location;
}
- public String getSourceFile() {
- return "SomeClass";
- }
};
return this;
}
diff --git a/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java b/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
index 2c1037b..a1e2564 100644
--- a/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
+++ b/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
@@ -8,95 +8,51 @@
import static org.mockitoutil.ClassLoaders.excludingClassLoader;
import java.lang.reflect.Method;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.exceptions.verification.ArgumentsAreDifferent;
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 currentClassLoader = ExceptionFactoryTest.class.getClassLoader();
+ private static ClassLoader classLoaderWithoutJUnit = excludingClassLoader().withCodeSourceUrlOf(ExceptionFactory.class).without("org.junit", "junit").build();
- /** loaded by the current classloader */
- private static Class<?> opentestComparisonFailure;
- private static Class<?> opentestArgumentsAreDifferent;
+ /** loaded by the current current class loader */
+ private static Class<?> junitArgumentsAreDifferent;
- /** 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 */
+ /** loaded by the custom classloader {@value #classLoaderWithoutJUnit}, which excludes junit-classes */
private static Class<?> nonJunitArgumentsAreDifferent;
@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());
- opentestComparisonFailure = org.opentest4j.AssertionFailedError.class;
- opentestArgumentsAreDifferent = org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent.class;
+ nonJunitArgumentsAreDifferent = classLoaderWithoutJUnit.loadClass(ArgumentsAreDifferent.class.getName());
+ junitArgumentsAreDifferent = org.mockito.exceptions.verification.junit.ArgumentsAreDifferent.class;
}
@Test
- public void createArgumentsAreDifferentException_withoutJUnitOrOpenTest() throws Exception {
- AssertionError e = invokeFactoryThroughLoader(classLoaderWithoutJUnitOrOpenTest);
-
- assertThat(e).isExactlyInstanceOf(nonJunitArgumentsAreDifferent);
- }
-
- @Test
- public void createArgumentsAreDifferentException_withJUnit3_butNotOpenTest() throws Exception {
- AssertionError e = invokeFactoryThroughLoader(classLoaderWithoutOpenTest);
-
- assertThat(e).isExactlyInstanceOf(junit3ArgumentsAreDifferent).isInstanceOf(junit3ComparisonFailure);
- }
-
- @Test
- public void createArgumentsAreDifferentException_withOpenTest() throws Exception {
- AssertionError e = invokeFactoryThroughLoader(currentClassLoader);
-
- assertThat(e).isExactlyInstanceOf(opentestArgumentsAreDifferent).isInstanceOf(opentestComparisonFailure);
- }
-
- @Test
- public void createArgumentsAreDifferentException_withoutJUnitOrOpenTest_2x() throws Exception {
- AssertionError e;
-
- e = invokeFactoryThroughLoader(classLoaderWithoutJUnitOrOpenTest);
- assertThat(e).isExactlyInstanceOf(nonJunitArgumentsAreDifferent);
-
- e = invokeFactoryThroughLoader(classLoaderWithoutJUnitOrOpenTest);
- assertThat(e).isExactlyInstanceOf(nonJunitArgumentsAreDifferent);
- }
-
- @Test
- public void createArgumentsAreDifferentException_withJUnit3_2x() throws Exception {
- AssertionError e;
-
- e = invokeFactoryThroughLoader(classLoaderWithoutOpenTest);
- assertThat(e).isExactlyInstanceOf(junit3ArgumentsAreDifferent);
-
- e = invokeFactoryThroughLoader(classLoaderWithoutOpenTest);
- assertThat(e).isExactlyInstanceOf(junit3ArgumentsAreDifferent);
- }
-
- @Test
- public void createArgumentsAreDifferentException_withOpenTest_2x() throws Exception {
- AssertionError e;
-
- e = invokeFactoryThroughLoader(currentClassLoader);
- assertThat(e).isExactlyInstanceOf(opentestArgumentsAreDifferent);
-
- e = invokeFactoryThroughLoader(currentClassLoader);
- assertThat(e).isExactlyInstanceOf(opentestArgumentsAreDifferent);
- }
-
- private static AssertionError invokeFactoryThroughLoader(ClassLoader loader) throws Exception {
- Class<?> exceptionFactory = loader.loadClass(ExceptionFactory.class.getName());
+ public void createArgumentsAreDifferentException_withoutJUnit() throws Exception {
+ Class<?> exceptionFactory = classLoaderWithoutJUnit.loadClass(ExceptionFactory.class.getName());
Method m = exceptionFactory.getDeclaredMethod("createArgumentsAreDifferentException", String.class, String.class, String.class);
- return (AssertionError) m.invoke(null, "message", "wanted", "actual");
+ Object e = m.invoke(null, "message", "wanted", "actual");
+
+ assertThat(e).isExactlyInstanceOf(nonJunitArgumentsAreDifferent);
+ }
+
+ @Test
+ public void createArgumentsAreDifferentException_withJUnit() throws Exception {
+ AssertionError e = ExceptionFactory.createArgumentsAreDifferentException("message", "wanted", "actual");
+
+ assertThat(e).isExactlyInstanceOf(junitArgumentsAreDifferent);
+ }
+
+ @Test
+ public void createArgumentsAreDifferentException_withJUnit2x() throws Exception {
+ AssertionError e;
+
+ e = ExceptionFactory.createArgumentsAreDifferentException("message", "wanted", "actual");
+ assertThat(e).isExactlyInstanceOf(junitArgumentsAreDifferent);
+
+ e = ExceptionFactory.createArgumentsAreDifferentException("message", "wanted", "actual");
+ assertThat(e).isExactlyInstanceOf(junitArgumentsAreDifferent);
}
}
diff --git a/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java b/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java
index 40e5396..ac963c4 100644
--- a/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java
+++ b/src/test/java/org/mockito/internal/listeners/StubbingLookupNotifierTest.java
@@ -9,7 +9,6 @@
import org.mockito.ArgumentMatcher;
import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.invocation.Invocation;
-import org.mockito.listeners.StubbingLookupListener;
import org.mockito.stubbing.Stubbing;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java b/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
index 7ef0334..40ad320 100644
--- a/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
+++ b/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java
@@ -5,26 +5,14 @@
package org.mockito.internal.progress;
-import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.exceptions.misusing.RedundantListenerException;
-import org.mockito.internal.listeners.AutoCleanableListener;
import org.mockito.internal.verification.VerificationModeFactory;
-import org.mockito.listeners.MockitoListener;
import org.mockito.verification.VerificationMode;
import org.mockitoutil.TestBase;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import static org.junit.Assert.*;
public class MockingProgressImplTest extends TestBase {
@@ -65,46 +53,4 @@
//then no exception is thrown:
mockingProgress.mockingStarted(null, null);
}
-
- @Test
- public void should_not_allow_redundant_listeners() {
- MockitoListener listener1 = mock(MockitoListener.class);
- final MockitoListener listener2 = mock(MockitoListener.class);
-
- final Set<MockitoListener> listeners = new LinkedHashSet<MockitoListener>();
-
- //when
- MockingProgressImpl.addListener(listener1, listeners);
-
- //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();
-
- Set<MockitoListener> listeners = new LinkedHashSet<MockitoListener>();
-
- //when
- MockingProgressImpl.addListener(someListener, listeners);
- MockingProgressImpl.addListener(dirtyListener, listeners);
-
- //then
- Assertions.assertThat(listeners).containsExactlyInAnyOrder(someListener, dirtyListener);
-
- //when
- MockingProgressImpl.addListener(cleanListener, listeners);
-
- //then dirty listener was removed automatically
- Assertions.assertThat(listeners).containsExactlyInAnyOrder(someListener, cleanListener);
- }
-
- interface MyListener extends MockitoListener, AutoCleanableListener {}
}
diff --git a/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java b/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java
index 253dcf7..cca74bc 100644
--- a/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java
+++ b/src/test/java/org/mockito/internal/runners/DefaultInternalRunnerTest.java
@@ -45,10 +45,10 @@
.run(newNotifier(runListener));
verify(runListener, times(1)).testFailure(any(Failure.class));
- verify(runListener, times(1)).testFinished(any(Description.class));
- verify(mockitoTestListener, only()).testFinished(any(TestFinishedEvent.class));
+ verify(runListener, never()).testFinished(any(Description.class));
+ verify(mockitoTestListener, never()).testFinished(any(TestFinishedEvent.class));
- reset(runListener, mockitoTestListener);
+ reset(runListener);
new DefaultInternalRunner(SuccessTest.class, supplier)
.run(newNotifier(runListener));
@@ -67,7 +67,7 @@
public static final class SuccessTest {
@Test
- public void this_test_is_NOT_supposed_to_fail() {
+ public void test() {
assertTrue(true);
}
}
@@ -78,7 +78,7 @@
private System system;
@Test
- public void this_test_is_supposed_to_fail() {
+ public void test() {
assertNotNull(system);
}
}
diff --git a/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java b/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java
index a65ae21..855afb0 100644
--- a/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java
+++ b/src/test/java/org/mockito/internal/session/DefaultMockitoSessionBuilderTest.java
@@ -97,16 +97,6 @@
}).throwsException(UnfinishedMockingSessionException.class);
}
- @Test public void auto_cleans_dirty_listeners() {
- new DefaultMockitoSessionBuilder().startMocking();
-
- ThrowableAssert.assertThat(new Runnable() {
- public void run() {
- new DefaultMockitoSessionBuilder().startMocking();
- }
- }).throwsException(UnfinishedMockingSessionException.class);
- }
-
class TestClass {
@Mock public Set<Object> set;
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 b051e12..d91df8c 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java
@@ -5,52 +5,39 @@
package org.mockito.internal.stubbing.defaultanswers;
import org.junit.Test;
-import org.mockitousage.examples.use.Article;
-import java.io.Closeable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.concurrent.Callable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
@SuppressWarnings("unused")
public class ReturnsGenericDeepStubsTest {
- interface ListOfInteger extends List<Integer> {
- }
+ interface ListOfInteger extends List<Integer> {}
- interface AnotherListOfInteger extends ListOfInteger {
- }
+ interface AnotherListOfInteger extends ListOfInteger {}
interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
Set<Number> remove(Object key); // override with fixed ParameterizedType
-
List<? super Number> returningWildcard();
-
Map<String, K> returningNonMockableNestedGeneric();
-
K returningK();
-
<O extends K> List<O> paramTypeWithTypeParams();
-
<S extends Appendable, T extends S> T twoTypeParams(S s);
-
<O extends K> O typeVarWithTypeParams();
-
Number returnsNormalType();
}
@Test
- public void generic_deep_mock_frenzy__look_at_these_chained_calls() {
+ public void generic_deep_mock_frenzy__look_at_these_chained_calls() throws Exception {
GenericsNest<?> mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
Set<? extends Map.Entry<? extends Cloneable, Set<Number>>> entries = mock.entrySet();
- Iterator<? extends Map.Entry<? extends Cloneable, Set<Number>>> entriesIterator = mock.entrySet().iterator();
+ Iterator<? extends Map.Entry<? extends Cloneable,Set<Number>>> entriesIterator = mock.entrySet().iterator();
Map.Entry<? extends Cloneable, Set<Number>> nextEntry = mock.entrySet().iterator().next();
Cloneable cloneableKey = mock.entrySet().iterator().next().getKey();
@@ -62,17 +49,17 @@
}
@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() throws Exception {
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);
+ 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);
+ 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() throws Exception {
GenericsNest<?> mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
Cloneable cloneable_bound_of_typevar_K = mock.returningK();
@@ -80,7 +67,7 @@
}
@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() throws Exception {
GenericsNest<?> mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
Cloneable cloneable_bound_of_typevar_K_referenced_by_typevar_O = (Cloneable) mock.typeVarWithTypeParams();
@@ -88,7 +75,7 @@
}
@Test
- public void can_create_mock_from_return_types_declared_with_a_bounded_wildcard() {
+ public void can_create_mock_from_return_types_declared_with_a_bounded_wildcard() throws Exception {
GenericsNest<?> mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
List<? super Integer> objects = mock.returningWildcard();
@@ -97,7 +84,7 @@
}
@Test
- public void can_still_work_with_raw_type_in_the_return_type() {
+ public void can_still_work_with_raw_type_in_the_return_type() throws Exception {
GenericsNest<?> mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
Number the_raw_type_that_should_be_returned = mock.returnsNormalType();
@@ -105,7 +92,7 @@
}
@Test
- public void will_return_default_value_on_non_mockable_nested_generic() {
+ public void will_return_default_value_on_non_mockable_nested_generic() throws Exception {
GenericsNest<?> genericsNest = mock(GenericsNest.class, RETURNS_DEEP_STUBS);
ListOfInteger listOfInteger = mock(ListOfInteger.class, RETURNS_DEEP_STUBS);
AnotherListOfInteger anotherListOfInteger = mock(AnotherListOfInteger.class, RETURNS_DEEP_STUBS);
@@ -116,80 +103,11 @@
}
@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_callsite_when_erasure_takes_place_for_example___StringBuilder_is_subject_to_erasure() throws Exception {
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);
- }
-
- class WithGenerics<T> {
- T execute() {
- throw new IllegalArgumentException();
- }
- }
-
- class SubClass<S> extends WithGenerics<S> {
- }
-
- class UserOfSubClass {
- SubClass<String> generate() {
- return null;
- }
- }
-
- @Test
- public void can_handle_deep_stubs_with_generics_at_end_of_deep_invocation() {
- UserOfSubClass mock = mock(UserOfSubClass.class, RETURNS_DEEP_STUBS);
-
- when(mock.generate().execute()).thenReturn("sub");
-
- assertThat(mock.generate().execute()).isEqualTo("sub");
- }
-
- public interface TopInterface<T> {
- T generic();
- }
-
- public interface MiddleInterface<T> extends TopInterface<T> {
- }
-
- public class OwningClassWithDeclaredUpperBounds<T extends Iterable<Article> & Callable<Article> & Closeable> {
- public abstract class AbstractInner implements MiddleInterface<T> {
- }
- }
-
- @Test
- 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);
-
- // It seems that while the syntax used on OwningClassWithDeclaredUpperBounds.AbstractInner
- // appear to be legal, the javac compiler does not follow through
- // hence we need casting, this may also explain why GenericMetadataSupport has trouble to
- // extract matching data as well.
-
- assertThat(mock.generic())
- .describedAs("mock should implement first bound : 'Iterable'")
- .isInstanceOf(Iterable.class);
- assertThat(((Iterable<Article>) mock.generic()).iterator())
- .describedAs("Iterable returns Iterator").isInstanceOf(Iterator.class);
- assertThat(((Iterable<Article>) 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();
-
- assertThat(mock.generic())
- .describedAs("mock should implement second interface bound : 'Callable'")
- .isInstanceOf(Callable.class);
- assertThat(((Callable<Article>) 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();
-
- assertThat(mock.generic())
- .describedAs("mock should implement third interface bound : 'Closeable'")
- .isInstanceOf(Closeable.class);
+ mock.twoTypeParams(new StringBuilder()).append(2).append(3);
}
}
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 ba5b822..7de160c 100755
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java
@@ -6,24 +6,15 @@
import org.junit.Test;
import org.mockito.internal.configuration.plugins.Plugins;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsGenericDeepStubsTest.WithGenerics;
import org.mockito.internal.util.MockUtil;
import org.mockitoutil.TestBase;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
-import static org.mockito.Mockito.when;
public class ReturnsMocksTest extends TestBase {
private ReturnsMocks values = new ReturnsMocks();
- interface AllInterface {
- FooInterface getInterface();
- BarClass getNormalClass();
- Baz getFinalClass();
- WithGenerics<String> withGenerics();
- }
-
interface FooInterface {
}
@@ -34,30 +25,21 @@
}
@Test
- public void should_return_mock_value_for_interface() throws Throwable {
- Object interfaceMock = values.answer(invocationOf(AllInterface.class, "getInterface"));
+ public void should_return_mock_value_for_interface() throws Exception {
+ Object interfaceMock = values.returnValueFor(FooInterface.class);
assertTrue(MockUtil.isMock(interfaceMock));
}
@Test
- public void should_return_mock_value_for_class() throws Throwable {
- Object classMock = values.answer(invocationOf(AllInterface.class, "getNormalClass"));
+ public void should_return_mock_value_for_class() throws Exception {
+ Object classMock = values.returnValueFor(BarClass.class);
assertTrue(MockUtil.isMock(classMock));
}
- @SuppressWarnings("unchecked")
@Test
- public void should_return_mock_value_for_generic_class() throws Throwable {
- WithGenerics<String> classMock = (WithGenerics<String>) values.answer(invocationOf(AllInterface.class, "withGenerics"));
- assertTrue(MockUtil.isMock(classMock));
- when(classMock.execute()).thenReturn("return");
- assertEquals("return", classMock.execute());
- }
-
- @Test
- public void should_return_null_for_final_class_if_unsupported() throws Throwable {
+ public void should_return_null_for_final_class_if_unsupported() throws Exception {
assumeFalse(Plugins.getMockMaker().isTypeMockable(Baz.class).mockable());
- assertNull(values.answer(invocationOf(AllInterface.class, "getFinalClass")));
+ assertNull(values.returnValueFor(Baz.class));
}
@Test
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 8acf0ea..228c56a 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java
@@ -4,29 +4,15 @@
*/
package org.mockito.internal.stubbing.defaultanswers;
-import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
+import static org.assertj.core.api.Assertions.assertThat;
+
import org.junit.Test;
import org.mockito.exceptions.verification.SmartNullPointerException;
-import org.mockito.internal.debugging.LocationImpl;
-import org.mockito.internal.invocation.InterceptedInvocation;
-import org.mockito.internal.invocation.SerializableMethod;
-import org.mockito.internal.invocation.mockref.MockStrongReference;
import org.mockito.stubbing.Answer;
import org.mockitoutil.TestBase;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
public class ReturnsSmartNullsTest extends TestBase {
@@ -99,274 +85,4 @@
.hasMessageContaining("lumpa");
}
}
-
- interface GenericFoo<T> {
- T get();
- }
-
- interface GenericFooBar extends GenericFoo<Foo> {
- <I> I method();
- <I> I methodWithArgs(int firstArg, I secondArg);
- <I> I methodWithVarArgs(int firstArg, I... secondArg);
- }
-
- @Test
- public void should_return_an_object_that_has_been_defined_with_class_generic() throws Throwable {
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Foo smartNull = (Foo) answer.answer(invocationOf(GenericFooBar.class, "get"));
-
- assertThat(smartNull.toString())
- .contains("SmartNull returned by")
- .contains("genericFooBar.get()");
- }
-
- @Test
- public void should_return_an_object_that_has_been_defined_with_method_generic() throws Throwable {
-
- Answer<Object> answer = new ReturnsSmartNulls();
-
- String smartNull = (String) answer.answer(invocationOf(GenericFooBar.class, "method"));
-
- assertThat(smartNull)
- .isNull();
- }
-
- private static <T> InterceptedInvocation invocationMethodWithArgs(final T obj) throws NoSuchMethodException {
- return new InterceptedInvocation(
- new MockStrongReference<Object>(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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithArgs("secondArg"));
-
- 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 {
-
- final List<String> list = Collections.singletonList("String");
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithArgs(list));
-
- 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 {
-
- final Map<String, String> map = new HashMap<String, String>();
- map.put("key-1", "value-1");
- map.put("key-2", "value-2");
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithArgs(map));
-
- 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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull =
- answer.answer(invocationMethodWithArgs(new HashSet<String>(Arrays.asList("set-1", "set-2"))));
-
- 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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
- final Foo mock = mock(Foo.class);
-
- Object smartNull = answer.answer(invocationMethodWithArgs(mock));
-
- assertThat(smartNull)
- .isNotNull()
- .isNotSameAs(mock);
- assertThat(smartNull.toString())
- .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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithArgs(new Object() {
- }));
-
- assertThat(smartNull.toString())
- .contains("SmartNull returned by")
- .contains("genericFooBar.methodWithArgs(");
- }
-
- @Test
- public void should_throw_a_error_on_invocation_of_returned_mock() throws Throwable {
-
- final Answer<Object> 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();
- }
- });
-
- Assertions.assertThat(throwable)
- .isInstanceOf(SmartNullPointerException.class)
- .hasMessageContaining("genericFooBar.methodWithArgs(")
- .hasMessageContaining("1")
- .hasMessageContaining(mock.toString());
- }
-
- private static <T> InterceptedInvocation invocationMethodWithVarArgs(final T[] obj) throws NoSuchMethodException {
- return new InterceptedInvocation(
- new MockStrongReference<Object>(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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithVarArgs(new String[]{"varArg-1", "varArg-2"}));
-
- 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 {
-
- final List<String> arg1 = Collections.singletonList("String");
- final List<String> arg2 = Arrays.asList("str-1", "str-2");
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithVarArgs(new List[]{arg1, arg2}));
-
- 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<String, String> map1 = new HashMap<String, String>() {{
- put("key-1", "value-1");
- put("key-2", "value-2");
- }};
- final Map<String, String> map2 = new HashMap<String, String>() {{
- put("key-3", "value-1");
- put("key-4", "value-2");
- }};
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithVarArgs(new Map[]{map1, map2}));
-
- 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 {
-
- final HashSet<String> set1 = new HashSet<String>(Arrays.asList("set-1", "set-2"));
- final HashSet<String> set2 = new HashSet<String>(Arrays.asList("set-1", "set-2"));
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull =
- answer.answer(invocationMethodWithVarArgs(new HashSet[]{set1, set2}));
-
- 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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
- final Foo mock1 = mock(Foo.class);
- final Foo mock2 = mock(Foo.class);
-
- Object smartNull = answer.answer(invocationMethodWithVarArgs(new Foo[]{mock1, mock2}));
-
- assertThat(smartNull)
- .isNotNull()
- .isNotSameAs(mock1)
- .isNotSameAs(mock2);
- assertThat(smartNull.toString())
- .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 {
-
- Answer<Object> answer = new ReturnsSmartNulls();
-
- Object smartNull = answer.answer(invocationMethodWithVarArgs(new Object[]{new Object() {
- }, new Object() {
- }}));
-
- assertThat(smartNull.toString())
- .contains("SmartNull returned by")
- .contains("genericFooBar.methodWithVarArgs(");
- }
-
}
diff --git a/src/test/java/org/mockito/internal/util/MockSettingsTest.java b/src/test/java/org/mockito/internal/util/MockSettingsTest.java
index 01df499..76219c2 100644
--- a/src/test/java/org/mockito/internal/util/MockSettingsTest.java
+++ b/src/test/java/org/mockito/internal/util/MockSettingsTest.java
@@ -6,16 +6,15 @@
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.internal.creation.settings.CreationSettings;
import org.mockito.mock.MockCreationSettings;
import org.mockitoutil.TestBase;
import java.util.List;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
public class MockSettingsTest extends TestBase {
+
@Test
public void public_api_for_creating_settings() throws Exception {
//when
@@ -27,18 +26,4 @@
assertEquals(List.class, settings.getTypeToMock());
assertEquals("dummy", settings.getMockName().toString());
}
- @Test
- public void test_without_annotations() throws Exception {
- MockCreationSettings<List> settings = Mockito.withSettings()
- .withoutAnnotations()
- .build(List.class);
-
- CreationSettings copy = new CreationSettings((CreationSettings)settings);
-
- assertEquals(List.class, settings.getTypeToMock());
- assertEquals(List.class, copy.getTypeToMock());
-
- assertTrue(settings.isStripAnnotations());
- assertTrue(copy.isStripAnnotations());
- }
}
diff --git a/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java b/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java
index 2d6edae..129547f 100644
--- a/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java
+++ b/src/test/java/org/mockito/internal/util/SimpleMockitoLogger.java
@@ -4,8 +4,6 @@
*/
package org.mockito.internal.util;
-import org.mockito.plugins.MockitoLogger;
-
public class SimpleMockitoLogger implements MockitoLogger {
private StringBuilder loggedInfo = new StringBuilder();
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 cc5b588..323efbf 100644
--- a/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
+++ b/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java
@@ -8,16 +8,9 @@
import java.io.Serializable;
import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
@@ -28,67 +21,32 @@
interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
T self();
}
-
interface UpperBoundedTypeWithClass<E extends Number & Comparable<E>> {
E get();
}
-
interface UpperBoundedTypeWithInterfaces<E extends Comparable<E> & Cloneable> {
E get();
}
+ interface ListOfNumbers extends List<Number> {}
+ interface AnotherListOfNumbers extends ListOfNumbers {}
- interface ListOfNumbers extends List<Number> {
- }
+ abstract class ListOfNumbersImpl implements ListOfNumbers {}
+ abstract class AnotherListOfNumbersImpl extends ListOfNumbersImpl {}
- interface AnotherListOfNumbers extends ListOfNumbers {
- }
-
- abstract class ListOfNumbersImpl implements ListOfNumbers {
- }
-
- abstract class AnotherListOfNumbersImpl extends ListOfNumbersImpl {
- }
-
- interface ListOfAnyNumbers<N extends Number & Cloneable> extends List<N> {
- }
+ interface ListOfAnyNumbers<N extends Number & Cloneable> extends List<N> {}
interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
Set<Number> remove(Object key); // override with fixed ParameterizedType
-
List<? super Integer> returning_wildcard_with_class_lower_bound();
-
List<? super K> returning_wildcard_with_typeVar_lower_bound();
-
List<? extends K> returning_wildcard_with_typeVar_upper_bound();
-
K returningK();
-
<O extends K> List<O> paramType_with_type_params();
-
<S, T extends S> T two_type_params();
-
<O extends K> O typeVar_with_type_params();
}
- static class StringList extends ArrayList<String> {
- }
-
- public interface TopInterface<T> {
- T generic();
- }
-
- public interface MiddleInterface<T> extends TopInterface<T> {
- }
-
- public class OwningClassWithDeclaredUpperBounds<T extends List<String> & Comparable<String> & Cloneable> {
- public abstract class AbstractInner implements MiddleInterface<T> {
- }
- }
-
- public class OwningClassWithNoDeclaredUpperBounds<T> {
- public abstract class AbstractInner implements MiddleInterface<T> {
- }
- }
+ static class StringList extends ArrayList<String> { }
@Test
public void typeVariable_of_self_type() {
@@ -98,7 +56,7 @@
}
@Test
- public void can_get_raw_type_from_Class() {
+ public void can_get_raw_type_from_Class() throws Exception {
assertThat(inferFrom(ListOfAnyNumbers.class).rawType()).isEqualTo(ListOfAnyNumbers.class);
assertThat(inferFrom(ListOfNumbers.class).rawType()).isEqualTo(ListOfNumbers.class);
assertThat(inferFrom(GenericsNest.class).rawType()).isEqualTo(GenericsNest.class);
@@ -106,7 +64,7 @@
}
@Test
- public void can_get_raw_type_from_ParameterizedType() {
+ public void can_get_raw_type_from_ParameterizedType() throws Exception {
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);
@@ -114,7 +72,7 @@
}
@Test
- public void can_get_type_variables_from_Class() {
+ public void can_get_type_variables_from_Class() throws Exception {
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");
@@ -131,7 +89,7 @@
}
@Test
- public void can_get_type_variables_from_ParameterizedType() {
+ public void can_get_type_variables_from_ParameterizedType() throws Exception {
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");
@@ -140,7 +98,7 @@
}
@Test
- public void typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() {
+ public void typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(StringList.class).resolveGenericReturnType(firstNamedMethod("iterator", StringList.class));
assertThat(genericMetadata.rawType()).isEqualTo(Iterator.class);
@@ -148,7 +106,7 @@
}
@Test
- public void typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() {
+ public void typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
@@ -156,7 +114,7 @@
}
@Test
- public void bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() {
+ public void bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returningK", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
@@ -165,7 +123,7 @@
}
@Test
- public void fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() {
+ public void fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
@@ -173,7 +131,7 @@
}
@Test
- public void paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() {
+ public void paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Collection.class);
@@ -183,7 +141,7 @@
}
@Test
- public void paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() {
+ public void paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("paramType_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
@@ -192,7 +150,7 @@
}
@Test
- public void typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() {
+ public void typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("typeVar_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
@@ -201,7 +159,7 @@
}
@Test
- public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() {
+ public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(StringBuilder.class).resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class));
assertThat(genericMetadata.rawType()).isEqualTo(StringBuilder.class);
@@ -209,8 +167,9 @@
}
+
@Test
- public void paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() {
+ public void paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_class_lower_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
@@ -220,18 +179,17 @@
}
@Test
- public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() {
+ public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
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");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
- assertThat(boundedType.interfaceBounds()).contains(Cloneable.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() {
+ public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_upper_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
@@ -241,75 +199,6 @@
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class);
}
- @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);
- }
-
- @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();
- }
-
- private ParameterizedType parameterizedTypeOf(final Class<?> rawType, final Class<?> ownerType, final Type... actualTypeArguments) {
- return new ParameterizedType() {
- @Override
- public Type[] getActualTypeArguments() {
- return actualTypeArguments;
- }
-
- @Override
- public Type getRawType() {
- return rawType;
- }
-
- @Override
- public Type getOwnerType() {
- return ownerType;
- }
-
- public boolean equals(Object other) {
- if (other instanceof ParameterizedType) {
- ParameterizedType otherParamType = (ParameterizedType) other;
- if (this == otherParamType) {
- return true;
- } else {
- return equals(ownerType, otherParamType.getOwnerType())
- && equals(rawType, otherParamType.getRawType())
- && Arrays.equals(actualTypeArguments, otherParamType.getActualTypeArguments());
- }
- } else {
- return false;
- }
- }
-
- private boolean equals(Object a, Object b) {
- return (a == b) || (a != null && a.equals(b));
- }
- };
- }
-
private Type typeVariableValue(Map<TypeVariable<?>, Type> typeVariables, String typeVariableName) {
for (Map.Entry<TypeVariable<?>, Type> typeVariableTypeEntry : typeVariables.entrySet()) {
if (typeVariableTypeEntry.getKey().getName().equals(typeVariableName)) {
diff --git a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
index 2e56742..e846216 100644
--- a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
+++ b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
@@ -10,7 +10,7 @@
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoAssertionError;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockito.verification.VerificationMode;
import static org.hamcrest.CoreMatchers.is;
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 107f5ce..4ce557e 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
@@ -5,125 +5,78 @@
package org.mockito.internal.verification.checkers;
+import static java.util.Arrays.asList;
+
+import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.internal.invocation.*;
-import org.mockito.internal.invocation.mockref.MockReference;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
+import org.mockito.internal.invocation.InvocationBuilder;
+import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.Invocation;
-import org.mockito.invocation.Location;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
-import java.util.ArrayList;
-import java.util.List;
-
-import static java.util.Arrays.asList;
-import static java.util.Collections.singletonList;
-
public class MissingInvocationCheckerTest extends TestBase {
- private InvocationMatcher wanted;
- private List<Invocation> invocations;
+ private InvocationMatcher wanted;
+ private List<Invocation> 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() {
- wanted = buildSimpleMethod().toInvocationMatcher();
- invocations = asList(buildSimpleMethod().toInvocation());
+ @Test
+ public void shouldPassBecauseActualInvocationFound() {
+ wanted = buildSimpleMethod().toInvocationMatcher();
+ invocations = asList(buildSimpleMethod().toInvocation());
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
+ MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
+ }
- @Test
- public void shouldReportWantedButNotInvoked() {
- wanted = buildSimpleMethod().toInvocationMatcher();
- invocations = asList(buildDifferentMethod().toInvocation());
+ @Test
+ public void shouldReportWantedButNotInvoked() {
+ wanted = buildSimpleMethod().toInvocationMatcher();
+ invocations = asList(buildDifferentMethod().toInvocation());
- exception.expect(WantedButNotInvoked.class);
- exception.expectMessage("Wanted but not invoked:");
- exception.expectMessage("mock.simpleMethod()");
- exception.expectMessage("However, there was exactly 1 interaction with this mock:");
- exception.expectMessage("mock.differentMethod();");
+ exception.expect(WantedButNotInvoked.class);
+ exception.expectMessage("Wanted but not invoked:");
+ exception.expectMessage("mock.simpleMethod()");
+ exception.expectMessage("However, there was exactly 1 interaction with this mock:");
+ exception.expectMessage("mock.differentMethod();");
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
+ MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
+ }
- @Test
- public void shouldReportWantedInvocationDiffersFromActual() {
- wanted = buildIntArgMethod(new InvocationBuilder()).arg(2222).toInvocationMatcher();
- invocations = asList(buildIntArgMethod(new InvocationBuilder()).arg(1111).toInvocation());
+ @Test
+ public void shouldReportWantedInvocationDiffersFromActual() {
+ wanted = buildIntArgMethod().arg(2222).toInvocationMatcher();
+ invocations = asList(buildIntArgMethod().arg(1111).toInvocation());
- exception.expect(ArgumentsAreDifferent.class);
+ exception.expect(ArgumentsAreDifferent.class);
- exception.expectMessage("Argument(s) are different! Wanted:");
- exception.expectMessage("mock.intArgumentMethod(2222);");
- exception.expectMessage("Actual invocation has different arguments:");
- exception.expectMessage("mock.intArgumentMethod(1111);");
+ exception.expectMessage("Argument(s) are different! Wanted:");
+ exception.expectMessage("mock.intArgumentMethod(2222);");
+ exception.expectMessage("Actual invocation has different arguments:");
+ exception.expectMessage("mock.intArgumentMethod(1111);");
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
+ MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
+ }
- @Test
- public void shouldReportUsingInvocationDescription() {
- wanted = buildIntArgMethod(new CustomInvocationBuilder()).arg(2222).toInvocationMatcher();
- invocations = singletonList(buildIntArgMethod(new CustomInvocationBuilder()).arg(1111).toInvocation());
+ private InvocationBuilder buildIntArgMethod() {
+ return new InvocationBuilder().mock(mock).method("intArgumentMethod").argTypes(int.class);
+ }
- exception.expect(ArgumentsAreDifferent.class);
+ private InvocationBuilder buildSimpleMethod() {
+ return new InvocationBuilder().mock(mock).simpleMethod();
+ }
- exception.expectMessage("Argument(s) are different! Wanted:");
- exception.expectMessage("mock.intArgumentMethod(MyCoolPrint(2222));");
- exception.expectMessage("Actual invocation has different arguments:");
- exception.expectMessage("mock.intArgumentMethod(MyCoolPrint(1111));");
-
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
-
- private InvocationBuilder buildIntArgMethod(InvocationBuilder invocationBuilder) {
- return invocationBuilder.mock(mock).method("intArgumentMethod").argTypes(int.class);
- }
-
- private InvocationBuilder buildSimpleMethod() {
- return new InvocationBuilder().mock(mock).simpleMethod();
- }
-
- private InvocationBuilder buildDifferentMethod() {
- return new InvocationBuilder().mock(mock).differentMethod();
- }
-
- static class CustomInvocationBuilder extends InvocationBuilder {
- @Override
- protected Invocation createInvocation(MockReference<Object> mockRef, MockitoMethod mockitoMethod, final Object[] arguments,
- RealMethod realMethod, Location location, int sequenceNumber) {
- return new InterceptedInvocation(mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber) {
- @Override
- public List<ArgumentMatcher> getArgumentsAsMatchers() {
- List<ArgumentMatcher> matchers = new ArrayList<ArgumentMatcher>();
- 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 + ")";
- }
- });
- }
- return matchers;
- }
- };
- }
- }
+ private InvocationBuilder buildDifferentMethod() {
+ return new InvocationBuilder().mock(mock).differentMethod();
+ }
}
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 51cbc02..7f37b12 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java
@@ -12,7 +12,7 @@
import org.mockito.Mock;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.verification.InOrderContextImpl;
diff --git a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
index 85e0113..90569a8 100644
--- a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
+++ b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
@@ -33,10 +33,10 @@
Objenesis.class
)
.withCodeSourceUrlOf(coverageTool())
- .without("junit", "org.junit", "org.opentest4j")
+ .without("junit", "org.junit")
.build();
- Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit", "opentest4j").listOwnedClasses();
+ Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit").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");
diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java
index 69d1d03..7ec3750 100644
--- a/src/test/java/org/mockitousage/IMethods.java
+++ b/src/test/java/org/mockitousage/IMethods.java
@@ -124,8 +124,6 @@
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, String[] two);
Object threeArgumentMethod(int valueOne, Object valueTwo, String valueThree);
diff --git a/src/test/java/org/mockitousage/MethodsImpl.java b/src/test/java/org/mockitousage/MethodsImpl.java
index d538dd1..9417cbe 100644
--- a/src/test/java/org/mockitousage/MethodsImpl.java
+++ b/src/test/java/org/mockitousage/MethodsImpl.java
@@ -237,10 +237,6 @@
return null;
}
- public String simpleMethod(String one, Integer two, Integer three, Integer four, Integer five, Integer six) {
- return null;
- }
-
public String simpleMethod(String one, String[] two) {
return null;
}
diff --git a/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java b/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java
index 87ec697..ae5edd5 100644
--- a/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java
+++ b/src/test/java/org/mockitousage/basicapi/MockingMultipleInterfacesTest.java
@@ -93,6 +93,7 @@
}
}
+
@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
diff --git a/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java b/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java
index b5892ef..98ab7d2 100644
--- a/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java
+++ b/src/test/java/org/mockitousage/basicapi/MocksCreationTest.java
@@ -12,21 +12,13 @@
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.RETURNS_SMART_NULLS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.withSettings;
+import static org.mockito.Mockito.*;
@SuppressWarnings("unchecked")
public class MocksCreationTest extends TestBase {
@@ -34,12 +26,12 @@
private class HasPrivateConstructor {}
@Test
- public void should_create_mock_when_constructor_is_private() {
+ public void shouldCreateMockWhenConstructorIsPrivate() {
assertNotNull(Mockito.mock(HasPrivateConstructor.class));
}
@Test
- public void should_combine_mock_name_and_smart_nulls() {
+ public void shouldCombineMockNameAndSmartNulls() {
//given
IMethods mock = mock(IMethods.class, withSettings()
.defaultAnswer(RETURNS_SMART_NULLS)
@@ -59,7 +51,7 @@
}
@Test
- public void should_combine_mock_name_and_extra_interfaces() {
+ public void shouldCombineMockNameAndExtraInterfaces() {
//given
IMethods mock = mock(IMethods.class, withSettings()
.extraInterfaces(List.class)
@@ -75,7 +67,7 @@
}
@Test
- public void should_specify_mock_name_via_settings() {
+ public void shouldSpecifyMockNameViaSettings() {
//given
IMethods mock = mock(IMethods.class, withSettings().name("great mockie"));
@@ -87,7 +79,7 @@
}
@Test
- public void should_scream_when_spy_created_with_wrong_type() {
+ public void shouldScreamWhenSpyCreatedWithWrongType() {
//given
List list = new LinkedList();
try {
@@ -100,28 +92,14 @@
@SuppressWarnings({"CheckReturnValue", "MockitoUsage"})
@Test
- public void should_allow_creating_spies_with_correct_type() {
+ public void shouldAllowCreatingSpiesWithCorrectType() {
List list = new LinkedList();
mock(LinkedList.class, withSettings().spiedInstance(list));
}
@Test
- public void should_allow_inline_mock_creation() {
+ public void shouldAllowInlineMockCreation() throws Exception {
when(mock(Set.class).isEmpty()).thenReturn(false);
}
- @Retention(RetentionPolicy.RUNTIME)
- @interface SomeAnnotation {}
-
- @SomeAnnotation static class Foo {}
-
- @Test
- public void should_strip_annotations() {
- Foo withAnnotations = mock(Foo.class);
- Foo withoutAnnotations = mock(Foo.class, withSettings().withoutAnnotations());
-
- //expect:
- assertTrue(withAnnotations.getClass().isAnnotationPresent(SomeAnnotation.class));
- assertFalse(withoutAnnotations.getClass().isAnnotationPresent(SomeAnnotation.class));
- }
}
diff --git a/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java b/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java
index c8f3dd5..3e4faaf 100644
--- a/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java
+++ b/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java
@@ -9,7 +9,7 @@
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.NoInteractionsWanted;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitoutil.TestBase;
import java.util.ArrayList;
diff --git a/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java b/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java
deleted file mode 100644
index 280fc61..0000000
--- a/src/test/java/org/mockitousage/debugging/StubbingLookupListenerCallbackTest.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (c) 2018 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockitousage.debugging;
-
-import org.junit.Test;
-import org.mockito.ArgumentMatcher;
-import org.mockito.InOrder;
-import org.mockito.listeners.StubbingLookupEvent;
-import org.mockito.listeners.StubbingLookupListener;
-import org.mockito.mock.MockCreationSettings;
-import org.mockitousage.IMethods;
-import org.mockitoutil.ConcurrentTesting;
-import org.mockitoutil.TestBase;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.*;
-
-public class StubbingLookupListenerCallbackTest extends TestBase {
-
- StubbingLookupListener listener = mock(StubbingLookupListener.class);
- StubbingLookupListener listener2 = mock(StubbingLookupListener.class);
- Foo mock = mock(Foo.class, withSettings().stubbingLookupListeners(listener));
-
- @Test
- public void should_call_listener_when_mock_return_normally_with_stubbed_answer() {
- // given
- doReturn("coke").when(mock).giveMeSomeString("soda");
- doReturn("java").when(mock).giveMeSomeString("coffee");
-
- // when
- mock.giveMeSomeString("soda");
-
- // then
- verify(listener).onStubbingLookup(argThat(new ArgumentMatcher<StubbingLookupEvent>() {
- @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
- public void should_call_listener_when_mock_return_normally_with_default_answer() {
- // given
- doReturn("java").when(mock).giveMeSomeString("coffee");
-
- // when
- mock.giveMeSomeString("soda");
-
- // then
- verify(listener).onStubbingLookup(argThat(new ArgumentMatcher<StubbingLookupEvent>() {
- @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
- public void should_not_call_listener_when_mock_is_not_called() {
- // when stubbing is recorded
- doReturn("java").when(mock).giveMeSomeString("coffee");
-
- // then
- verifyZeroInteractions(listener);
- }
-
- @Test
- public void should_allow_same_listener() {
- // given
- Foo mock = mock(Foo.class, withSettings().stubbingLookupListeners(listener, listener));
-
- // when
- mock.giveMeSomeString("tea");
- mock.giveMeSomeString("coke");
-
- // then each listener was notified 2 times (notified 4 times in total)
- verify(listener, times(4)).onStubbingLookup(any(StubbingLookupEvent.class));
- }
-
- @Test
- public void should_call_all_listeners_in_order() {
- // given
- Foo mock = mock(Foo.class, withSettings().stubbingLookupListeners(listener, listener2));
- doReturn("sprite").when(mock).giveMeSomeString("soda");
-
- // when
- mock.giveMeSomeString("soda");
-
- // then
- InOrder inOrder = inOrder(listener, listener2);
- inOrder.verify(listener).onStubbingLookup(any(StubbingLookupEvent.class));
- inOrder.verify(listener2).onStubbingLookup(any(StubbingLookupEvent.class));
- }
-
- @Test
- public void should_call_all_listeners_when_mock_throws_exception() {
- // given
- Foo mock = mock(Foo.class, withSettings().stubbingLookupListeners(listener, listener2));
- doThrow(new NoWater()).when(mock).giveMeSomeString("tea");
-
- // when
- try {
- mock.giveMeSomeString("tea");
- fail();
- } catch (NoWater e) {
- // then
- verify(listener).onStubbingLookup(any(StubbingLookupEvent.class));
- verify(listener2).onStubbingLookup(any(StubbingLookupEvent.class));
- }
- }
-
- @Test
- public void should_delete_listener() {
- // given
- Foo mock = mock(Foo.class, withSettings().stubbingLookupListeners(listener, listener2));
-
- // when
- mock.doSomething("1");
- mockingDetails(mock).getMockCreationSettings().getStubbingLookupListeners().remove(listener2);
- mock.doSomething("2");
-
- // then
- verify(listener, times(2)).onStubbingLookup(any(StubbingLookupEvent.class));
- verify(listener2, times(1)).onStubbingLookup(any(StubbingLookupEvent.class));
- }
-
- @Test
- public void should_clear_listeners() {
- // given
- Foo mock = mock(Foo.class, withSettings().stubbingLookupListeners(listener, listener2));
-
- // when
- mockingDetails(mock).getMockCreationSettings().getStubbingLookupListeners().clear();
- mock.doSomething("foo");
-
- // then
- verifyZeroInteractions(listener, listener2);
- }
-
- @Test
- public void add_listeners_concurrently_sanity_check() throws Exception {
- //given
- final IMethods mock = mock(IMethods.class);
- final MockCreationSettings<?> settings = mockingDetails(mock).getMockCreationSettings();
-
- List<Runnable> runnables = new LinkedList<Runnable>();
- 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);
- }
- });
- }
-
- //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.
- assertEquals(50, settings.getStubbingLookupListeners().size());
- }
-
- private static class NoWater extends RuntimeException {}
-}
diff --git a/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java b/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java
index cf10301..1cd495c 100644
--- a/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java
+++ b/src/test/java/org/mockitousage/internal/debugging/LocationImplTest.java
@@ -4,15 +4,13 @@
*/
package org.mockitousage.internal.debugging;
+import static org.assertj.core.api.Assertions.assertThat;
+
import org.junit.Test;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.exceptions.stacktrace.StackTraceFilter;
import org.mockitoutil.TestBase;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("serial")
@@ -39,18 +37,4 @@
//then
assertEquals("-> at <<unknown line>>", loc);
}
-
- @Test
- public void provides_location_class() {
- //when
- final List<String> files = new ArrayList<String>();
- new Runnable() { //anonymous inner class adds stress to the check
- public void run() {
- files.add(new LocationImpl().getSourceFile());
- }
- }.run();
-
- //then
- assertEquals("LocationImplTest.java", files.get(0));
- }
}
diff --git a/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java
index 9921176..2e13171 100644
--- a/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java
+++ b/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java
@@ -9,7 +9,7 @@
import org.mockito.Mock;
import org.mockito.quality.Strictness;
import org.mockito.internal.junit.JUnitRule;
-import org.mockito.plugins.MockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
import org.mockito.junit.MockitoRule;
import org.mockitousage.IMethods;
diff --git a/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java
index 3ea7add..dfec883 100644
--- a/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java
+++ b/src/test/java/org/mockitousage/junitrule/MockitoJUnitRuleTest.java
@@ -19,10 +19,6 @@
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
- // Fixes #1578: Protect against multiple execution.
- @Rule
- public MockitoRule mockitoRule2 = mockitoRule;
-
@Mock
private Injected injected;
diff --git a/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java
index fa8bb35..b802013 100644
--- a/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java
+++ b/src/test/java/org/mockitousage/junitrule/StrictJUnitRuleTest.java
@@ -14,7 +14,6 @@
import org.mockito.junit.MockitoJUnit;
import org.mockito.quality.Strictness;
import org.mockitousage.IMethods;
-import org.mockitousage.strictness.ProductionCode;
import org.mockitoutil.SafeJUnitRule;
import static org.junit.Assert.assertEquals;
@@ -76,7 +75,7 @@
//when
when(mock.simpleMethod(10)).thenReturn("10");
- ProductionCode.simpleMethod(mock, 20);
+ when(mock.simpleMethod(20)).thenReturn("20");
}
@Test public void fails_fast_when_stubbing_invoked_with_different_argument() throws Throwable {
@@ -88,7 +87,7 @@
"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" +
+ " -> at org.mockitousage.junitrule.StrictJUnitRuleTest.fails_fast_when_stubbing_invoked_with_different_argument(StrictJUnitRuleTest.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" +
@@ -117,7 +116,7 @@
//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);
+ mock.simpleMethod(15);
}
@Test public void verify_no_more_interactions_ignores_stubs() throws Throwable {
diff --git a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
index 9b4cc1e..8f4c420 100644
--- a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
+++ b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
@@ -8,14 +8,13 @@
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
-import org.mockito.ArgumentMatcher;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.VerificationCollector;
import org.mockitousage.IMethods;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
public class VerificationCollectorImplTest {
@@ -47,54 +46,14 @@
IMethods methods = mock(IMethods.class);
- methods.intArgumentMethod(6);
-
verify(methods).simpleMethod();
verify(methods).byteReturningMethod();
- verify(methods).intArgumentMethod(8);
- verify(methods).longArg(8L);
try {
collector.collectAndReport();
- failBecauseExceptionWasNotThrown(MockitoAssertionError.class);
+ fail();
} catch (MockitoAssertionError error) {
assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
assertThat(error).hasMessageContaining("2. Wanted but not invoked:");
- assertThat(error).hasMessageContaining("3. Argument(s) are different! Wanted:");
- assertThat(error).hasMessageContaining("4. Wanted but not invoked:");
- }
- }
-
- @Test
- public void should_collect_matching_error_from_non_matching_arguments() {
- VerificationCollector collector = MockitoJUnit.collector().assertLazily();
-
- IMethods methods = mock(IMethods.class);
-
- methods.intArgumentMethod(6);
- methods.longArg(8L);
- methods.forShort((short)6);
-
- verify(methods).intArgumentMethod(8);
- verify(methods).longArg(longThat(new ArgumentMatcher<Long>() {
- @Override
- public boolean matches(Long argument) {
- throw new AssertionError("custom error message");
- }
- }));
- verify(methods).forShort(shortThat(new ArgumentMatcher<Short>() {
- @Override
- public boolean matches(Short argument) {
- return false;
- }
- }));
-
- try {
- collector.collectAndReport();
- failBecauseExceptionWasNotThrown(MockitoAssertionError.class);
- } catch (MockitoAssertionError error) {
- assertThat(error).hasMessageContaining("1. Argument(s) are different! Wanted:");
- assertThat(error).hasMessageContaining("2. custom error message");
- assertThat(error).hasMessageContaining("3. Argument(s) are different! Wanted:");
}
}
@@ -107,7 +66,7 @@
verify(methods, never()).simpleMethod();
verify(methods).byteReturningMethod();
- this.assertExactlyOneFailure(collector);
+ this.assertAtLeastOneFailure(collector);
}
@Test
@@ -120,13 +79,13 @@
verify(methods).byteReturningMethod();
verify(methods).simpleMethod();
- this.assertExactlyOneFailure(collector);
+ this.assertAtLeastOneFailure(collector);
}
- private void assertExactlyOneFailure(VerificationCollector collector) {
+ private void assertAtLeastOneFailure(VerificationCollector collector) {
try {
collector.collectAndReport();
- failBecauseExceptionWasNotThrown(MockitoAssertionError.class);
+ fail();
} catch (MockitoAssertionError error) {
assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
assertThat(error.getMessage()).doesNotContain("2.");
@@ -138,11 +97,8 @@
JUnitCore runner = new JUnitCore();
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.getFailureCount()).isEqualTo(1);
+ assertThat(result.getFailures().get(0).getMessage()).contains("1. Wanted but not invoked:");
}
// This class is picked up when running a test suite using an IDE. It fails on purpose.
@@ -165,14 +121,5 @@
verify(methods).simpleMethod();
}
-
- @Test
- public void should_fail_with_args() {
- IMethods methods = mock(IMethods.class);
- methods.intArgumentMethod(8);
-
- verify(methods).intArgumentMethod(9);
- verify(methods).byteReturningMethod();
- }
}
}
diff --git a/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java
index ef932b7..f61572b 100644
--- a/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java
+++ b/src/test/java/org/mockitousage/junitrunner/StrictStubsRunnerTest.java
@@ -13,7 +13,6 @@
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockitousage.IMethods;
-import org.mockitousage.strictness.ProductionCode;
import org.mockitoutil.JUnitResultAssert;
import org.mockitoutil.TestBase;
@@ -66,7 +65,7 @@
}
@Test public void argument_mismatch() {
when(mock.simpleMethod(10)).thenReturn("");
- ProductionCode.simpleMethod(mock, 20);
+ mock.simpleMethod(20);
}
}
}
diff --git a/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java b/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java
index 8c94d3d..3114834 100644
--- a/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java
+++ b/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java
@@ -7,7 +7,7 @@
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java b/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java
index 4d6b868..bee9569 100644
--- a/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java
@@ -11,7 +11,7 @@
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java
index d38e676..9c4dcb0 100644
--- a/src/test/java/org/mockitousage/matchers/MatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java
@@ -14,7 +14,7 @@
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@@ -286,7 +286,7 @@
when(mock.oneArg(anyLong())).thenReturn("6");
when(mock.oneArg(anyShort())).thenReturn("7");
when(mock.oneArg((String) anyObject())).thenReturn("8");
- when(mock.oneArg(Mockito.<Object>anyObject())).thenReturn("9");
+ when(mock.oneArg(anyObject())).thenReturn("9");
when(mock.oneArg(any(RandomAccess.class))).thenReturn("10");
assertEquals("0", mock.oneArg(true));
@@ -594,14 +594,14 @@
public void eq_matcher_and_nulls() {
mock.simpleMethod((Object) null);
- verify(mock).simpleMethod(Mockito.<Object>eq(null));
+ verify(mock).simpleMethod(eq(null));
}
@Test
public void same_matcher_and_nulls() {
mock.simpleMethod((Object) null);
- verify(mock).simpleMethod(Mockito.<Object>same(null));
+ verify(mock).simpleMethod(same(null));
}
@Test
diff --git a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
index 6c0f9c2..46773b8 100644
--- a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
@@ -8,8 +8,7 @@
import org.assertj.core.api.ThrowableAssert;
import org.junit.Test;
import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@@ -35,8 +34,8 @@
public void any_should_be_actual_alias_to_anyObject() {
mock.simpleMethod((Object) null);
- verify(mock).simpleMethod(Mockito.<Object>any());
- verify(mock).simpleMethod(Mockito.<Object>anyObject());
+ verify(mock).simpleMethod(any());
+ verify(mock).simpleMethod(anyObject());
}
@Test
diff --git a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java
index a972d0f..84ad482 100644
--- a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java
@@ -7,7 +7,7 @@
import org.junit.Before;
import org.junit.Test;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitoutil.TestBase;
import static org.mockito.Matchers.refEq;
diff --git a/src/test/java/org/mockitousage/matchers/VarargsTest.java b/src/test/java/org/mockitousage/matchers/VarargsTest.java
index 1433919..685c918 100644
--- a/src/test/java/org/mockitousage/matchers/VarargsTest.java
+++ b/src/test/java/org/mockitousage/matchers/VarargsTest.java
@@ -23,7 +23,7 @@
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockitousage.IMethods;
diff --git a/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java b/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java
index 9485d1c..a1a3500 100644
--- a/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java
+++ b/src/test/java/org/mockitousage/plugins/MockitoPluginsTest.java
@@ -11,7 +11,6 @@
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;
@@ -33,7 +32,6 @@
assertNotNull(plugins.getDefaultPlugin(InstantiatorProvider.class));
assertNotNull(plugins.getDefaultPlugin(InstantiatorProvider2.class));
assertNotNull(plugins.getDefaultPlugin(AnnotationEngine.class));
- assertNotNull(plugins.getDefaultPlugin(MockitoLogger.class));
}
@SuppressWarnings("deprecation")
diff --git a/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java b/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java
index f8a262d..3c6601b 100644
--- a/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java
+++ b/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java
@@ -2,6 +2,7 @@
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
+
package org.mockitousage.serialization;
import org.junit.Before;
@@ -17,7 +18,6 @@
import java.util.List;
import java.util.concurrent.Callable;
-import static org.assertj.core.api.Assertions.assertThat;
public class AcrossClassLoaderSerializationTest {
@@ -33,7 +33,6 @@
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");
}
private Object read_stream_and_deserialize_it_in_class_loader_B(byte[] bytes) throws Exception {
diff --git a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java
index c26e8d8..3294614 100644
--- a/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java
+++ b/src/test/java/org/mockitousage/serialization/DeepStubsSerializableTest.java
@@ -11,11 +11,7 @@
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.fail;
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.withSettings;
+import static org.mockito.Mockito.*;
import static org.mockitoutil.SimpleSerializationUtil.serializeAndBack;
public class DeepStubsSerializableTest {
@@ -49,7 +45,7 @@
assertThat(deserialized_deep_stub.iterator().next().add("yes")).isEqualTo(true);
}
- @Test
+ @Test(expected = ClassCastException.class)
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());
@@ -57,14 +53,10 @@
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);
- }
+ // when stubbing on a deserialized mock
+ when(deserialized_deep_stub.iterator().next().get(42)).thenReturn("no");
+
+ // then revert to the default RETURNS_DEEP_STUBS and the code will raise a ClassCastException
}
static class SampleClass implements Serializable {
diff --git a/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java
deleted file mode 100644
index 9d78669..0000000
--- a/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2017 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockitousage.serialization;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-
-import java.io.Serializable;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.*;
-import static org.mockitoutil.SimpleSerializationUtil.serializeAndBack;
-
-@RunWith(MockitoJUnitRunner.StrictStubs.class)
-public class StrictStubsSerializableTest {
-
- @Mock(serializable = true) private SampleClass sampleClass;
-
- @Test
- public void should_serialize_and_deserialize_mock_created_with_serializable_and_strict_stubs() throws Exception {
- // given
- when(sampleClass.isFalse()).thenReturn(true);
-
- // when
- SampleClass deserializedSample = serializeAndBack(sampleClass);
- // to satisfy strict stubbing
- deserializedSample.isFalse();
- verify(deserializedSample).isFalse();
- verify(sampleClass, never()).isFalse();
-
- // then
- assertThat(deserializedSample.isFalse()).isEqualTo(true);
- assertThat(sampleClass.isFalse()).isEqualTo(true);
- }
-
- static class SampleClass implements Serializable {
-
- boolean isFalse() {
- return false;
- }
- }
-}
diff --git a/src/test/java/org/mockitousage/session/MockitoSessionTest.java b/src/test/java/org/mockitousage/session/MockitoSessionTest.java
index 5271f92..a87928c 100644
--- a/src/test/java/org/mockitousage/session/MockitoSessionTest.java
+++ b/src/test/java/org/mockitousage/session/MockitoSessionTest.java
@@ -5,15 +5,12 @@
package org.mockitousage.session;
import org.junit.After;
-import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
-import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoSession;
-import org.mockito.exceptions.misusing.InjectMocksException;
import org.mockito.exceptions.misusing.UnfinishedStubbingException;
import org.mockito.quality.Strictness;
import org.mockitousage.IMethods;
@@ -100,17 +97,6 @@
resetState();
}
- @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);
- }
-
public static class SessionWithoutAnyConfiguration {
@Mock IMethods mock;
@@ -235,36 +221,4 @@
verify(mock);
}
}
-
- public static class SessionWithInitMocksFailure {
- @InjectMocks private ConstructorFail sut;
- MockitoSession mockito;
-
- @Before
- public void before() {
- mockito = Mockito.mockitoSession().initMocks(this).startMocking();
- }
-
- @After public void after() {
- if (mockito != null) {
- //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 test2() {
- //should fail the same way
- }
-
- static class ConstructorFail {
- ConstructorFail() {
- throw new RuntimeException("Boo!");
- }
- }
- }
}
diff --git a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java
index 029ea2f..92e1e85 100644
--- a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java
@@ -7,7 +7,7 @@
import org.junit.Test;
import org.mockito.Mock;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java b/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java
deleted file mode 100644
index 38bcaa3..0000000
--- a/src/test/java/org/mockitousage/strictness/LenientMockAnnotationTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitousage.strictness;
-
-import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.exceptions.misusing.PotentialStubbingProblem;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoRule;
-import org.mockito.quality.Strictness;
-import org.mockitousage.IMethods;
-
-import static org.mockito.Mockito.when;
-
-public class LenientMockAnnotationTest {
-
- public @Rule MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
- @Mock(lenient = true) IMethods lenientMock;
- @Mock IMethods regularMock;
-
- @Test
- public void mock_is_lenient() {
- when(lenientMock.simpleMethod("1")).thenReturn("1");
- when(regularMock.simpleMethod("2")).thenReturn("2");
-
- //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);
- }
-}
diff --git a/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java b/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java
deleted file mode 100644
index 2487b4d..0000000
--- a/src/test/java/org/mockitousage/strictness/PotentialStubbingSensitivityTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitousage.strictness;
-
-import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.exceptions.misusing.PotentialStubbingProblem;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoRule;
-import org.mockito.quality.Strictness;
-import org.mockitousage.IMethods;
-
-import static org.mockito.Mockito.when;
-
-public class PotentialStubbingSensitivityTest {
-
- @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
- @Mock IMethods mock;
-
- @Before
- public void setup() {
- when(mock.simpleMethod("1")).thenReturn("1");
- }
-
- @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
- when(mock.simpleMethod("2")).thenReturn("2");
-
- //methods in anonymous inner classes are ok, too
- new Runnable() {
- public void run() {
- when(mock.simpleMethod("3")).thenReturn("3");
- }
- }.run();
-
- //avoiding unnecessary stubbing failures:
- mock.simpleMethod("1");
- mock.simpleMethod("2");
- mock.simpleMethod("3");
- }
-
- @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);
- }
-}
diff --git a/src/test/java/org/mockitousage/strictness/ProductionCode.java b/src/test/java/org/mockitousage/strictness/ProductionCode.java
deleted file mode 100644
index 036e2c2..0000000
--- a/src/test/java/org/mockitousage/strictness/ProductionCode.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitousage.strictness;
-
-import org.mockitousage.IMethods;
-
-/**
- * Test utility class that simulates invocation of mock in production code.
- * In certain tests, the production code needs to be invoked in a different class/source file than the test.
- */
-public class ProductionCode {
-
- public static void simpleMethod(IMethods mock, String argument) {
- mock.simpleMethod(argument);
- }
-
- public static void simpleMethod(IMethods mock, int argument) {
- mock.simpleMethod(argument);
- }
-}
diff --git a/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java b/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java
index db265c5..2dce3e0 100644
--- a/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java
+++ b/src/test/java/org/mockitousage/strictness/StrictnessPerMockTest.java
@@ -60,8 +60,9 @@
//and on strict stub mock (created by session), we cannot call stubbed method with different arg:
Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ @Override
public void call() throws Throwable {
- ProductionCode.simpleMethod(strictStubsMock, 200);
+ strictStubsMock.simpleMethod(200);
}
}).isInstanceOf(PotentialStubbingProblem.class);
}
diff --git a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java
index 499ec18..3838bee 100644
--- a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java
+++ b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingTest.java
@@ -51,7 +51,7 @@
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() throws Throwable {
- ProductionCode.simpleMethod(mock, "100");
+ mock.simpleMethod("100");
}
}).isInstanceOf(PotentialStubbingProblem.class);
}
diff --git a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java
index 1aa565a..e42d340 100644
--- a/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java
+++ b/src/test/java/org/mockitousage/strictness/StrictnessPerStubbingWithRunnerTest.java
@@ -33,8 +33,9 @@
//but on strict stubbing, we cannot:
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- ProductionCode.simpleMethod(mock, "100");
+ @Override
+ public void call() throws Throwable {
+ mock.simpleMethod("100");
}
}).isInstanceOf(PotentialStubbingProblem.class);
diff --git a/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java b/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java
index c071e01..592cca9 100644
--- a/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java
+++ b/src/test/java/org/mockitousage/strictness/StrictnessWhenRuleStrictnessIsUpdatedTest.java
@@ -34,8 +34,9 @@
//then previous mock is strict:
when(mock.simpleMethod(1)).thenReturn("1");
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- ProductionCode.simpleMethod(mock, 2);
+ @Override
+ public void call() throws Throwable {
+ mock.simpleMethod(2);
}
}).isInstanceOf(PotentialStubbingProblem.class);
@@ -53,8 +54,9 @@
//then previous mock is strict:
when(mock.simpleMethod(1)).thenReturn("1");
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- ProductionCode.simpleMethod(mock, 2);
+ @Override
+ public void call() throws Throwable {
+ mock.simpleMethod(2);
}
}).isInstanceOf(PotentialStubbingProblem.class);
diff --git a/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java b/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java
index d63021c..3a323fb 100644
--- a/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java
+++ b/src/test/java/org/mockitousage/strictness/StrictnessWithRulesTest.java
@@ -35,8 +35,9 @@
//but on strict stubbing, we cannot:
assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
- public void call() {
- ProductionCode.simpleMethod(mock, "100");
+ @Override
+ public void call() throws Throwable {
+ mock.simpleMethod("100");
}
}).isInstanceOf(PotentialStubbingProblem.class);
diff --git a/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java b/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java
index c06aac5..c63cb6d 100644
--- a/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java
@@ -13,9 +13,9 @@
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
-import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
public class BasicStubbingTest extends TestBase {
@@ -124,30 +124,6 @@
try {
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());
- }
- }
-
- @Test
- public void test_stub_only_not_verifiable_verify_no_more_interactions() {
- IMethods localMock = mock(IMethods.class, withSettings().stubOnly());
-
- try {
- verifyNoMoreInteractions(localMock);
- fail();
- } catch (CannotVerifyStubOnlyMock e) {}
- }
-
- @Test
- public void test_stub_only_not_verifiable_in_order() {
- IMethods localMock = mock(IMethods.class, withSettings().stubOnly());
-
- try {
- inOrder(localMock);
- fail();
} catch (CannotVerifyStubOnlyMock e) {}
}
}
diff --git a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
index 0e574f0..5622b54 100644
--- a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
@@ -4,6 +4,7 @@
*/
package org.mockitousage.stubbing;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.exceptions.verification.TooManyActualInvocations;
@@ -16,11 +17,7 @@
import java.util.List;
import java.util.Locale;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
@@ -77,20 +74,6 @@
interface Second extends List<String> {}
- class BaseClassGenerics<A, B> {}
-
- class ReversedGenerics<A, B> extends BaseClassGenerics<A, B> {
- ReversedGenerics<B, A> reverse() {
- return null;
- }
-
- A finalMethod() {
- return null;
- }
- }
-
- class SuperOfReversedGenerics extends ReversedGenerics<String, Long> {}
-
@Test
public void myTest() throws Exception {
SocketFactory sf = mock(SocketFactory.class, RETURNS_DEEP_STUBS);
@@ -224,7 +207,7 @@
Person person = mock(Person.class, RETURNS_DEEP_STUBS);
@Test
- public void shouldStubbingBasicallyWorkFine() {
+ public void shouldStubbingBasicallyWorkFine() throws Exception {
//given
given(person.getAddress().getStreet().getName()).willReturn("Norymberska");
@@ -236,7 +219,7 @@
}
@Test
- public void shouldVerificationBasicallyWorkFine() {
+ public void shouldVerificationBasicallyWorkFine() throws Exception {
//given
person.getAddress().getStreet().getName();
@@ -245,7 +228,7 @@
}
@Test
- public void verification_work_with_argument_Matchers_in_nested_calls() {
+ public void verification_work_with_argument_Matchers_in_nested_calls() throws Exception {
//given
person.getAddress("111 Mock Lane").getStreet();
person.getAddress("111 Mock Lane").getStreet(Locale.ITALIAN).getName();
@@ -257,7 +240,7 @@
}
@Test
- public void deep_stub_return_same_mock_instance_if_invocation_matchers_matches() {
+ public void deep_stub_return_same_mock_instance_if_invocation_matchers_matches() throws Exception {
when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
person.getAddress("the docks").getStreet().getName();
@@ -270,7 +253,7 @@
}
@Test
- public void times_never_atLeast_atMost_verificationModes_should_work() {
+ public void times_never_atLeast_atMost_verificationModes_should_work() throws Exception {
when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
person.getAddress("the docks").getStreet().getName();
@@ -285,7 +268,7 @@
@Test
- public void inOrder_only_work_on_the_very_last_mock_but_it_works() {
+ public void inOrder_only_work_on_the_very_last_mock_but_it_works() throws Exception {
when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");
when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");
@@ -307,7 +290,7 @@
}
@Test
- public void verificationMode_only_work_on_the_last_returned_mock() {
+ public void verificationMode_only_work_on_the_last_returned_mock() throws Exception {
// 1st invocation on Address mock (stubbing)
when(person.getAddress("the docks").getStreet().getName()).thenReturn("deep");
@@ -321,14 +304,14 @@
verify(person.getAddress("the docks"), times(1)).getStreet();
fail();
} catch (TooManyActualInvocations e) {
- assertThat(e.getMessage())
+ Assertions.assertThat(e.getMessage())
.contains("Wanted 1 time")
.contains("But was 3 times");
}
}
@Test
- public void shouldFailGracefullyWhenClassIsFinal() {
+ public void shouldFailGracefullyWhenClassIsFinal() throws Exception {
//when
FinalClass value = new FinalClass();
given(person.getFinalClass()).willReturn(value);
@@ -343,14 +326,4 @@
assertNull(first.getString());
assertNull(first.getSecond().get(0));
}
-
- @Test
- public void deep_stub_does_not_stack_overflow_on_reversed_generics() {
- SuperOfReversedGenerics mock = mock(SuperOfReversedGenerics.class, RETURNS_DEEP_STUBS);
-
- when((Object) mock.reverse().finalMethod()).thenReturn(5L);
-
- assertThat(mock.reverse().finalMethod()).isEqualTo(5L);
- }
-
}
diff --git a/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java b/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java
deleted file mode 100644
index b5f9421..0000000
--- a/src/test/java/org/mockitousage/stubbing/SmartNullsGenericBugTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2018 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockitousage.stubbing;
-
-import org.assertj.core.api.Assertions;
-import org.junit.Test;
-import org.mockito.Answers;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.withSettings;
-
-//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));
-
- final Entity result = concreteDao.findById();
-
- 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));
-
- final String other = concreteDao.find();
-
- 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));
-
- final String other = concreteDao.findArgs(1, "plop");
-
- 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));
-
- final String other = concreteDao.findVarargs(42, "plip", "plop");
-
- Assertions.assertThat(other)
- .as("#1551")
- .isEqualTo("");
- }
-
- static class AbstractDao<T> {
- T findById() {
- return null;
- }
- <M> M find() { return null; }
- <M> M findArgs(int idx, M arg) { return null; }
- <M> M findVarargs(int idx, M... args) { return null; }
- }
-
- static class Entity { }
- static class ConcreteDao extends AbstractDao<Entity> { }
-}
diff --git a/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java b/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java
index 8e27f73..9b3dc86 100644
--- a/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/SmartNullsStubbingTest.java
@@ -42,15 +42,6 @@
}
}
- @Test
- public void should_not_throw_NPE_when_verifying_with_returns_smart_nulls() {
- Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
-
- when(mock.returnsFromArg(null)).thenReturn("Does not fail.");
-
- assertThat((Object) mock.returnsFromArg(null)).isEqualTo("Does not fail.");
- }
-
interface Bar {
void boo();
}
@@ -68,8 +59,6 @@
return null;
}
- <T> T returnsFromArg(T arg) { return arg; }
-
void boo() {}
}
diff --git a/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java b/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java
index dc68f12..724239e 100644
--- a/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StrictStubbingEndToEndTest.java
@@ -17,7 +17,6 @@
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.quality.Strictness;
import org.mockitousage.IMethods;
-import org.mockitousage.strictness.ProductionCode;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -103,7 +102,7 @@
@Test public void mismatch() {
given(mock.simpleMethod(1)).willReturn("");
- ProductionCode.simpleMethod(mock, 2);
+ mock.simpleMethod(2);
}
}
diff --git a/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java b/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java
index 7059719..2f40a2d 100644
--- a/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StrictStubbingTest.java
@@ -14,7 +14,6 @@
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.quality.Strictness;
import org.mockitousage.IMethods;
-import org.mockitousage.strictness.ProductionCode;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@@ -83,7 +82,7 @@
//stubbing argument mismatch is detected
assertThat(new Runnable() {
public void run() {
- ProductionCode.simpleMethod(mock, 200);
+ mock.simpleMethod(200);
}
}).throwsException(PotentialStubbingProblem.class);
}
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java
index a5e8e3a..417d998 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java
@@ -30,13 +30,11 @@
import org.mockito.stubbing.Answer3;
import org.mockito.stubbing.Answer4;
import org.mockito.stubbing.Answer5;
-import org.mockito.stubbing.Answer6;
import org.mockito.stubbing.VoidAnswer1;
import org.mockito.stubbing.VoidAnswer2;
import org.mockito.stubbing.VoidAnswer3;
import org.mockito.stubbing.VoidAnswer4;
import org.mockito.stubbing.VoidAnswer5;
-import org.mockito.stubbing.VoidAnswer6;
import org.mockitousage.IMethods;
import java.util.Date;
@@ -248,36 +246,4 @@
verify(target, times(1)).simpleMethod("hello", 1, 2, 3, 4);
}
- @Test
- 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<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 {
- final IMethods target = mock(IMethods.class);
-
- given(iMethods.simpleMethod(anyString(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt()))
- .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);
-
- // expect the answer to write correctly to "target"
- verify(target, times(1)).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
deleted file mode 100644
index b0c29d5..0000000
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2018 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockitousage.stubbing;
-
-import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockitoutil.TestBase;
-
-import java.util.List;
-
-import static org.mockito.Mockito.doThrow;
-
-//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
- Mockito.validateMockitoUsage();
- }
-
- abstract static class UninstantiableException extends RuntimeException {}
-}
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithDelegateTest.java
index 0d7c9b0..24c4854 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 org.junit.Test;
-import org.mockito.AdditionalAnswers;
import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockitousage.IMethods;
@@ -15,13 +14,12 @@
import java.util.Collection;
import java.util.List;
-import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
@SuppressWarnings("unchecked")
public class StubbingWithDelegateTest {
@@ -177,25 +175,4 @@
assertThat(e).isEqualTo(failure);
}
}
-
- interface Foo {
- int bar();
- }
-
- @Test
- public void should_call_anonymous_class_method() throws Throwable {
- Foo foo = new Foo() {
- public int bar() {
- return 0;
- }
- };
-
- Foo mock = mock(Foo.class);
- when(mock.bar()).thenAnswer(AdditionalAnswers.delegatesTo(foo));
-
- //when
- mock.bar();
-
- //then no exception is thrown
- }
}
diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
index af42261..b0e3179 100644
--- a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
+++ b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
@@ -12,7 +12,7 @@
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationTest.java
index 3ede48b..d9a74ff 100644
--- a/src/test/java/org/mockitousage/verification/BasicVerificationTest.java
+++ b/src/test/java/org/mockitousage/verification/BasicVerificationTest.java
@@ -11,7 +11,7 @@
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.TooManyActualInvocations;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
index e920ad8..8e1bf06 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
@@ -96,7 +96,7 @@
try {
inOrder.verify(one).simpleMethod(999);
fail();
- } catch (org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent e) {
+ } catch (org.mockito.exceptions.verification.junit.ArgumentsAreDifferent e) {
assertThat(e).hasMessageContaining("has different arguments");
}
}
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 7293434..43729f3 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -13,7 +13,7 @@
import org.mockito.exceptions.verification.NeverWantedButInvoked;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
index 8456c46..954b99f 100644
--- a/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
+++ b/src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java
@@ -7,7 +7,7 @@
import org.assertj.core.api.Assertions;
import org.junit.Test;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java
deleted file mode 100644
index 5e1bdcb..0000000
--- a/src/test/java/org/mockitousage/verification/VerificationInOrderWithTimeoutTest.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitousage.verification;
-
-import org.assertj.core.api.Assertions;
-import org.assertj.core.api.ThrowableAssert;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.Mock;
-import org.mockito.exceptions.base.MockitoException;
-import org.mockito.exceptions.verification.VerificationInOrderFailure;
-import org.mockito.junit.MockitoRule;
-import org.mockitousage.IMethods;
-import org.mockitoutil.async.AsyncTesting;
-
-import static org.mockito.Mockito.after;
-import static org.mockito.Mockito.inOrder;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.junit.MockitoJUnit.rule;
-
-public class VerificationInOrderWithTimeoutTest {
-
- @Rule public MockitoRule mockito = rule();
-
- @Mock private IMethods mock1;
- @Mock private IMethods mock2;
-
- private AsyncTesting async;
-
- @Before public void setUp() {
- async = new AsyncTesting();
- }
-
- @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
- }
-
- @Test
- public void should_verify_in_order_with_timeout() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'c'));
- async.runAfter(200, callMock(mock2, 'b'));
-
- // then
- InOrder inOrder = inOrder(mock1, mock2);
- inOrder.verify(mock1, timeout(100)).oneArg('a');
- inOrder.verify(mock2, timeout(500)).oneArg('b');
- }
-
- @Test
- public void should_verify_in_order_with_timeout_and_fail() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(100, callMock(mock2, 'b'));
-
- // 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');");
- }
-
- @Test
- public void should_verify_in_order_with_times_x() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'a'));
- async.runAfter(200, callMock(mock2, 'b'));
- async.runAfter(250, callMock(mock2, 'b'));
-
- // then
- InOrder inOrder = inOrder(mock1, mock2);
- inOrder.verify(mock1, timeout(100).times(2)).oneArg('a');
- inOrder.verify(mock2, timeout(500).times(2)).oneArg('b');
- }
-
- @Test
- public void should_verify_in_order_with_times_x_and_fail() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'a'));
- async.runAfter(200, callMock(mock2, 'b'));
- async.runAfter(250, callMock(mock2, 'b'));
-
- // then
- 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');");
- }
-
- @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
- }
-
- @Test
- public void should_verify_in_order_with_at_least_once() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'a'));
- async.runAfter(100, callMock(mock2, 'b'));
- async.runAfter(120, callMock(mock2, 'b'));
-
- // then
- InOrder inOrder = inOrder(mock1, mock2);
- inOrder.verify(mock1, timeout(200).atLeastOnce()).oneArg('a');
- inOrder.verify(mock2, timeout(500).atLeastOnce()).oneArg('b');
- }
-
- @Test
- public void should_verify_in_order_with_at_least_once_and_fail() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'a'));
- async.runAfter(100, callMock(mock2, 'b'));
- async.runAfter(120, callMock(mock2, 'b'));
-
- // 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');");
- }
-
- @Test
- public void should_verify_in_order_with_at_least_x() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'a'));
- async.runAfter(100, callMock(mock2, 'b'));
- async.runAfter(120, callMock(mock2, 'b'));
-
- // then
- InOrder inOrder = inOrder(mock1, mock2);
- inOrder.verify(mock1, timeout(200).atLeast(2)).oneArg('a');
- inOrder.verify(mock2, timeout(500).atLeast(2)).oneArg('b');
- }
-
- @Test
- public void should_verify_in_order_with_at_least_x_and_fail() {
- // when
- async.runAfter(20, callMock(mock1, 'a'));
- async.runAfter(50, callMock(mock1, 'a'));
- async.runAfter(100, callMock(mock2, 'b'));
- async.runAfter(120, callMock(mock2, 'b'));
-
- // 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");
- }
-
- private Runnable callMock(final IMethods mock, final char c) {
- return new Runnable() {
- @Override
- public void run() {
- mock.oneArg(c);
- }
- };
- }
-}
diff --git a/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java b/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java
index bfc2e22..027eb2c 100644
--- a/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java
@@ -10,7 +10,7 @@
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java b/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java
index 7bbb52b..f437c03 100644
--- a/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationWithAfterTest.java
@@ -66,7 +66,7 @@
Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
@Override
public void call() {
- verify(mock, after(600)).oneArg('1');
+ verify(mock, after(300)).oneArg('1');
}
}).isInstanceOf(TooManyActualInvocations.class);
}
diff --git a/src/test/java/org/mockitoutil/async/AsyncTesting.java b/src/test/java/org/mockitoutil/async/AsyncTesting.java
index a193eb6..3b11e10 100644
--- a/src/test/java/org/mockitoutil/async/AsyncTesting.java
+++ b/src/test/java/org/mockitoutil/async/AsyncTesting.java
@@ -10,13 +10,11 @@
* Streamlines testing async code for Mockito tests.
*
* Instances of this class are NOT thread safe (intentionally, they are not required to be thread safe)
- *
- * //TODO convert to test rule
*/
public class AsyncTesting {
//Sanity limit of threas. Increase it if justified.
- private final static int MAX_THREADS = 4;
+ private final static int MAX_THREADS = 3;
private final LinkedList<Exception> problems = new LinkedList<Exception>();
private final LinkedList<Thread> threads = new LinkedList<Thread>();
diff --git a/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidByteBuddyMockMaker.java b/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidByteBuddyMockMaker.java
index db77fb7..56ffcec 100644
--- a/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidByteBuddyMockMaker.java
+++ b/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidByteBuddyMockMaker.java
@@ -4,8 +4,8 @@
*/
package org.mockito.android.internal.creation;
-import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker;
+import org.mockito.internal.util.ConsoleMockitoLogger;
import org.mockito.internal.util.Platform;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
@@ -21,7 +21,7 @@
if (Platform.isAndroid() || Platform.isAndroidMockMakerRequired()) {
delegate = new SubclassByteBuddyMockMaker(new AndroidLoadingStrategy());
} else {
- Plugins.getMockitoLogger().log(join(
+ new ConsoleMockitoLogger().log(join(
"IMPORTANT NOTE FROM MOCKITO:",
"",
"You included the 'mockito-android' dependency in a non-Android environment.",
diff --git a/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java b/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java
index 7229438..5a66ab1 100644
--- a/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java
+++ b/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java
@@ -16,12 +16,7 @@
class AndroidLoadingStrategy implements SubclassLoader {
@Override
- public boolean isDisrespectingOpenness() {
- return false;
- }
-
- @Override
- public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean localMock) {
+ public ClassLoadingStrategy<ClassLoader> resolveStrategy(Class<?> mockedType, ClassLoader classLoader, boolean codegen) {
File target = AndroidTempFileLocator.target;
if (target == null) {
throw new MockitoException(join(
diff --git a/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java b/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java
index 34e179b..a79816c 100644
--- a/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java
+++ b/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java
@@ -23,10 +23,12 @@
} catch (Throwable ignored) {
}
if (t == null) {
- t = getCacheDirFromInstrumentationRegistry("android.support.test.InstrumentationRegistry");
- }
- if (t == null) {
- t = getCacheDirFromInstrumentationRegistry("androidx.test.InstrumentationRegistry");
+ try {
+ Class<?> clazz = Class.forName("android.support.test.InstrumentationRegistry");
+ Object context = clazz.getDeclaredMethod("getTargetContext").invoke(clazz);
+ t = (File) context.getClass().getMethod("getCacheDir").invoke(context);
+ } catch (Throwable ignored) {
+ }
}
if (t == null) {
try {
@@ -44,16 +46,6 @@
target = t;
}
- private static File getCacheDirFromInstrumentationRegistry(String className) {
- try {
- Class<?> clazz = Class.forName(className);
- Object context = clazz.getDeclaredMethod("getTargetContext").invoke(clazz);
- return (File) context.getClass().getMethod("getCacheDir").invoke(context);
- } catch (Throwable ignored) {
- }
- return null;
- }
-
private static File[] guessPath(String input) {
List<File> results = new ArrayList<File>();
for (String potential : splitPathList(input)) {
diff --git a/subprojects/inline/inline.gradle b/subprojects/inline/inline.gradle
index 22db17b..b8d2577 100644
--- a/subprojects/inline/inline.gradle
+++ b/subprojects/inline/inline.gradle
@@ -9,6 +9,5 @@
tasks.javadoc.enabled = false
-//required by the "StressTest.java" and "OneLinerStubStressTest.java"
+//required by the "StressTest.java"
test.maxHeapSize = "256m"
-retryTest.maxHeapSize = "256m"
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/OneLinerStubStressTest.java b/subprojects/inline/src/test/java/org/mockitoinline/OneLinerStubStressTest.java
deleted file mode 100644
index 44ff959..0000000
--- a/subprojects/inline/src/test/java/org/mockitoinline/OneLinerStubStressTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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 static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class OneLinerStubStressTest {
-
- public class OneLinerStubTestClass {
- public String getStuff() {
- return "A";
- }
- }
-
- private static String generateLargeString() {
- final int length = 2000000;
- final StringBuilder stringBuilder = new StringBuilder(length);
- for (int i = 0; i <= length; i++) {
- stringBuilder.append("B");
- }
- return stringBuilder.toString();
- }
-
- @Test
- public void call_a_lot_of_mocks_using_one_line_stubbing() {
- //This requires smaller heap set for the test process, see "inline.gradle"
- final String returnValue = generateLargeString();
- for (int i = 0; i < 50000; i++) {
- // make sure that mock object does not get cleaned up prematurely
- final OneLinerStubTestClass mock =
- when(mock(OneLinerStubTestClass.class).getStuff()).thenReturn(returnValue).getMock();
- assertEquals(returnValue, mock.getStuff());
- }
- }
-}
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/bugs/CyclicMockMethodArgumentMemoryLeakTest.java b/subprojects/inline/src/test/java/org/mockitoinline/bugs/CyclicMockMethodArgumentMemoryLeakTest.java
deleted file mode 100644
index 439c888..0000000
--- a/subprojects/inline/src/test/java/org/mockitoinline/bugs/CyclicMockMethodArgumentMemoryLeakTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2019 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitoinline.bugs;
-
-import org.junit.Test;
-
-import static org.mockito.Mockito.framework;
-import static org.mockito.Mockito.mock;
-
-public class CyclicMockMethodArgumentMemoryLeakTest {
- private static final int ARRAY_LENGTH = 1 << 20; // 4 MB
-
- @Test
- public void no_memory_leak_when_cyclically_calling_method_with_mocks() {
- for (int i = 0; i < 100; ++i) {
- final A a = mock(A.class);
- a.largeArray = new int[ARRAY_LENGTH];
- final B b = mock(B.class);
-
- a.accept(b);
- b.accept(a);
-
- framework().clearInlineMocks();
- }
- }
-
- private static class A {
- private int[] largeArray;
-
- void accept(B b) {}
- }
-
- private static class B {
- void accept(A a) {}
- }
-}
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/bugs/SelfSpyReferenceMemoryLeakTest.java b/subprojects/inline/src/test/java/org/mockitoinline/bugs/SelfSpyReferenceMemoryLeakTest.java
deleted file mode 100644
index f4bb55a..0000000
--- a/subprojects/inline/src/test/java/org/mockitoinline/bugs/SelfSpyReferenceMemoryLeakTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2019 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockitoinline.bugs;
-
-import org.junit.Test;
-
-import static org.mockito.Mockito.framework;
-import static org.mockito.Mockito.spy;
-
-public class SelfSpyReferenceMemoryLeakTest {
- private static final int ARRAY_LENGTH = 1 << 20; // 4 MB
-
- @Test
- public void no_memory_leak_when_spy_holds_reference_to_self() {
- for (int i = 0; i < 100; ++i) {
- final DeepRefSelfClass instance = spy(new DeepRefSelfClass());
- instance.refInstance(instance);
-
- framework().clearInlineMocks();
- }
- }
-
- private static class DeepRefSelfClass {
- private final DeepRefSelfClass[] array = new DeepRefSelfClass[1];
-
- private final int[] largeArray = new int[ARRAY_LENGTH];
-
- private void refInstance(DeepRefSelfClass instance) {
- array[0] = instance;
- }
- }
-}