instance_id
stringlengths 17
39
| repo
stringclasses 8
values | issue_id
stringlengths 14
34
| pr_id
stringlengths 14
34
| linking_methods
sequencelengths 1
3
| base_commit
stringlengths 40
40
| merge_commit
stringlengths 0
40
⌀ | hints_text
sequencelengths 0
106
| resolved_comments
sequencelengths 0
119
| created_at
unknown | labeled_as
sequencelengths 0
7
| problem_title
stringlengths 7
174
| problem_statement
stringlengths 0
55.4k
| gold_files
sequencelengths 0
10
| gold_files_postpatch
sequencelengths 1
10
| test_files
sequencelengths 0
60
| gold_patch
stringlengths 220
5.83M
| test_patch
stringlengths 386
194k
⌀ | split_random
stringclasses 3
values | split_time
stringclasses 3
values | issue_start_time
timestamp[ns] | issue_created_at
unknown | issue_by_user
stringlengths 3
21
| split_repo
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mockito/mockito/642_646 | mockito/mockito | mockito/mockito/642 | mockito/mockito/646 | [
"keyword_issue_to_pr"
] | db06504e1c1a41d4343dcf5951c6f4a1b0feb2ec | a4aa848a9b59ce46a6abb5f6e4ad551afa063648 | [
"I think we can push `2.1.0` next week since RC has been available for a little while now. Also I submitted a (random) PR to Google Guava and 850k+ tests did not fail :tada: https://github.com/google/guava/pull/2567\n",
"Shall I publish a RC tomorrow after merging #646 ?\n",
"-1 for merging #646 unless it's safe with unexpected system properties\n-1 for RC for #646. If this is the only bug / improvement, I suggest we push out 2.1.0 final, followed by 2.1.1 that contains the improvement. While I like the improvement, it does not strike me as something that needs another release candidate.\n\nGiven that we don't have more feedback to investigate, I suggest to set the final release to Monday. Good day to release :)\n",
"I think we should merge #646 before releasing a final version. We already got several reported issues that were caused by old Java versions and I expect that quite a lot of people might not have updated their JDK in years.\n\nOtherthan that, I agree that we do not need a release candidate for this.\n",
"Oh oops I indeed did not mean RC, but the final release :p\n\nSo lets merge #646 when the issue is fixed and then publish `2.1.0` on monday :tada:\n",
"I will tweak the code before the end of the week-end, I was short on time these past two week.\n",
"The final version needs to be exactly the same as the last RC. That's the idea of \"release candidates\" :)\n\nEssentially, the options are:\n\na) publish 2.1.0 final now, include the improvement in 2.1.1 (no rc needed, after 2.1.0 is out we won't be releasing candidates for 2.x versions)\nb) wait for fixes in the improvement, merge it, publish 2.1.0-rc-2, wait some time (for example, a day), publish 2.1.0 final\n\n@raphw says it's important to include the fix, so let's do option b)\n",
"It is not strictly required for 1 very small bug fix to create a whole new RC with the accompanying waiting time. Other teams have also published their latest RC with just a couple of bug fixes immediately as final release, so I think we can safely release 2.1.0 with #646 on monday.\n",
"The fact that other teams do it does not mean that it's right :)\n\nWe want to be in the position that we can always say that: \"the RC is exactly the final release\". This helps convincing teams to use RCs.\n\nOf course nothing can stop you from publishing final with any number of fixes you want. However, it is simply the matter of good practice to follow version conventions and avoid making exceptions for no good reason.\n\nPublishing final version with patches on top of last RC is sloppy. The reason one might want to do it is when the release process is manual / hard. It's not the case for Mockito, where entire pipeline is automated!!! :D\n",
"I agree with you that we should **not** push this to the final release but I really think that we should merge #646 before going final. Therefore, I suggest a second release candidate instead of a release on Monday. Let's please do this right. Isn't this what RCs are for? Doing so, we can also merge #648.\n\nThe problem addressed by #646 was reported at least 6 times. Many developers do not even mean to run old Java versions but have some outdated JDK bundled with their IDE. This means that tests run using Maven but not in, for example, Eclipse, what is difficult to debug and will most likely cause frustration among some early adopters of Mockito 2. In the end, I have spent some hours myself to investigate reported issues of this origin. If we had thought of something like @bric3's solution earlier, I am sure we would have done this right away and I was very happy to see this PR. I am also sure this automatic debugging help will free us some time once Mockito 2 hits the mainstream and more people run into this problem.\n\nAs for #648, I think this can make quite a difference in how the Mockito 2 release is perceived in the public. A lot of people have already implemented their own stream-aware \"smart null\" answers or Java 8-adapters - thanks to the great Mockito API making this so easy - and most of our other changes are internal clean-ups and and do not really change user experience. With adding support for mocking final types and methods, we are delivering something new and exciting, something that people will speak about. Without such a feature, we are risking to suffer the Java 7-phenomenon where very few people bothered to update despite the significant changes made in the OpenJDK. In the end, to a user updating is a risk and additional work; so why bother if there is nothing in for you? In this perspective, Java 8 was an entirely different story. And _true_ final mocks do not really exist in the Java-space yet, in this respect we have built something that was never done before! I am sure people will want to try this feature out what hopefully motivates more folks to an upgrade.\n\nGiven that we have 2 PRs that only need to be merged with features that are both helping migration and adding some fuzz about the upcoming release, I am strictly against going for a final version on Monday. Let's pick this low hanging fruit. Also, from a marketing perspective, releasing Mockito 2.1 on Monday and Mockito 2.2-RC on Tuesday, I do not think this would sell well.\n\nI wish I had time to do all this before the RC was published but I was too busy during JavaZone and I had to catch up some sleep before getting everything I wanted ready. But now we have waited so long, let's delay the final version for just a little bit more. Isn't anticipation the greatest joy anyways? \n",
"> The problem addressed by #646 was reported at least 6 times. \n\nI totally agree. Let's make java8 warning a part of 2.1.0. All I want is to follow good practices of versioning and RC.\n\n> releasing Mockito 2.1 on Monday and Mockito 2.2-RC on Tuesday, I do not think this would sell well.\n\nWe don't publish RCs for _compatible_ versions. We don't plan RCs for 2.2, 2.3, 2.12.32, they are compatible versions and don't need RCs.\n\n> And true final mocks do not really exist in the Java-space yet, in this respect we have built something that was never done before!\n\nLOVE IT!!!!\n\n> As for #648, I think this can make quite a difference in how the Mockito 2 release is perceived in the public.\n\nThat's really cool :) Caveats:\n- it's late\n- the feature is not ready (assuming the code is ok, documentation? release notes?)\n- the feature is a breaking change due to extra dependencies\n\nI'm not sure why you push so hard to include it in 2.1.0. You can spend more time on this feature, make it great, compatible, well documented, push it with 2.2.0 few weeks from now, include buzz, promo, etc. You will achieve **exactly** the same results community-wise. Actually, I think it is even better to spread good features over time to demonstrate that Mockito continually improves. Community will be adopting Mockito 2 slowly, it will take years. Some projects will stay on 1.10 forever :)\n\nI'm curious:\n- how much time is needed to make the feature is ready?\n- how much time is needed to make the feature backwards compatible?\n\n@raphw, I'm very happy you work on this and I totally admire your passion to improve Mockito. Let's build a plan and make it work. This feature is too late for 2.1.0. Last minute, unannounced big features, in the RC phase - this is just not a good idea. We've been planning the release for months, inline mocks never appeared on the checklists.\n\nLong story short, we don't need to block 2.1.0 to make this available in 2.x and make it an awesome, neat feature!!! :)\n",
"As I said before, the feature is ready: it passes all of Mockito's unit tests when it is activated and we even added this to the Travis build to be constantly verified. At the same time, the feature guarantees to not break anything.\n\nI want to merge this now as there is nothing left to do, this is why the feature is a PR ready to be merged and not a private branch. If it is not included in 2.1, I can live with this but I find this a missed opportunity. From my perspective, this feature is good to go and I do not plan to spend more time on it, even if it is not included in 2.1. I can only improve it once people started using it and give me feedback.\n\nI already explained why I think it would be better to include it in 2.1 from a marketing perspective. Other than that, the feature can be added in 2.2 but in the meantime, it will just sit there with nothing changing; worst case some rebasements onto head.\n\nEffectively, what you suggests means therefore that we release 2.1.Final now and 2.2.Final in a few weeks (?). 2.2.Final will be the exact same jar as 2.1.Final would be with this feature merged. I simply do not see how this would improve anything.\n",
"Usually following process is is good, but some time following guts is nice too. I second @raphw to include the mockmaker, it's opt-in. \n\nI agree final mock never appeared on the radar here, but the topic was discussed and investigated more than a year ago, by me and especially Rafael who, in the end, achieved this alone. That's a fantastic work @raphw !!!\n\nIncluding this is an opportunity. We already included incubating API before, I don't see why we shouldn't include it in 2.1.0 (and as such an 2.1.0-RC.x ) as well.\n",
"Thank you guys challenging me and the good practices. We should be challenging one another and keep growing as technical leaders. Discussions like those are the core of collaborative software engineering. Let's enjoy them and never feel discouraged! I find you guys the best crowd I worked with in a while, and @raphw, you did pull off a feature nobody yet did in the history of mocking :)\n\nAbout the feature: it's too late to include it in the 2.1.0 final. It's great work and it must be included in Mockito. This feature is incompatible in the current form because of new dependencies. \n\nI will continue pushing Mockito team to follow decent engineering practices:\n- when RC is published, subsequent RCs are triggered for bugfixes required to get the release out\n- subsequent RCs are not used to ship new features, especially when they include breaking changes\n- no sudden big changes, midnight before major version release ;)\n- favoring incremental improvements, for better stability\n\nMockito is the product that has 2M users, it deserves thoughtful and rigorous following of decent engineering practices. Of course exceptions are necessary, but for good reasons!\n\n> Effectively, what you suggests means therefore that we release 2.1.Final now and 2.2.Final in a few weeks (?). 2.2.Final will be the exact same jar as 2.1.Final would be with this feature merged. I simply do not see how this would improve anything.\n\nWe can merge and publish version 2.2.0 even next day after the release, so long the feature is ready & compatible. I haven't reviewed the PR thoroughly yet, anyone else did? Does it have user-facing documentation (e.g. how can I opt-in for the feature, what can I expect?). Is it utterly and completely safe for default behavior?\n",
"> Is it utterly and completely safe for default behavior?\n\n**YES**, it uses the plugin loader for that, people that want to try final class mocks will have to explicitly make a file in the folder `mockito-extensions`.\n\n> Does it have user-facing documentation (e.g. how can I opt-in for the feature, what can I expect?)\n\nSee [`Mockito` class](https://github.com/mockito/mockito/pull/648/files#diff-ddbc0d47e06a589778a6efe24c5d71d3R1220)\n\n> I haven't reviewed the PR thoroughly yet, anyone else did?\n\n**YES**, I did\n\n> - subsequent RCs are not used to ship new features, especially when they include breaking changes\n\nAdding a dependency is not a breaking change. However for other reasons I think mockito should avoid relying on that dependency. **EDIT :** manually shadowed.\n\n> - no sudden big changes, midnight before major version release ;)\n\nFor such a change, actually an opt-in feature, I think we should release another release candidate. (We will have another RC anyway due to the java version warning.)\n",
"@bric3, shouting not needed :) Thank you for the answers! It's really helpful.\n\nThe documentation looks nice, I'll make some edits in the branch.\n\nAdding new dependency is backwards incompatible. I will write later why :)\n\nI'm +1 to including it in RC because:\n- I'm confident about the quality and documentation\n- It's an opt-in feature\n- New dependency is shadowed\n- The other new dependency (agent) is a part of ByteBuddy, so I'm willing to compromise the backwards compatibility of the RCs this time.\n\nI will write a comment to PR with few things I want to get done before it's merged.\n\nGreat work, thank you!\n",
"Adding new dependency is a breaking change: https://www.linkedin.com/pulse/sofware-craftsmanship-adding-new-dependency-breaking-change-faber :)\n",
"I don't think I fully agree with your article. In very technical terms, yes it is a breaking change. However, claiming that it breaks builds is imo a stretch in this particular case. The dependency is very small, has almost no new versions and looking at the release schedule, only 3 minor versions were available longer than a week. Therefore the likelihood of having a dependency conflict (even in minor range) is close to zero (if not zero). Therefore I think it is an exaggeration to claim it is something to worry about.\n\nI would also not like to point to your thoughtpiece in the documentation. I do acknowledge your point of view, but I simply do not share it. Therefore I would like to refrain from putting it in the official documentation, since that would indicate it is shared by the whole Mockito dev team.\n",
"The article does not discuss the probability of failure. It simply describes facts. Change that can break clients is by definition \"incompatible\". The team can still decide to ship such change, as we are doing :)\n\nI respect your POV. Write your own article!\n\nI intend to link to the article. However, I would love to link to your article, too. Mockito needs more traction and publicity, strong opinions and public discussions is good for us all.\n\nI'm serious, write the article!\n",
"@szczepiq \nI don't see a problem of adding a new dependency since the major version of mockito changed. Mockito v1.x has dependencies to hamcrest and objenesis whereas v2.x relies one byte-buddy and objenesis, so an other dependency don't make it worse. \n\nThe problem you describe in your article is IMO not the added dependency that breaks the build, that can also happen if a library updates to a new version of a dependency . I think the root cause is the fact that you client relies on library (read mockito) version that has no final/GA release. If they use non final version they should be aware of changes. For the same reason many teams have a policy that only allows to use final releases. \n",
"I don't agree with these facts :\n\n> Adding new dependency is a breaking change\n> - New dependency is not present in corporate repo of one of your clients. His build breaks.\n\nThis argument completely disreagard dependency management tool like gradle or maven. Mockito is only distributed on bintray and maven central that are exactly made for getting those transitive dependencies.\n\n> - New dependency is not allowed in corporate repo of your client (for example, due to poor reputation or security concerns). The client cannot use the new version.\n\nWith such policies, the importing library update itself is subject to these restrictions, and therefore updates are not allowed anyway until reviews approves changes of the importing library. This will happen regardless of the dependency being an external jar or being shaded.\n\ne.g. license concerns won't be elimitated if the classes are just shaded.\n\n> - New dependency is already declared by the client, but with different, incompatible version. Conflict resolution picks up later version causing failures at runtime.\n> \n> Updating dependency could be a breaking change\n\nThis is indeed true and this is the only valid argument to me. Anyway the scope of this argument is limited because upgrading the importing library too can be in itself a breaking change (according to semver), e.g. mockito 2.x is incompatible with mockito 1.x.\nThis is indeed a problem with minor versions.\n\nUpdating a dependency is indeed something that could be breaking, but so could be the importing library.\n",
"@bric3, you're right, my first example in the use case is invalid. Thanks for pointing this out, I'll update the article.\n\n@bric3, @ChristianSchwarz - you're right about the fact that major versions can carry breaking changes. However, including incompatible changes in subsequent release candidate is a poor engineering practice.\n\nRelease candidate by definition, is a software that is \"ready to release\" unless significant bugs are discovered. This means that N+1 release candidate should not have new features, big changes, and most importantly, incompatible changes. Consumers of release candidates need to be able to rely on this rule.\n\nThoughtful exceptions can always be made by the team, as we are doing :) I'll keep pushing for decent versioning practices. Thanks guys for feedback!!!\n",
"@szczepiq not there's still two items in #123, I think they can be safely removed, as we won't remove the serialVersionUid, and unincubated API have either _hatched out_ or stil incubating.\n\nAlso on mockito javadoc there's link that point to an old website (like https://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring), I think we should only point to mockito wiki or github repo, not external website that can disappear anytime.\n",
"Done. \n\n> I think we should only point to mockito wiki or github repo\n\n+1\n",
"I think we can publish on monday. The release seems very stable and we have yet another successful upgrade, this time at RxJava: https://github.com/ReactiveX/RxJava/pull/4636\n",
"+1. THANKS for great work :DDDD Pleasure doing projects together!!!\n\nGreat idea to migrate RxJava!\n",
"Published, w00h00. Upgrade today :tada: \n"
] | [
"Why would this be abstract? It has a private constructor anyways.\n",
"To keep it consistent, let's make these constant Strings too.\n",
"Space after `if`?\n",
"I would reverse this, to make the conditional equivalent to the name of the method. Very small nit though, but I had to think about it for a second :smile: \n",
"It seems that these lines are untested. Are we able to come up with a test for this? E.g. why would we reorder these values.\n",
"replace 'visible' with 'non-private'? Users might not know what 'visible' is :)\n",
"AFAIR, StringJoiner always adds next line for each String argument. This means that if java is < 45, there will be extra EOLs. Perhaps it's fine, just wanted FYI.\n",
"This is a fantastic improvement, very Mockito-style :D We always strive to make the exception messages better, even a notch better. In the long run all those small improvements create a compound effect. We'll have fantastic error handling, crisp and clear exception messages and happy users!!!\n",
"FYI: Java 9 changes the standard version String and possibly other standard system properties. Let's make sure it works on Java 9 :)\n",
"Let's make sure this is always safe, regardless of the content of the system properties. Those properties are mutable AFAIK, and/or might change/be different with future versions of java or perhaps even jvm/jdk vendor.\n\nOtherwise, love this PR :)\n",
"Yes I wanted an extra empty line before platform information (if the runtime is a java 8 version below update 45)\n",
"ok\n",
"At the moment this shouldn't be a problem. the parsing targets Java 8 runtime\n\nhttp://openjdk.java.net/jeps/223\n",
"Because they are wrong in the message ;) \nThe type to mock is not the class that the mockmaker created ;)\n",
"yes i forgot that, I was a bit in hurry for this PR, and wanted to push on the remote ;)\nThis was still a work in progress ;)\n",
"It's a usual practice to disallow instantiation.\n",
"Yes true, but that is what the private constructor guarantees too right? But leaving it in is fine too :)\n"
] | "2016-09-22T08:33:22Z" | [
"epic"
] | Release 2.1.0 final | The purpose of this ticket is to collect all actions and requirements for getting 2.1.0 final. Let's not wait too long :)
- [x] investigate #638
- [x] identify opportunities to promo the RC and get more feedback
- [x] decide how long do we wait for feedback before publishing final version
- [x] @TimvdLippe review the #648
- [x] #648 - include more info the javadoc, e.g. direction of the feature, what we expect from the user, inform it is incubating, etc
- [x] @szczepiq review the #648
- update the release notes re #648
- [x] inform about the new feature (incubating, motivating, future direction)
- [x] publish another RC and spread the word
| [
"src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java",
"src/main/java/org/mockito/internal/util/Platform.java"
] | [
"src/test/java/org/mockito/internal/util/PlatformTest.java"
] | diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
index 907ebd0276..9d165f6899 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
@@ -1,19 +1,18 @@
package org.mockito.internal.creation.bytebuddy;
+import static org.mockito.internal.util.StringJoiner.join;
+import java.lang.reflect.Modifier;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.MockAccess;
import org.mockito.internal.creation.instance.Instantiator;
+import org.mockito.internal.util.Platform;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
-import java.lang.reflect.Modifier;
-
-import static org.mockito.internal.util.StringJoiner.join;
-
public class ByteBuddyMockMaker implements MockMaker {
private final CachingMockBytecodeGenerator cachingMockBytecodeGenerator;
@@ -37,8 +36,8 @@ public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
} catch (ClassCastException cce) {
throw new MockitoException(join(
"ClassCastException occurred while creating the mockito mock :",
- " class to mock : " + describeClass(mockedProxyType),
- " created class : " + describeClass(settings.getTypeToMock()),
+ " class to mock : " + describeClass(settings.getTypeToMock()),
+ " created class : " + describeClass(mockedProxyType),
" proxy instance class : " + describeClass(mockInstance),
" instance creation by : " + instantiator.getClass().getSimpleName(),
"",
@@ -51,7 +50,11 @@ public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
}
<T> Class<T> createProxyClass(MockFeatures<T> mockFeatures) {
- return cachingMockBytecodeGenerator.get(mockFeatures);
+ try {
+ return cachingMockBytecodeGenerator.get(mockFeatures);
+ } catch (Exception bytecodeGenerationFailed) {
+ throw prettifyFailure(mockFeatures, bytecodeGenerationFailed);
+ }
}
@@ -71,6 +74,27 @@ private <T> T ensureMockIsAssignableToMockedType(MockCreationSettings<T> setting
return typeToMock.cast(mock);
}
+ private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) {
+ if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) {
+ throw new MockitoException(join(
+ "Mockito cannot mock this class: " + mockFeatures.mockedType + ".",
+ "Most likely it is a private class that is not visible by Mockito",
+ ""
+ ), generationFailed);
+ }
+ throw new MockitoException(join(
+ "Mockito cannot mock this class: " + mockFeatures.mockedType,
+ "",
+ "Mockito can only non-private & non-final classes.",
+ "If you're not sure why you're getting this error, please report to the mailing list.",
+ "",
+ Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : "",
+ Platform.describe(),
+ "",
+ "Underlying exception : " + generationFailed
+ ), generationFailed);
+ }
+
private static String describeClass(Class<?> type) {
return type == null ? "null" : "'" + type.getCanonicalName() + "', loaded by classloader : '" + type.getClassLoader() + "'";
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java
index 1093c37c87..461dec6168 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java
@@ -1,12 +1,9 @@
package org.mockito.internal.creation.bytebuddy;
-import org.mockito.exceptions.base.MockitoException;
-
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
-import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
@@ -15,8 +12,6 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import static org.mockito.internal.util.StringJoiner.join;
-
class CachingMockBytecodeGenerator extends ReferenceQueue<ClassLoader> {
private static final ClassLoader BOOT_LOADER = new URLClassLoader(new URL[0], null);
@@ -86,7 +81,7 @@ Class<?> getOrGenerateMockClass(MockFeatures<?> features) {
synchronized (features.mockedType) {
generatedMockClass = getMockClass(mockKey);
if(generatedMockClass == null) {
- generatedMockClass = generate(features);
+ generatedMockClass = generator.generateMockClass(features);
generatedClassCache.put(mockKey, weak ? new WeakReference<Class<?>>(generatedMockClass) : new SoftReference<Class<?>>(generatedMockClass));
}
}
@@ -94,33 +89,6 @@ Class<?> getOrGenerateMockClass(MockFeatures<?> features) {
return generatedMockClass;
}
- private <T> Class<? extends T> generate(MockFeatures<T> mockFeatures) {
- try {
- return generator.generateMockClass(mockFeatures);
- } catch (Exception bytecodeGenerationFailed) {
- throw prettifyFailure(mockFeatures, bytecodeGenerationFailed);
- }
- }
-
- private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) {
- if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) {
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.mockedType + ".",
- "Most likely it is a private class that is not visible by Mockito",
- ""
- ), generationFailed);
- }
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.mockedType,
- "",
- "Mockito can only mock visible & non-final classes.",
- "If you're not sure why you're getting this error, please report to the mailing list.",
- "",
- "Underlying exception : " + generationFailed),
- generationFailed
- );
- }
-
// should be stored as a weak reference
private static class MockKey<T> {
private final String mockedType;
diff --git a/src/main/java/org/mockito/internal/util/Platform.java b/src/main/java/org/mockito/internal/util/Platform.java
new file mode 100644
index 0000000000..c899b20dab
--- /dev/null
+++ b/src/main/java/org/mockito/internal/util/Platform.java
@@ -0,0 +1,64 @@
+package org.mockito.internal.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public abstract class Platform {
+
+ private static final Pattern JAVA_8_RELEASE_VERSION_SCHEME = Pattern.compile("1\\.8\\.0_(\\d+)(?:-ea)?(?:-b\\d+)?");
+ private static final Pattern JAVA_8_DEV_VERSION_SCHEME = Pattern.compile("1\\.8\\.0b\\d+_u(\\d+)");
+ public static final String JAVA_VERSION = System.getProperty("java.specification.version");
+ public static final String JVM_VERSION = System.getProperty("java.runtime.version");
+ public static final String JVM_VENDOR = System.getProperty("java.vm.vendor");
+ public static final String JVM_VENDOR_VERSION = System.getProperty("java.vm.version");
+ public static final String JVM_NAME = System.getProperty("java.vm.name");
+ public static final String JVM_INFO = System.getProperty("java.vm.info");
+ public static final String OS_NAME = System.getProperty("os.name");
+ public static final String OS_VERSION = System.getProperty("os.version");
+
+ private Platform() {}
+
+ public static String describe() {
+ return String.format("Java : %s\n" +
+ "JVM vendor name : %s\n" +
+ "JVM vendor version : %s\n" +
+ "JVM name : %s\n" +
+ "JVM version : %s\n" +
+ "JVM info : %s\n" +
+ "OS name : %s\n" +
+ "OS version : %s\n",
+ JAVA_VERSION,
+ JVM_VENDOR,
+ JVM_VENDOR_VERSION,
+ JVM_NAME,
+ JVM_VERSION,
+ JVM_INFO,
+ OS_NAME,
+ OS_VERSION);
+ }
+
+ public static boolean isJava8BelowUpdate45() {
+ return isJava8BelowUpdate45(JVM_VERSION);
+ }
+
+ static boolean isJava8BelowUpdate45(String jvmVersion) {
+ Matcher matcher = JAVA_8_RELEASE_VERSION_SCHEME.matcher(jvmVersion);
+ if (matcher.matches()) {
+ int update = Integer.parseInt(matcher.group(1));
+ return update < 45;
+ }
+
+ matcher = JAVA_8_DEV_VERSION_SCHEME.matcher(jvmVersion);
+ if (matcher.matches()) {
+ int update = Integer.parseInt(matcher.group(1));
+ return update < 45;
+ }
+
+ matcher = Pattern.compile("1\\.8\\.0-b\\d+").matcher(jvmVersion);
+ if (matcher.matches()) {
+ return true;
+ }
+
+ return false;
+ }
+}
| diff --git a/src/test/java/org/mockito/internal/util/PlatformTest.java b/src/test/java/org/mockito/internal/util/PlatformTest.java
new file mode 100644
index 0000000000..f146666620
--- /dev/null
+++ b/src/test/java/org/mockito/internal/util/PlatformTest.java
@@ -0,0 +1,98 @@
+package org.mockito.internal.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.Test;
+
+public class PlatformTest {
+
+ @Test
+ public void const_are_initialized_from_system_properties() {
+ assertThat(Platform.JVM_VERSION).isEqualTo(System.getProperty("java.runtime.version"));
+ assertThat(Platform.JVM_INFO).isEqualTo(System.getProperty("java.vm.info"));
+ assertThat(Platform.JVM_NAME).isEqualTo(System.getProperty("java.vm.name"));
+ assertThat(Platform.JVM_VENDOR).isEqualTo(System.getProperty("java.vm.vendor"));
+ assertThat(Platform.JVM_VENDOR_VERSION).isEqualTo(System.getProperty("java.vm.version"));
+ }
+
+ @Test
+ public void should_parse_open_jdk_string() {
+ // Given
+ // Sources :
+ // - http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
+ // - http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html
+ // - http://www.oracle.com/technetwork/java/javase/jdk8-naming-2157130.html
+ // - http://stackoverflow.com/questions/35844985/how-do-we-get-sr-and-fp-of-ibm-jre-using-java
+ // - http://www.ibm.com/support/knowledgecenter/SSYKE2_6.0.0/com.ibm.java.doc.user.win32.60/user/java_version_check.html
+ Map<String, Boolean> versions = new HashMap<String, Boolean>() {{
+ put("1.8.0_92-b14", false);
+ put("1.8.0-b24", true);
+ put("1.8.0_5", true);
+ put("1.8.0b5_u44", true);
+ put("1.8.0b5_u92", false);
+ put("1.7.0_4", false);
+ put("1.4.0_03-b04", false);
+ put("1.4.0_03-ea-b01", false);
+ put("pxi3270_27sr4-20160303_03 (SR4)", false);
+ put("pwi3260sr11-20120412_01 (SR11)", false);
+ }};
+
+ assertPlatformParsesCorrectlyVariousVersionScheme(versions);
+ }
+
+ @Test
+ public void should_parse_open_jdk9_string() {
+ // The tested method targets Java 8 but should be able to parse other Java version numbers including Java 9
+
+ // Given
+ // Sources :
+ // - http://openjdk.java.net/jeps/223 (Java 9)
+ //
+ // System Property Existing Proposed
+ // ------------------------------- ------------ --------
+ // Early Access
+ // java.runtime.version 1.9.0-ea-b73 9-ea+73
+ // java.vm.version 1.9.0-ea-b73 9-ea+73
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ // Major (GA)
+ // java.version 1.9.0 9
+ // java.runtime.version 1.9.0-b100 9+100
+ // java.vm.version 1.9.0-b100 9+100
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ // Minor #1 (GA)
+ // java.version 1.9.0_20 9.1.2
+ // java.runtime.version 1.9.0_20-b62 9.1.2+62
+ // java.vm.version 1.9.0_20-b62 9.1.2+62
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ // Security #1 (GA)
+ // java.version 1.9.0_5 9.0.1
+ // java.runtime.version 1.9.0_5-b20 9.0.1+20
+ // java.vm.version 1.9.0_5-b20 9.0.1+20
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ Map<String, Boolean> versions = new HashMap<String, Boolean>() {{
+ put("9-ea+73", false);
+ put("9+100", false);
+ put("9.1.2+62", false);
+ put("9.0.1+20", false);
+ }};
+
+ assertPlatformParsesCorrectlyVariousVersionScheme(versions);
+ }
+
+
+ private void assertPlatformParsesCorrectlyVariousVersionScheme(Map<String, Boolean> versions) {
+ for (Map.Entry<String, Boolean> version : versions.entrySet()) {
+ assertThat(Platform.isJava8BelowUpdate45(version.getKey())).describedAs(version.getKey())
+ .isEqualTo(version.getValue());
+ }
+ }
+}
| train | train | 2016-09-24T23:12:43 | "2016-09-17T15:57:32Z" | mockitoguy | train |
mockito/mockito/640_646 | mockito/mockito | mockito/mockito/640 | mockito/mockito/646 | [
"keyword_pr_to_issue"
] | db06504e1c1a41d4343dcf5951c6f4a1b0feb2ec | a4aa848a9b59ce46a6abb5f6e4ad551afa063648 | [
"Can be closed...\n"
] | [
"Why would this be abstract? It has a private constructor anyways.\n",
"To keep it consistent, let's make these constant Strings too.\n",
"Space after `if`?\n",
"I would reverse this, to make the conditional equivalent to the name of the method. Very small nit though, but I had to think about it for a second :smile: \n",
"It seems that these lines are untested. Are we able to come up with a test for this? E.g. why would we reorder these values.\n",
"replace 'visible' with 'non-private'? Users might not know what 'visible' is :)\n",
"AFAIR, StringJoiner always adds next line for each String argument. This means that if java is < 45, there will be extra EOLs. Perhaps it's fine, just wanted FYI.\n",
"This is a fantastic improvement, very Mockito-style :D We always strive to make the exception messages better, even a notch better. In the long run all those small improvements create a compound effect. We'll have fantastic error handling, crisp and clear exception messages and happy users!!!\n",
"FYI: Java 9 changes the standard version String and possibly other standard system properties. Let's make sure it works on Java 9 :)\n",
"Let's make sure this is always safe, regardless of the content of the system properties. Those properties are mutable AFAIK, and/or might change/be different with future versions of java or perhaps even jvm/jdk vendor.\n\nOtherwise, love this PR :)\n",
"Yes I wanted an extra empty line before platform information (if the runtime is a java 8 version below update 45)\n",
"ok\n",
"At the moment this shouldn't be a problem. the parsing targets Java 8 runtime\n\nhttp://openjdk.java.net/jeps/223\n",
"Because they are wrong in the message ;) \nThe type to mock is not the class that the mockmaker created ;)\n",
"yes i forgot that, I was a bit in hurry for this PR, and wanted to push on the remote ;)\nThis was still a work in progress ;)\n",
"It's a usual practice to disallow instantiation.\n",
"Yes true, but that is what the private constructor guarantees too right? But leaving it in is fine too :)\n"
] | "2016-09-22T08:33:22Z" | [
"enhancement"
] | Improve exception message to hint at upgrading java minor version to latest | Driven by #636
| [
"src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java",
"src/main/java/org/mockito/internal/util/Platform.java"
] | [
"src/test/java/org/mockito/internal/util/PlatformTest.java"
] | diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
index 907ebd0276..9d165f6899 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/ByteBuddyMockMaker.java
@@ -1,19 +1,18 @@
package org.mockito.internal.creation.bytebuddy;
+import static org.mockito.internal.util.StringJoiner.join;
+import java.lang.reflect.Modifier;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.InternalMockHandler;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.MockAccess;
import org.mockito.internal.creation.instance.Instantiator;
+import org.mockito.internal.util.Platform;
import org.mockito.invocation.MockHandler;
import org.mockito.mock.MockCreationSettings;
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
-import java.lang.reflect.Modifier;
-
-import static org.mockito.internal.util.StringJoiner.join;
-
public class ByteBuddyMockMaker implements MockMaker {
private final CachingMockBytecodeGenerator cachingMockBytecodeGenerator;
@@ -37,8 +36,8 @@ public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
} catch (ClassCastException cce) {
throw new MockitoException(join(
"ClassCastException occurred while creating the mockito mock :",
- " class to mock : " + describeClass(mockedProxyType),
- " created class : " + describeClass(settings.getTypeToMock()),
+ " class to mock : " + describeClass(settings.getTypeToMock()),
+ " created class : " + describeClass(mockedProxyType),
" proxy instance class : " + describeClass(mockInstance),
" instance creation by : " + instantiator.getClass().getSimpleName(),
"",
@@ -51,7 +50,11 @@ public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
}
<T> Class<T> createProxyClass(MockFeatures<T> mockFeatures) {
- return cachingMockBytecodeGenerator.get(mockFeatures);
+ try {
+ return cachingMockBytecodeGenerator.get(mockFeatures);
+ } catch (Exception bytecodeGenerationFailed) {
+ throw prettifyFailure(mockFeatures, bytecodeGenerationFailed);
+ }
}
@@ -71,6 +74,27 @@ private <T> T ensureMockIsAssignableToMockedType(MockCreationSettings<T> setting
return typeToMock.cast(mock);
}
+ private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) {
+ if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) {
+ throw new MockitoException(join(
+ "Mockito cannot mock this class: " + mockFeatures.mockedType + ".",
+ "Most likely it is a private class that is not visible by Mockito",
+ ""
+ ), generationFailed);
+ }
+ throw new MockitoException(join(
+ "Mockito cannot mock this class: " + mockFeatures.mockedType,
+ "",
+ "Mockito can only non-private & non-final classes.",
+ "If you're not sure why you're getting this error, please report to the mailing list.",
+ "",
+ Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : "",
+ Platform.describe(),
+ "",
+ "Underlying exception : " + generationFailed
+ ), generationFailed);
+ }
+
private static String describeClass(Class<?> type) {
return type == null ? "null" : "'" + type.getCanonicalName() + "', loaded by classloader : '" + type.getClassLoader() + "'";
}
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java
index 1093c37c87..461dec6168 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/CachingMockBytecodeGenerator.java
@@ -1,12 +1,9 @@
package org.mockito.internal.creation.bytebuddy;
-import org.mockito.exceptions.base.MockitoException;
-
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
-import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
@@ -15,8 +12,6 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import static org.mockito.internal.util.StringJoiner.join;
-
class CachingMockBytecodeGenerator extends ReferenceQueue<ClassLoader> {
private static final ClassLoader BOOT_LOADER = new URLClassLoader(new URL[0], null);
@@ -86,7 +81,7 @@ Class<?> getOrGenerateMockClass(MockFeatures<?> features) {
synchronized (features.mockedType) {
generatedMockClass = getMockClass(mockKey);
if(generatedMockClass == null) {
- generatedMockClass = generate(features);
+ generatedMockClass = generator.generateMockClass(features);
generatedClassCache.put(mockKey, weak ? new WeakReference<Class<?>>(generatedMockClass) : new SoftReference<Class<?>>(generatedMockClass));
}
}
@@ -94,33 +89,6 @@ Class<?> getOrGenerateMockClass(MockFeatures<?> features) {
return generatedMockClass;
}
- private <T> Class<? extends T> generate(MockFeatures<T> mockFeatures) {
- try {
- return generator.generateMockClass(mockFeatures);
- } catch (Exception bytecodeGenerationFailed) {
- throw prettifyFailure(mockFeatures, bytecodeGenerationFailed);
- }
- }
-
- private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) {
- if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) {
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.mockedType + ".",
- "Most likely it is a private class that is not visible by Mockito",
- ""
- ), generationFailed);
- }
- throw new MockitoException(join(
- "Mockito cannot mock this class: " + mockFeatures.mockedType,
- "",
- "Mockito can only mock visible & non-final classes.",
- "If you're not sure why you're getting this error, please report to the mailing list.",
- "",
- "Underlying exception : " + generationFailed),
- generationFailed
- );
- }
-
// should be stored as a weak reference
private static class MockKey<T> {
private final String mockedType;
diff --git a/src/main/java/org/mockito/internal/util/Platform.java b/src/main/java/org/mockito/internal/util/Platform.java
new file mode 100644
index 0000000000..c899b20dab
--- /dev/null
+++ b/src/main/java/org/mockito/internal/util/Platform.java
@@ -0,0 +1,64 @@
+package org.mockito.internal.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public abstract class Platform {
+
+ private static final Pattern JAVA_8_RELEASE_VERSION_SCHEME = Pattern.compile("1\\.8\\.0_(\\d+)(?:-ea)?(?:-b\\d+)?");
+ private static final Pattern JAVA_8_DEV_VERSION_SCHEME = Pattern.compile("1\\.8\\.0b\\d+_u(\\d+)");
+ public static final String JAVA_VERSION = System.getProperty("java.specification.version");
+ public static final String JVM_VERSION = System.getProperty("java.runtime.version");
+ public static final String JVM_VENDOR = System.getProperty("java.vm.vendor");
+ public static final String JVM_VENDOR_VERSION = System.getProperty("java.vm.version");
+ public static final String JVM_NAME = System.getProperty("java.vm.name");
+ public static final String JVM_INFO = System.getProperty("java.vm.info");
+ public static final String OS_NAME = System.getProperty("os.name");
+ public static final String OS_VERSION = System.getProperty("os.version");
+
+ private Platform() {}
+
+ public static String describe() {
+ return String.format("Java : %s\n" +
+ "JVM vendor name : %s\n" +
+ "JVM vendor version : %s\n" +
+ "JVM name : %s\n" +
+ "JVM version : %s\n" +
+ "JVM info : %s\n" +
+ "OS name : %s\n" +
+ "OS version : %s\n",
+ JAVA_VERSION,
+ JVM_VENDOR,
+ JVM_VENDOR_VERSION,
+ JVM_NAME,
+ JVM_VERSION,
+ JVM_INFO,
+ OS_NAME,
+ OS_VERSION);
+ }
+
+ public static boolean isJava8BelowUpdate45() {
+ return isJava8BelowUpdate45(JVM_VERSION);
+ }
+
+ static boolean isJava8BelowUpdate45(String jvmVersion) {
+ Matcher matcher = JAVA_8_RELEASE_VERSION_SCHEME.matcher(jvmVersion);
+ if (matcher.matches()) {
+ int update = Integer.parseInt(matcher.group(1));
+ return update < 45;
+ }
+
+ matcher = JAVA_8_DEV_VERSION_SCHEME.matcher(jvmVersion);
+ if (matcher.matches()) {
+ int update = Integer.parseInt(matcher.group(1));
+ return update < 45;
+ }
+
+ matcher = Pattern.compile("1\\.8\\.0-b\\d+").matcher(jvmVersion);
+ if (matcher.matches()) {
+ return true;
+ }
+
+ return false;
+ }
+}
| diff --git a/src/test/java/org/mockito/internal/util/PlatformTest.java b/src/test/java/org/mockito/internal/util/PlatformTest.java
new file mode 100644
index 0000000000..f146666620
--- /dev/null
+++ b/src/test/java/org/mockito/internal/util/PlatformTest.java
@@ -0,0 +1,98 @@
+package org.mockito.internal.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.Test;
+
+public class PlatformTest {
+
+ @Test
+ public void const_are_initialized_from_system_properties() {
+ assertThat(Platform.JVM_VERSION).isEqualTo(System.getProperty("java.runtime.version"));
+ assertThat(Platform.JVM_INFO).isEqualTo(System.getProperty("java.vm.info"));
+ assertThat(Platform.JVM_NAME).isEqualTo(System.getProperty("java.vm.name"));
+ assertThat(Platform.JVM_VENDOR).isEqualTo(System.getProperty("java.vm.vendor"));
+ assertThat(Platform.JVM_VENDOR_VERSION).isEqualTo(System.getProperty("java.vm.version"));
+ }
+
+ @Test
+ public void should_parse_open_jdk_string() {
+ // Given
+ // Sources :
+ // - http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
+ // - http://www.oracle.com/technetwork/java/javase/jdk7-naming-418744.html
+ // - http://www.oracle.com/technetwork/java/javase/jdk8-naming-2157130.html
+ // - http://stackoverflow.com/questions/35844985/how-do-we-get-sr-and-fp-of-ibm-jre-using-java
+ // - http://www.ibm.com/support/knowledgecenter/SSYKE2_6.0.0/com.ibm.java.doc.user.win32.60/user/java_version_check.html
+ Map<String, Boolean> versions = new HashMap<String, Boolean>() {{
+ put("1.8.0_92-b14", false);
+ put("1.8.0-b24", true);
+ put("1.8.0_5", true);
+ put("1.8.0b5_u44", true);
+ put("1.8.0b5_u92", false);
+ put("1.7.0_4", false);
+ put("1.4.0_03-b04", false);
+ put("1.4.0_03-ea-b01", false);
+ put("pxi3270_27sr4-20160303_03 (SR4)", false);
+ put("pwi3260sr11-20120412_01 (SR11)", false);
+ }};
+
+ assertPlatformParsesCorrectlyVariousVersionScheme(versions);
+ }
+
+ @Test
+ public void should_parse_open_jdk9_string() {
+ // The tested method targets Java 8 but should be able to parse other Java version numbers including Java 9
+
+ // Given
+ // Sources :
+ // - http://openjdk.java.net/jeps/223 (Java 9)
+ //
+ // System Property Existing Proposed
+ // ------------------------------- ------------ --------
+ // Early Access
+ // java.runtime.version 1.9.0-ea-b73 9-ea+73
+ // java.vm.version 1.9.0-ea-b73 9-ea+73
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ // Major (GA)
+ // java.version 1.9.0 9
+ // java.runtime.version 1.9.0-b100 9+100
+ // java.vm.version 1.9.0-b100 9+100
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ // Minor #1 (GA)
+ // java.version 1.9.0_20 9.1.2
+ // java.runtime.version 1.9.0_20-b62 9.1.2+62
+ // java.vm.version 1.9.0_20-b62 9.1.2+62
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ // Security #1 (GA)
+ // java.version 1.9.0_5 9.0.1
+ // java.runtime.version 1.9.0_5-b20 9.0.1+20
+ // java.vm.version 1.9.0_5-b20 9.0.1+20
+ // java.specification.version 1.9 9
+ // java.vm.specification.version 1.9 9
+ //
+ Map<String, Boolean> versions = new HashMap<String, Boolean>() {{
+ put("9-ea+73", false);
+ put("9+100", false);
+ put("9.1.2+62", false);
+ put("9.0.1+20", false);
+ }};
+
+ assertPlatformParsesCorrectlyVariousVersionScheme(versions);
+ }
+
+
+ private void assertPlatformParsesCorrectlyVariousVersionScheme(Map<String, Boolean> versions) {
+ for (Map.Entry<String, Boolean> version : versions.entrySet()) {
+ assertThat(Platform.isJava8BelowUpdate45(version.getKey())).describedAs(version.getKey())
+ .isEqualTo(version.getValue());
+ }
+ }
+}
| train | train | 2016-09-24T23:12:43 | "2016-09-17T15:27:23Z" | mockitoguy | train |
mockito/mockito/650_651 | mockito/mockito | mockito/mockito/650 | mockito/mockito/651 | [
"timestamp(timedelta=1.0, similarity=0.9526223644965176)",
"keyword_pr_to_issue"
] | 88329aa20973fdc71cb2816139f165148587e0ac | 329a8f46ad685b6bfb315f649232b1d8ec5b8cc8 | [] | [] | "2016-09-24T14:20:27Z" | [] | Update AssertJ to 3 | Since AssertJ 3 relies on Java 8, we can now update on master. It seems that there are very few breaking changes so hopefully this should not be a big hassle.
| [
"build.gradle"
] | [
"build.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index 33f03bff72..946fd0d943 100644
--- a/build.gradle
+++ b/build.gradle
@@ -67,7 +67,7 @@ dependencies {
testCompile 'org.ow2.asm:asm:5.1'
- testCompile 'org.assertj:assertj-core:1.7.1'
+ testCompile 'org.assertj:assertj-core:3.5.2'
testRuntime configurations.provided
| null | val | train | 2016-09-17T17:38:04 | "2016-09-24T09:34:15Z" | TimvdLippe | train |
mockito/mockito/653_654 | mockito/mockito | mockito/mockito/653 | mockito/mockito/654 | [
"timestamp(timedelta=1.0, similarity=0.8851382101039562)"
] | bde8b406f7988a7434d9edd2866e61817c13e05e | 83d76ea7fcea66be81bf70802a44c08cb4f6cca2 | [
"PR? :)\n",
"Check. See #654.\n"
] | [] | "2016-09-27T14:33:49Z" | [
"refactoring"
] | Typos in FailureDetecter | `FailureDetecter` should be `FailureDetector`. Its method `isSussessful()` should probably be `isSuccessful()`.
| [
"src/main/java/org/mockito/internal/runners/StrictRunner.java",
"src/main/java/org/mockito/internal/runners/util/FailureDetecter.java"
] | [
"src/main/java/org/mockito/internal/runners/StrictRunner.java",
"src/main/java/org/mockito/internal/runners/util/FailureDetector.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/runners/StrictRunner.java b/src/main/java/org/mockito/internal/runners/StrictRunner.java
index 6138865488..0c4a347abd 100644
--- a/src/main/java/org/mockito/internal/runners/StrictRunner.java
+++ b/src/main/java/org/mockito/internal/runners/StrictRunner.java
@@ -6,7 +6,7 @@
import org.junit.runner.notification.RunNotifier;
import org.mockito.Mockito;
import org.mockito.internal.junit.UnnecessaryStubbingsReporter;
-import org.mockito.internal.runners.util.FailureDetecter;
+import org.mockito.internal.runners.util.FailureDetector;
public class StrictRunner implements RunnerImpl {
@@ -26,7 +26,7 @@ public StrictRunner(RunnerImpl runner, Class<?> testClass) {
public void run(RunNotifier notifier) {
//TODO need to be able to opt in for full stack trace instead of just relying on the stack trace filter
UnnecessaryStubbingsReporter reporter = new UnnecessaryStubbingsReporter();
- FailureDetecter listener = new FailureDetecter();
+ FailureDetector listener = new FailureDetector();
Mockito.framework().addListener(reporter);
try {
@@ -37,7 +37,7 @@ public void run(RunNotifier notifier) {
Mockito.framework().removeListener(reporter);
}
- if (!filterRequested && listener.isSussessful()) {
+ if (!filterRequested && listener.isSuccessful()) {
//only report when:
//1. if all tests from given test have ran (filter requested is false)
// Otherwise we would report unnecessary stubs even if the user runs just single test from the class
diff --git a/src/main/java/org/mockito/internal/runners/util/FailureDetecter.java b/src/main/java/org/mockito/internal/runners/util/FailureDetector.java
similarity index 86%
rename from src/main/java/org/mockito/internal/runners/util/FailureDetecter.java
rename to src/main/java/org/mockito/internal/runners/util/FailureDetector.java
index 1ba6d52978..14d4eba468 100644
--- a/src/main/java/org/mockito/internal/runners/util/FailureDetecter.java
+++ b/src/main/java/org/mockito/internal/runners/util/FailureDetector.java
@@ -10,7 +10,7 @@
/**
* Implementation of JUnit run listener that knows when any of the tests failed
*/
-public class FailureDetecter extends RunListener {
+public class FailureDetector extends RunListener {
private boolean failed;
@@ -20,7 +20,7 @@ public void testFailure(Failure failure) throws Exception {
failed = true;
}
- public boolean isSussessful() {
+ public boolean isSuccessful() {
return !failed;
}
-}
\ No newline at end of file
+}
| null | val | train | 2016-09-24T23:16:33 | "2016-09-27T11:57:26Z" | odrotbohm | train |
mockito/mockito/655_656 | mockito/mockito | mockito/mockito/655 | mockito/mockito/656 | [
"timestamp(timedelta=0.0, similarity=0.9690160524901865)"
] | 83d76ea7fcea66be81bf70802a44c08cb4f6cca2 | dbab2de80d29fa30cc2d641bed78190444b0fb77 | [] | [] | "2016-09-27T16:15:03Z" | [] | Typo in JUnitDetecter class name | `JUnitDetecter` class should be renamed to `JUnitDetector` and accordingly the variables in `FriendlyExceptionMaker` and `JUnitTool` should be renamed from detecter to detector.
| [
"src/main/java/org/mockito/internal/junit/FriendlyExceptionMaker.java",
"src/main/java/org/mockito/internal/junit/JUnitDetecter.java",
"src/main/java/org/mockito/internal/junit/JUnitTool.java"
] | [
"src/main/java/org/mockito/internal/junit/FriendlyExceptionMaker.java",
"src/main/java/org/mockito/internal/junit/JUnitDetector.java",
"src/main/java/org/mockito/internal/junit/JUnitTool.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/junit/FriendlyExceptionMaker.java b/src/main/java/org/mockito/internal/junit/FriendlyExceptionMaker.java
index 2900f7267b..3c122c9afe 100644
--- a/src/main/java/org/mockito/internal/junit/FriendlyExceptionMaker.java
+++ b/src/main/java/org/mockito/internal/junit/FriendlyExceptionMaker.java
@@ -8,15 +8,15 @@
*/
class FriendlyExceptionMaker {
- private final JUnitDetecter detecter;
+ private final JUnitDetector detector;
- FriendlyExceptionMaker(JUnitDetecter detecter) {
- this.detecter = detecter;
+ FriendlyExceptionMaker(JUnitDetector detector) {
+ this.detector = detector;
}
//TODO SF this can be now unit tested
public AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
- if (!detecter.hasJUnit()) {
+ if (!detector.hasJUnit()) {
return new ArgumentsAreDifferent(message);
}
diff --git a/src/main/java/org/mockito/internal/junit/JUnitDetecter.java b/src/main/java/org/mockito/internal/junit/JUnitDetector.java
similarity index 87%
rename from src/main/java/org/mockito/internal/junit/JUnitDetecter.java
rename to src/main/java/org/mockito/internal/junit/JUnitDetector.java
index 3ccc7f0294..4aac39df8d 100644
--- a/src/main/java/org/mockito/internal/junit/JUnitDetecter.java
+++ b/src/main/java/org/mockito/internal/junit/JUnitDetector.java
@@ -1,10 +1,10 @@
package org.mockito.internal.junit;
-class JUnitDetecter {
+class JUnitDetector {
private boolean hasJUnit;
- JUnitDetecter() {
+ JUnitDetector() {
try {
Class.forName("junit.framework.ComparisonFailure");
hasJUnit = true;
diff --git a/src/main/java/org/mockito/internal/junit/JUnitTool.java b/src/main/java/org/mockito/internal/junit/JUnitTool.java
index ec98faabe7..4120acf0fb 100644
--- a/src/main/java/org/mockito/internal/junit/JUnitTool.java
+++ b/src/main/java/org/mockito/internal/junit/JUnitTool.java
@@ -6,13 +6,13 @@
public class JUnitTool {
- private static final JUnitDetecter detecter = new JUnitDetecter();
+ private static final JUnitDetector detector = new JUnitDetector();
public static boolean hasJUnit() {
- return detecter.hasJUnit();
+ return detector.hasJUnit();
}
public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
- return new FriendlyExceptionMaker(detecter).createArgumentsAreDifferentException(message, wanted, actual);
+ return new FriendlyExceptionMaker(detector).createArgumentsAreDifferentException(message, wanted, actual);
}
}
\ No newline at end of file
| null | val | train | 2016-09-27T16:50:34 | "2016-09-27T16:09:54Z" | vtorosyan | train |
mockito/mockito/661_662 | mockito/mockito | mockito/mockito/661 | mockito/mockito/662 | [
"timestamp(timedelta=0.0, similarity=0.9684891101898311)",
"keyword_pr_to_issue"
] | 7ec39e50872f8533d9bef191b0285cfe6898fa2f | 2fac43f833e585ebbaa0148de28b1db3f6098c0a | [] | [] | "2016-09-30T05:15:15Z" | [] | Update Gradle to 3.1 | Keep mockito up-to-date with Gradle. 3.1 is released and it brings some performance improvements, fixes and features: https://docs.gradle.org/3.1/release-notes
| [
"build.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat"
] | [
"build.gradle",
"gradle/wrapper/gradle-wrapper.properties",
"gradlew",
"gradlew.bat"
] | [] | diff --git a/build.gradle b/build.gradle
index 614c141c2a..bdede4725f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -123,7 +123,7 @@ apply from: 'gradle/release.gradle'
apply from: 'gradle/pom.gradle'
task wrapper(type: Wrapper) {
- gradleVersion = '3.0'
+ gradleVersion = '3.1'
}
task ciBuild {
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 08b5db1824..741e62f45b 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Sat Sep 17 14:22:48 CEST 2016
+#Thu Sep 29 21:49:00 PDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-3.1-bin.zip
diff --git a/gradlew b/gradlew
index 27309d9231..9aa616c273 100755
--- a/gradlew
+++ b/gradlew
@@ -161,4 +161,9 @@ function splitJvmOpts() {
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
+if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then
+ cd "$(dirname "$0")"
+fi
+
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/gradlew.bat b/gradlew.bat
index 832fdb6079..f9553162f1 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -49,7 +49,6 @@ goto fail
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
-if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@@ -60,11 +59,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
-goto execute
-
-:4NT_args
-@rem Get arguments from the 4NT Shell from JP Software
-set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
| null | test | train | 2016-09-29T15:16:56 | "2016-09-30T05:07:41Z" | jonatan-ivanov | train |
mockito/mockito/543_698 | mockito/mockito | mockito/mockito/543 | mockito/mockito/698 | [
"timestamp(timedelta=2.0, similarity=0.9517652425385589)"
] | a002a673de13d0f28a7451efc535a6cf344d4498 | af0763cc028fb27967a6b9c90a6e3622a24a556c | [] | [
"`out` could be `StringBuilder` instead of just `String`.\n",
"Formatting.\n",
"`String.format()` to improve readability?\n",
"Why not to mark it with `@Override` to force a deletion? AFAIR Mockito does not support Java 5 any longer.\n",
"It would be nice to prefer AssertJ assertions over Junit they have a better API and allow chaining. Not a blocker to merge though.\n",
"Actually it's the reverse `assertThat(value).isEqualTo(expected)`\n",
"@szczepiq It seems to remain not fixed.\n"
] | "2016-10-17T04:07:32Z" | [
"new feature"
] | new MockingDetails.printInvocations() API for debugging tests and edge cases | Let's add new MockingDetails.printInvocations() API. We already provide it silently via Mockito.debug().printInvocations(). Since the code is in place, let's expose it and get rid of the Mockito.debug()
- [ ] move Mockito.debug().printInvocations() to MockingDetails, move tests, too
- [ ] document new API addition somewhere (find place if there isn't any)
- [ ] document removal of the API (find place for removed API if any)
| [
"src/main/java/org/mockito/MockingDetails.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/MockitoDebugger.java",
"src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java",
"src/main/java/org/mockito/internal/debugging/WarningsCollector.java",
"src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java",
"src/main/java/org/mockito/internal/util/DefaultMockingDetails.java",
"src/main/java/org/mockito/stubbing/Stubbing.java"
] | [
"src/main/java/org/mockito/MockingDetails.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/MockitoDebugger.java",
"src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java",
"src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java",
"src/main/java/org/mockito/internal/debugging/WarningsCollector.java",
"src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java",
"src/main/java/org/mockito/internal/util/DefaultMockingDetails.java",
"src/main/java/org/mockito/stubbing/Stubbing.java"
] | [
"src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java",
"src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java"
] | diff --git a/src/main/java/org/mockito/MockingDetails.java b/src/main/java/org/mockito/MockingDetails.java
index 794582dc6a..6ac617c55d 100644
--- a/src/main/java/org/mockito/MockingDetails.java
+++ b/src/main/java/org/mockito/MockingDetails.java
@@ -14,6 +14,7 @@
/**
* Provides mocking information.
* For example, you can identify whether a particular object is either a mock or a spy.
+ * For examples and more information please refer to the javadoc of the individual methods on this class.
*
* @since 1.9.5
*/
@@ -84,7 +85,27 @@ public interface MockingDetails {
* <p>
* This method throws meaningful exception when object wrapped by MockingDetails is not a mock.
*
- * @since 2.2.0
+ * @since 2.2.3
*/
Collection<Stubbing> getStubbings();
+
+ /**
+ * Returns printing-friendly list of the invocations that occurred with the mock object.
+ * Additionally, this method prints stubbing information, including unused stubbings.
+ * For more information about unused stubbing detection see {@link MockitoHint}.
+ * <p>
+ * You can use this method for debugging,
+ * print the output of this method to the console to find out about all interactions with the mock.
+ * <p>
+ * Content that is printed is subject to change as we discover better ways of presenting important mock information.
+ * Don't write code that depends on the output of this method.
+ * If you need to know about interactions and stubbings, use {@link #getStubbings()} and {@link #getInvocations()}.
+ * <p>
+ * This method was moved from the deprecated and semi-hidden type {@link MockitoDebugger}.
+ * <p>
+ * This method throws meaningful exception when object wrapped by MockingDetails is not a mock.
+ *
+ * @since 2.2.6
+ */
+ String printInvocations();
}
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 47d08e4991..684add4b58 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -59,7 +59,7 @@
* <a href="#23">23. Automatic instantiation of <code>@Spies</code>, <code>@InjectMocks</code> and constructor injection goodness (Since 1.9.0)</a><br/>
* <a href="#24">24. One-liner stubs (Since 1.9.0)</a><br/>
* <a href="#25">25. Verification ignoring stubs (Since 1.9.0)</a><br/>
- * <a href="#26">26. Mocking details (Improved in 2.2.0)</a><br/>
+ * <a href="#26">26. Mocking details (Improved in 2.2.x)</a><br/>
* <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/>
* <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/>
* <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/>
@@ -889,7 +889,7 @@
*
*
*
- * <h3 id="26">26. <a class="meaningful_link" href="#mocking_details">Mocking details</a> (Improved in 2.2.0)</h3>
+ * <h3 id="26">26. <a class="meaningful_link" href="#mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
* <p>
*
* Mockito offers API to inspect the details of a mock object.
@@ -901,14 +901,17 @@
* Mockito.mockingDetails(someObject).isSpy();
*
* //Getting details like type to mock or default answer:
- * MockingDetails details = mockingDetails(someObject)
+ * MockingDetails details = mockingDetails(mock);
* details.getMockCreationSettings().getTypeToMock();
* details.getMockCreationSettings().getDefaultAnswer();
*
* //Getting interactions and stubbings of the mock:
- * MockingDetails details = mockingDetails(someObject)
+ * MockingDetails details = mockingDetails(mock);
* details.getInteractions();
* details.getStubbings();
+ *
+ * //Printing all interactions (including stubbing, unused stubs)
+ * System.out.println(mockingDetails(mock).printInvocations());
* </code></pre>
*
* For more information see javadoc for {@link MockingDetails}.
@@ -2649,9 +2652,7 @@ public static VerificationMode description(String description) {
}
/**
- * This API will move soon to a different place.
- * See <a href="https://github.com/mockito/mockito/issues/577">issue 577</a>.
- * See also <a href="https://github.com/mockito/mockito/issues/542">issue 542</a>.
+ * @deprecated - please use {@link MockingDetails#printInvocations()}.
*/
@Deprecated
static MockitoDebugger debug() {
diff --git a/src/main/java/org/mockito/MockitoDebugger.java b/src/main/java/org/mockito/MockitoDebugger.java
index c24d633dfc..46a41762b4 100644
--- a/src/main/java/org/mockito/MockitoDebugger.java
+++ b/src/main/java/org/mockito/MockitoDebugger.java
@@ -4,10 +4,15 @@
*/
package org.mockito;
+/**
+ * @deprecated - please use {@link MockingDetails#printInvocations()}.
+ */
+@Deprecated
public interface MockitoDebugger {
- //Prints all interactions with mock. Also prints stubbing information.
- //You can put it in your 'tearDown' method
+ /**
+ * @deprecated - please use {@link MockingDetails#printInvocations()}.
+ */
+ @Deprecated
String printInvocations(Object ... mocks);
-
}
\ No newline at end of file
diff --git a/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java b/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java
new file mode 100644
index 0000000000..b0df32af87
--- /dev/null
+++ b/src/main/java/org/mockito/internal/debugging/InvocationsPrinter.java
@@ -0,0 +1,54 @@
+package org.mockito.internal.debugging;
+
+import org.mockito.Mockito;
+import org.mockito.internal.util.collections.ListUtil;
+import org.mockito.invocation.Invocation;
+import org.mockito.stubbing.Stubbing;
+
+import java.util.Collection;
+import java.util.LinkedList;
+
+/**
+ * Prints invocations in human-readable, printable way
+ */
+public class InvocationsPrinter {
+
+ public String printInvocations(Object mock) {
+ Collection<Invocation> invocations = Mockito.mockingDetails(mock).getInvocations();
+ Collection<Stubbing> stubbings = Mockito.mockingDetails(mock).getStubbings();
+ if (invocations.isEmpty() && stubbings.isEmpty()) {
+ return "No interactions and stubbings found for mock: " + mock;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ int x = 1;
+ for(Invocation i:invocations) {
+ if (x == 1) {
+ sb.append("[Mockito] Interactions of: ").append(mock).append("\n");
+ }
+ sb.append(" ").append(x++).append(". ").append(i.toString()).append("\n");
+ sb.append(" ").append(i.getLocation()).append("\n");
+ if (i.stubInfo() != null) {
+ sb.append(" - stubbed ").append(i.stubInfo().stubbedAt()).append("\n");
+ }
+ }
+
+ LinkedList<Stubbing> unused = ListUtil.filter(stubbings, new ListUtil.Filter<Stubbing>() {
+ public boolean isOut(Stubbing s) {
+ return s.wasUsed();
+ }
+ });
+
+ if (unused.isEmpty()) {
+ return sb.toString();
+ }
+ sb.append("[Mockito] Unused stubbings of: " + mock).append("\n");
+
+ x = 1;
+ for(Stubbing s:stubbings) {
+ sb.append(" ").append(x++).append(". ").append(s.getInvocation()).append("\n");
+ sb.append(" - stubbed ").append(s.getInvocation().getLocation()).append("\n");
+ }
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java b/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java
index 8a8a056b7e..35e7e7b7a9 100644
--- a/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java
+++ b/src/main/java/org/mockito/internal/debugging/MockitoDebuggerImpl.java
@@ -17,6 +17,10 @@ public class MockitoDebuggerImpl implements MockitoDebugger {
private final UnusedStubsFinder unusedStubsFinder = new UnusedStubsFinder();
+ /**
+ * TODO: when MockitoDebugger is deleted, delete this implementation, too
+ */
+ @Deprecated
public String printInvocations(Object ... mocks) {
String out = "";
List<Invocation> invocations = AllInvocationsFinder.find(asList(mocks));
diff --git a/src/main/java/org/mockito/internal/debugging/WarningsCollector.java b/src/main/java/org/mockito/internal/debugging/WarningsCollector.java
index 725da1d740..e9418869e3 100644
--- a/src/main/java/org/mockito/internal/debugging/WarningsCollector.java
+++ b/src/main/java/org/mockito/internal/debugging/WarningsCollector.java
@@ -12,6 +12,7 @@
import java.util.LinkedList;
import java.util.List;
+@Deprecated
public class WarningsCollector {
private final List<Object> createdMocks;
diff --git a/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java b/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java
index 4d515af478..21d3b27dd2 100644
--- a/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java
+++ b/src/main/java/org/mockito/internal/invocation/UnusedStubsFinder.java
@@ -12,6 +12,7 @@
import java.util.*;
+@Deprecated
public class UnusedStubsFinder {
/**
diff --git a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java
index 5b485891d6..7114a46d21 100644
--- a/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java
+++ b/src/main/java/org/mockito/internal/util/DefaultMockingDetails.java
@@ -7,6 +7,7 @@
import org.mockito.MockingDetails;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.debugging.InvocationsPrinter;
import org.mockito.stubbing.Stubbing;
import org.mockito.internal.stubbing.StubbingComparator;
import org.mockito.invocation.Invocation;
@@ -58,6 +59,12 @@ public Collection<Stubbing> getStubbings() {
return out;
}
+ @Override
+ public String printInvocations() {
+ assertGoodMock();
+ return new InvocationsPrinter().printInvocations(toInspect);
+ }
+
private InternalMockHandler<Object> mockHandler() {
assertGoodMock();
return getMockHandler(toInspect);
diff --git a/src/main/java/org/mockito/stubbing/Stubbing.java b/src/main/java/org/mockito/stubbing/Stubbing.java
index 6e761382af..795e8ed485 100644
--- a/src/main/java/org/mockito/stubbing/Stubbing.java
+++ b/src/main/java/org/mockito/stubbing/Stubbing.java
@@ -7,7 +7,7 @@
* Stubbing declared on the mock object.
* See detailed description including sample code and use cases see javadoc for {@link MockingDetails#getStubbings()}.
*
- * @since 2.2.0
+ * @since 2.2.3
*/
public interface Stubbing {
@@ -21,7 +21,7 @@ public interface Stubbing {
* <p>
* To understand how this method is useful, see the description at {@link MockingDetails#getStubbings()}.
*
- * @since 2.2.0
+ * @since 2.2.3
*/
Invocation getInvocation();
@@ -37,7 +37,7 @@ public interface Stubbing {
* <p>
* To understand how this method is useful, see the description at {@link MockingDetails#getStubbings()}.
*
- * @since 2.2.0
+ * @since 2.2.3
*/
boolean wasUsed();
}
| diff --git a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java
index 4de9518b36..8af561bb3e 100644
--- a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java
+++ b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java
@@ -15,8 +15,10 @@
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.fail;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
@@ -163,6 +165,33 @@ public void manipulating_stubbings_explicitly_is_safe() {
assertEquals(1, mockingDetails(mock).getStubbings().size());
}
+ @Test
+ public void prints_invocations() throws Exception {
+ //given
+ given(mock.simpleMethod("different arg")).willReturn("foo");
+ mock.simpleMethod("arg");
+
+ //when
+ String log = Mockito.mockingDetails(mock).printInvocations();
+
+ //then
+ assertThat(log).containsIgnoringCase("unused");
+ assertThat(log).containsIgnoringCase("mock.simpleMethod(\"arg\")");
+ assertThat(log).containsIgnoringCase("mock.simpleMethod(\"different arg\")");
+ }
+
+ @Test
+ public void fails_when_printin_invocations_from_non_mock() {
+ try {
+ //when
+ mockingDetails(new Object()).printInvocations();
+ //then
+ fail();
+ } catch (NotAMockException e) {
+ TestCase.assertEquals("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of class java.lang.Object!", e.getMessage());
+ }
+ }
+
public class Foo { }
public interface Bar { }
public static class Gork { }
diff --git a/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java b/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java
new file mode 100644
index 0000000000..9d8bacd3e2
--- /dev/null
+++ b/src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java
@@ -0,0 +1,83 @@
+package org.mockitousage.debugging;
+
+import org.assertj.core.api.Assertions;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.internal.debugging.InvocationsPrinter;
+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.mockito.Mockito.when;
+
+public class InvocationsPrinterTest extends TestBase {
+
+ @Mock IMethods mock;
+
+ @Test public void no_invocations() {
+ Assert.assertEquals("No interactions and stubbings found for mock: mock", new InvocationsPrinter().printInvocations(mock));
+ }
+
+ @Test public void prints_invocations() {
+ mock.simpleMethod(100);
+ triggerInteraction();
+
+ assertThat(filterLineNo("[Mockito] Interactions of: mock\n" +
+ " 1. mock.simpleMethod(100);\n" +
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n" +
+ " 2. mock.otherMethod();\n" +
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n"))
+ .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock)));
+ }
+
+ @Test public void prints_stubbings() {
+ triggerStubbing();
+
+ assertThat(filterLineNo("[Mockito] Unused stubbings of: mock\n" +
+ " 1. mock.simpleMethod(\"a\");\n" +
+ " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n"))
+ .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock)));
+ }
+
+ @Test public void prints_invocations_and_stubbings() {
+ triggerStubbing();
+
+ mock.simpleMethod("a");
+ triggerInteraction();
+
+ assertThat(filterLineNo("[Mockito] Interactions of: mock\n" +
+ " 1. mock.simpleMethod(\"a\");\n" +
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n" +
+ " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n" +
+ " 2. mock.otherMethod();\n" +
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n"))
+ .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock)));
+ }
+
+ @Test public void prints_invocations_and_unused_stubbings() {
+ triggerStubbing();
+
+ mock.simpleMethod("b");
+ triggerInteraction();
+
+ assertThat(filterLineNo("[Mockito] Interactions of: mock\n" +
+ " 1. mock.simpleMethod(\"b\");\n" +
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n" +
+ " 2. mock.otherMethod();\n" +
+ " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n" +
+ "[Mockito] Unused stubbings of: mock\n" +
+ " 1. mock.simpleMethod(\"a\");\n" +
+ " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n"))
+ .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock)));
+ }
+
+ private void triggerInteraction() {
+ mock.otherMethod();
+ }
+
+ private void triggerStubbing() {
+ when(mock.simpleMethod("a")).thenReturn("x");
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/debugging/PrintingInvocationsDetectsUnusedStubTest.java b/src/test/java/org/mockitousage/debugging/PrintingInvocationsDetectsUnusedStubTest.java
deleted file mode 100644
index 1d7748e4a7..0000000000
--- a/src/test/java/org/mockitousage/debugging/PrintingInvocationsDetectsUnusedStubTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2007 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.Mock;
-import org.mockitoutil.TestBase;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.BDDMockito.given;
-
-public class PrintingInvocationsDetectsUnusedStubTest extends TestBase {
-
- @Mock Foo mock;
- @Mock Foo mockTwo;
-
- @Test
- public void shouldDetectUnusedStubbingWhenPrinting() throws Exception {
- //given
- given(mock.giveMeSomeString("different arg")).willReturn("foo");
- mock.giveMeSomeString("arg");
-
- //when
- String log = NewMockito.debug().printInvocations(mock, mockTwo);
-
- //then
- assertThat(log).containsIgnoringCase("unused");
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/debugging/PrintingInvocationsWhenEverythingOkTest.java b/src/test/java/org/mockitousage/debugging/PrintingInvocationsWhenEverythingOkTest.java
deleted file mode 100644
index 49f1b5b8d1..0000000000
--- a/src/test/java/org/mockitousage/debugging/PrintingInvocationsWhenEverythingOkTest.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.debugging;
-
-import org.junit.After;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockitoutil.TestBase;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.BDDMockito.given;
-import static org.mockito.BDDMockito.verify;
-
-public class PrintingInvocationsWhenEverythingOkTest extends TestBase {
-
- @Mock Foo mock;
- @Mock Foo mockTwo;
-
- @Test
- public void shouldPrintInvocationsWhenStubbingNotUsed() throws Exception {
- //given
- performStubbing();
- //when
- businessLogicWithAsking("arg");
- //then
- verify(mockTwo).doSomething("foo");
- }
-
- private void performStubbing() {
- given(mock.giveMeSomeString("arg")).willReturn("foo");
- }
-
- private void businessLogicWithAsking(String name) {
- String out = mock.giveMeSomeString(name);
- businessLogicWithTelling(out);
- }
-
- private void businessLogicWithTelling(String out) {
- mockTwo.doSomething(out);
- }
-
- @After
- public void printInvocations() {
- String log = NewMockito.debug().printInvocations(mock, mockTwo);
- //asking
- assertThat(log)
- .contains("giveMeSomeString(\"arg\")")
- .contains(".businessLogicWithAsking(");
- //telling
- assertThat(log)
- .contains("doSomething(\"foo\")")
- .contains(".businessLogicWithTelling(");
- //stubbing
- assertThat(log)
- .contains("giveMeSomeString(\"arg\")")
- .contains(".performStubbing(", log);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/mockitousage/debugging/PrintingInvocationsWhenStubNotUsedTest.java b/src/test/java/org/mockitousage/debugging/PrintingInvocationsWhenStubNotUsedTest.java
deleted file mode 100644
index 8b22ffec81..0000000000
--- a/src/test/java/org/mockitousage/debugging/PrintingInvocationsWhenStubNotUsedTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockitousage.debugging;
-
-import org.junit.After;
-import org.junit.Test;
-import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
-import org.mockitoutil.TestBase;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.BDDMockito.*;
-
-public class PrintingInvocationsWhenStubNotUsedTest extends TestBase {
-
- Foo mock = mock(Foo.class);
- Foo mockTwo = mock(Foo.class);
-
- @Test(expected = ArgumentsAreDifferent.class)
- public void shouldPrintInvocationsWhenStubbingNotUsed() throws Exception {
- //given
- performStubbing();
- //when
- businessLogicWithAsking("arg");
- //then
- verify(mockTwo).doSomething("foo");
- }
-
- private void performStubbing() {
- given(mock.giveMeSomeString("different arg")).willReturn("foo");
- }
-
- private void businessLogicWithAsking(String name) {
- String out = mock.giveMeSomeString(name);
- businessLogicWithTelling(out);
- }
-
- private void businessLogicWithTelling(String out) {
- mockTwo.doSomething(out);
- }
-
- @After
- public void printInvocations() {
- String log = NewMockito.debug().printInvocations(mock, mockTwo);
- //asking
- assertThat(log)
- .contains("giveMeSomeString(\"arg\")")
- .contains(".businessLogicWithAsking(");
- //telling
- assertThat(log)
- .contains("doSomething(null)")
- .contains(".businessLogicWithTelling(");
- //stubbing
- assertThat(log)
- .contains("giveMeSomeString(\"different arg\")")
- .contains(".performStubbing(");
- }
-}
\ No newline at end of file
| train | train | 2016-10-16T16:18:07 | "2016-08-10T00:45:21Z" | mockitoguy | train |
mockito/mockito/707_711 | mockito/mockito | mockito/mockito/707 | mockito/mockito/711 | [
"timestamp(timedelta=0.0, similarity=0.8775874955528284)"
] | f9f6d21974d530030ea731f21ad2da016ce14ada | 5d74ab11bc7358b195429e275c9fe8f29fb55ffe | [
"Given how Answer is supposed to be used it is a safe change to do. Plus, it is marked as @Incubating :)\n"
] | [] | "2016-10-24T10:31:38Z" | [
"bug"
] | Improve usability of arity Answers with regards to checked exceptions | Recently introduced Answer1 style answers don't declare Throwable. They should! Otherwise the user is forced to add boilerplate code to AnswerX implementations, whenever they use methods that declare checked exceptions. Plus, AnswerX should behave exactly as good old Answer interface!
Reported via the [mailing-list](https://groups.google.com/d/msgid/mockito/82d08ba9-5536-495e-90db-78c1062b6400%40googlegroups.com)
| [
"src/main/java/org/mockito/stubbing/Answer1.java",
"src/main/java/org/mockito/stubbing/Answer2.java",
"src/main/java/org/mockito/stubbing/Answer3.java",
"src/main/java/org/mockito/stubbing/Answer4.java",
"src/main/java/org/mockito/stubbing/Answer5.java",
"src/main/java/org/mockito/stubbing/VoidAnswer1.java",
"src/main/java/org/mockito/stubbing/VoidAnswer2.java",
"src/main/java/org/mockito/stubbing/VoidAnswer3.java",
"src/main/java/org/mockito/stubbing/VoidAnswer4.java",
"src/main/java/org/mockito/stubbing/VoidAnswer5.java"
] | [
"src/main/java/org/mockito/stubbing/Answer1.java",
"src/main/java/org/mockito/stubbing/Answer2.java",
"src/main/java/org/mockito/stubbing/Answer3.java",
"src/main/java/org/mockito/stubbing/Answer4.java",
"src/main/java/org/mockito/stubbing/Answer5.java",
"src/main/java/org/mockito/stubbing/VoidAnswer1.java",
"src/main/java/org/mockito/stubbing/VoidAnswer2.java",
"src/main/java/org/mockito/stubbing/VoidAnswer3.java",
"src/main/java/org/mockito/stubbing/VoidAnswer4.java",
"src/main/java/org/mockito/stubbing/VoidAnswer5.java"
] | [] | diff --git a/src/main/java/org/mockito/stubbing/Answer1.java b/src/main/java/org/mockito/stubbing/Answer1.java
index 23bf06c66b..dcc3ce9083 100644
--- a/src/main/java/org/mockito/stubbing/Answer1.java
+++ b/src/main/java/org/mockito/stubbing/Answer1.java
@@ -3,13 +3,36 @@
import org.mockito.Incubating;
/**
- * One parameter function which returns something
+ * Generic interface to be used for configuring mock's answer for a single 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">
+ * when(mock.someMethod(anyString())).thenAnswer(new Answer<Integer, String>() {
+ * Integer answer(String arg) {
+ * return arg.length();
+ * }
+ * });
+ *
+ * //Following will print "3"
+ * System.out.println(mock.someMethod("foo"));
+ * </code></pre>
*
* @param <T> return type
- * @param <A> input parameter 1 type
+ * @param <A0> type of the single argument
+ * @see Answer
*/
@Incubating
-public interface Answer1<T, A> {
- T answer(A a);
+public interface Answer1<T, A0> {
+ /**
+ * @param argument0 the single argument.
+ *
+ * @return the value to be returned.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ T answer(A0 argument0) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/Answer2.java b/src/main/java/org/mockito/stubbing/Answer2.java
index 89f1894f29..76ed89192a 100644
--- a/src/main/java/org/mockito/stubbing/Answer2.java
+++ b/src/main/java/org/mockito/stubbing/Answer2.java
@@ -3,13 +3,37 @@
import org.mockito.Incubating;
/**
- * Two parameter function which returns something
+ * Generic interface to be used for configuring mock's answer for a two 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">
+ * when(mock.someMethod(anyString(), anyChar())).thenAnswer(new Answer<String, String, Character>() {
+ * String answer(String s, Character c) {
+ * return s.replace('f', c);
+ * }
+ * });
+ *
+ * //Following will print "bar"
+ * System.out.println(mock.someMethod("far", 'b'));
+ * </code></pre>
*
* @param <T> return type
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
+ * @param <A0> type of the first argument
+ * @param <A1> type of the second argument
+ * @see Answer
*/
@Incubating
-public interface Answer2<T, A, B> {
- T answer(A a, B b);
+public interface Answer2<T, A0, A1> {
+ /**
+ * @param argument0 the first argument.
+ * @param argument1 the second argument.
+ *
+ * @return the value to be returned.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ T answer(A0 argument0, A1 argument1) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/Answer3.java b/src/main/java/org/mockito/stubbing/Answer3.java
index 18b4b22f80..a495872f31 100644
--- a/src/main/java/org/mockito/stubbing/Answer3.java
+++ b/src/main/java/org/mockito/stubbing/Answer3.java
@@ -3,14 +3,40 @@
import org.mockito.Incubating;
/**
- * Three parameter function which returns something
+ * Generic interface to be used for configuring mock's answer for a three 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">
+ * when(mock.someMethod(anyInt(), anyString(), anyChar())).thenAnswer(
+ * new Answer<StringBuilder, Integer, String, Character>() {
+ * StringBuilder answer(Integer i, String s, Character c) {
+ * return new StringBuilder().append(i).append(s).append(c);
+ * }
+ * });
+ *
+ * //Following will print "3xyz"
+ * System.out.println(mock.someMethod(3, "xy", 'z'));
+ * </code></pre>
*
* @param <T> return type
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
- * @param <C> input parameter 3 type
+ * @param <A0> type of the first argument
+ * @param <A1> type of the second argument
+ * @param <A2> type of the third argument
+ * @see Answer
*/
@Incubating
-public interface Answer3<T, A, B, C> {
- T answer(A a, B b, C c);
+public interface Answer3<T, A0, A1, A2> {
+ /**
+ * @param argument0 the first argument.
+ * @param argument1 the second argument.
+ * @param argument2 the third argument.
+ *
+ * @return the value to be returned.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ T answer(A0 argument0, A1 argument1, A2 argument2) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/Answer4.java b/src/main/java/org/mockito/stubbing/Answer4.java
index 286542bf8d..d33484ca91 100644
--- a/src/main/java/org/mockito/stubbing/Answer4.java
+++ b/src/main/java/org/mockito/stubbing/Answer4.java
@@ -3,15 +3,42 @@
import org.mockito.Incubating;
/**
- * Three parameter function which returns something
+ * Generic interface to be used for configuring mock's answer for a four 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">
+ * when(mock.someMethod(anyInt(), anyString(), anyChar(), any())).thenAnswer(
+ * new Answer<StringBuilder, Integer, String, Character, Object>() {
+ * StringBuilder answer(Integer i, String s, Character c, Object o) {
+ * return new StringBuilder().append(i).append(s).append(c).append(o.hashCode());
+ * }
+ * });
+ *
+ * //Following will print a string like "3xyz131635550"
+ * System.out.println(mock.someMethod(3, "xy", 'z', new Object()));
+ * </code></pre>
*
* @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 <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
+ * @see Answer
*/
@Incubating
-public interface Answer4<T, A, B, C, D> {
- T answer(A a, B b, C c, D d);
+public interface Answer4<T, A0, A1, A2, A3> {
+ /**
+ * @param argument0 the first argument.
+ * @param argument1 the second argument.
+ * @param argument2 the third argument.
+ * @param argument3 the fourth argument.
+ *
+ * @return the value to be returned.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ T answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/Answer5.java b/src/main/java/org/mockito/stubbing/Answer5.java
index 87e1734b3f..6231340da7 100644
--- a/src/main/java/org/mockito/stubbing/Answer5.java
+++ b/src/main/java/org/mockito/stubbing/Answer5.java
@@ -3,16 +3,43 @@
import org.mockito.Incubating;
/**
- * Three parameter function which returns something
+ * Generic interface to be used for configuring mock's answer for a five 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">
+ * when(mock.someMethod(anyInt(), anyString(), anyChar(), any(), anyBoolean())).thenAnswer(
+ * new Answer<StringBuilder, Integer, String, Character, Object, Boolean>() {
+ * StringBuilder answer(Integer i, String s, Character c, Object o, Boolean isIt) {
+ * return new StringBuilder().append(i).append(s).append(c).append(o.hashCode()).append(isIt);
+ * }
+ * });
+ *
+ * //Following will print a string like "3xyz131635550true"
+ * System.out.println(mock.someMethod(3, "xy", 'z', new Object(), true));
+ * </code></pre>
*
* @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 <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
+ * @see Answer
*/
@Incubating
-public interface Answer5<T, A, B, C, D, E> {
- T answer(A a, B b, C c, D d, E e);
+public interface Answer5<T, A0, A1, A2, A3, A4> {
+ /**
+ * @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.
+ *
+ * @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) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer1.java b/src/main/java/org/mockito/stubbing/VoidAnswer1.java
index 23717d58e7..8ec93f3d89 100644
--- a/src/main/java/org/mockito/stubbing/VoidAnswer1.java
+++ b/src/main/java/org/mockito/stubbing/VoidAnswer1.java
@@ -3,11 +3,32 @@
import org.mockito.Incubating;
/**
- * One parameter void function
+ * Generic interface to be used for configuring mock's answer for a single argument invocation that returns nothing.
*
- * @param <A> input parameter 1 type
+ * 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">
+ * when(mock.someMethod(anyString())).thenAnswer(new Answer<String>() {
+ * void answer(String msg) {
+ * throw new Exception(msg);
+ * }
+ * });
+ *
+ * //Following will raise an exception with the message "boom"
+ * mock.someMethod("boom");
+ * </code></pre>
+ *
+ * @param <A0> type of the single argument
+ * @see Answer
*/
@Incubating
-public interface VoidAnswer1<A> {
- void answer(A a);
+public interface VoidAnswer1<A0> {
+ /**
+ * @param argument0 the single argument.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ void answer(A0 argument0) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer2.java b/src/main/java/org/mockito/stubbing/VoidAnswer2.java
index 1df3af3e8a..55d594ae6c 100644
--- a/src/main/java/org/mockito/stubbing/VoidAnswer2.java
+++ b/src/main/java/org/mockito/stubbing/VoidAnswer2.java
@@ -3,12 +3,34 @@
import org.mockito.Incubating;
/**
- * Two parameter void function
+ * Generic interface to be used for configuring mock's answer for a two argument invocation that returns nothing.
*
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
+ * 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">
+ * when(mock.someMethod(anyString(), anyInt())).thenAnswer(new Answer<String, Integer>() {
+ * void answer(String msg, Integer count) {
+ * throw new Exception(String.format(msg, count));
+ * }
+ * });
+ *
+ * //Following will raise an exception with the message "boom 3"
+ * mock.someMethod("boom %d", 3);
+ * </code></pre>
+ *
+ * @param <A0> type of the first argument
+ * @param <A1> type of the second argument
+ * @see Answer
*/
@Incubating
-public interface VoidAnswer2<A, B> {
- void answer(A a, B b);
+public interface VoidAnswer2<A0, A1> {
+ /**
+ * @param argument0 the first argument.
+ * @param argument1 the second argument.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ void answer(A0 argument0, A1 argument1) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer3.java b/src/main/java/org/mockito/stubbing/VoidAnswer3.java
index 21927c50bd..2cdd268817 100644
--- a/src/main/java/org/mockito/stubbing/VoidAnswer3.java
+++ b/src/main/java/org/mockito/stubbing/VoidAnswer3.java
@@ -3,13 +3,36 @@
import org.mockito.Incubating;
/**
- * Two parameter void function
+ * Generic interface to be used for configuring mock's answer for a three argument invocation that returns nothing.
*
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
- * @param <C> input parameter 3 type
+ * 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">
+ * when(mock.someMethod(anyString(), anyInt(), anyString())).thenAnswer(new Answer<String, Integer, String>() {
+ * void answer(String msg, Integer count, String another) {
+ * throw new Exception(String.format(msg, another, count));
+ * }
+ * });
+ *
+ * //Following will raise an exception with the message "ka-boom 3"
+ * mock.someMethod("%s-boom %d", 3, "ka");
+ * </code></pre>
+ *
+ * @param <A0> type of the first argument
+ * @param <A1> type of the second argument
+ * @param <A2> type of the third argument
+ * @see Answer
*/
@Incubating
-public interface VoidAnswer3<A, B, C> {
- void answer(A a, B b, C c);
+public interface VoidAnswer3<A0, A1, A2> {
+ /**
+ * @param argument0 the first argument.
+ * @param argument1 the second argument.
+ * @param argument2 the third argument.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ void answer(A0 argument0, A1 argument1, A2 argument2) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer4.java b/src/main/java/org/mockito/stubbing/VoidAnswer4.java
index 8385e24e2c..939a04add0 100644
--- a/src/main/java/org/mockito/stubbing/VoidAnswer4.java
+++ b/src/main/java/org/mockito/stubbing/VoidAnswer4.java
@@ -3,14 +3,39 @@
import org.mockito.Incubating;
/**
- * Two parameter void function
+ * Generic interface to be used for configuring mock's answer for a four argument invocation that returns nothing.
*
- * @param <A> input parameter 1 type
- * @param <B> input parameter 2 type
- * @param <C> input parameter 3 type
- * @param <D> input parameter 4 type
+ * 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">
+ * when(mock.someMethod(anyString(), anyInt(), anyString(), anyChar())).thenAnswer(
+ * new Answer<String, Integer, String, Character>() {
+ * void answer(String msg, Integer count, String another, Character c) {
+ * throw new Exception(String.format(msg, another, c, count));
+ * }
+ * });
+ *
+ * //Following will raise an exception with the message "ka-boom <3"
+ * mock.someMethod("%s-boom %c%d", 3, "ka", '<');
+ * </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
+ * @see Answer
*/
@Incubating
-public interface VoidAnswer4<A, B, C, D> {
- void answer(A a, B b, C c, D d);
+public interface VoidAnswer4<A0, A1, A2, A3> {
+ /**
+ * @param argument0 the first argument.
+ * @param argument1 the second argument.
+ * @param argument2 the third argument.
+ * @param argument3 the fourth argument.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3) throws Throwable;
}
diff --git a/src/main/java/org/mockito/stubbing/VoidAnswer5.java b/src/main/java/org/mockito/stubbing/VoidAnswer5.java
index 4fdf9bda73..a92ab9b08f 100644
--- a/src/main/java/org/mockito/stubbing/VoidAnswer5.java
+++ b/src/main/java/org/mockito/stubbing/VoidAnswer5.java
@@ -3,15 +3,41 @@
import org.mockito.Incubating;
/**
- * Two parameter void function
+ * Generic interface to be used for configuring mock's answer for a five argument invocation that returns nothing.
*
- * @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
+ * 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">
+ * when(mock.someMethod(anyString(), anyInt(), anyString(), anyChar(), anyString())).thenAnswer(
+ * new Answer<String, Integer, String, Character>() {
+ * void answer(String msg, Integer count, String another, Character c, String subject) {
+ * throw new Exception(String.format(msg, another, c, count, subject));
+ * }
+ * });
+ *
+ * //Following will raise an exception with the message "ka-boom <3 mockito"
+ * mock.someMethod("%s-boom %c%d %s", 3, "ka", '<', "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
+ * @see Answer
*/
@Incubating
-public interface VoidAnswer5<A, B, C, D, E> {
- void answer(A a, B b, C c, D d, E e);
+public interface VoidAnswer5<A0, A1, A2, A3, A4> {
+ /**
+ * @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.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ void answer(A0 argument0, A1 argument1, A2 argument2, A3 argument3, A4 argument4) throws Throwable;
}
| null | train | train | 2016-10-24T06:17:32 | "2016-10-21T22:28:34Z" | bric3 | train |
mockito/mockito/609_754 | mockito/mockito | mockito/mockito/609 | mockito/mockito/754 | [
"keyword_pr_to_issue"
] | 2025a1830ff356124c808bffb9306582a5d40c6f | 0d24b6391fe99d1af7cf176b1c09f295cda964d0 | [
"https://github.com/mockito/mockito/issues/384#issuecomment-243044175\n",
"@szczepiq This is not the javadoc but I've mentioned a bit the runner in the what's new / migration guide in the wiki in the improvement section \n\nhttps://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2\n",
"Per https://github.com/mockito/mockito/issues/720#issuecomment-257087017 the message of `UnnecessaryStubbingException` should be improved to mention `MockitoJUnitRunner.Silent`.\n"
] | [] | "2016-11-14T05:07:55Z" | [
"docs"
] | Silent JUnit runner and quiet JUnit rule are better expose in the docs | See great feedback from a user in #384
| [
"src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java"
] | [
"src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java"
] | [
"src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java"
] | diff --git a/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java b/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java
index 39fbae80ee..603dc349e1 100644
--- a/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java
+++ b/src/main/java/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java
@@ -5,8 +5,13 @@
package org.mockito.exceptions.misusing;
/**
- * Unnecessary stubs are stubbed method calls that were never realized during test execution
- * (see also {@link org.mockito.quality.MockitoHint}), example:
+ * This exception indicates presence of unused stubbings.
+ * It is highly recommended to remove unused stubbings to keep the codebase clean.
+ * You can opt-out from detecting unused stubbings using {@link org.mockito.runners.MockitoJUnitRunner.Silent} or
+ * {@link org.mockito.junit.MockitoRule#silent()} (when you are using Mockito JUnit rules.
+ * For more information about detecting unused stubbings, see {@link org.mockito.quality.MockitoHint}.
+ * <p>
+ * Unnecessary stubbings are stubbed method calls that were never realized during test execution. Example:
* <pre class="code"><code class="java">
* //code under test:
* ...
@@ -26,7 +31,13 @@
* In order to keep the codebase clean & maintainable it is necessary to remove unnecessary code.
* Otherwise tests are harder to read and reason about.
* <p>
+ * Mockito JUnit Runner triggers <code>UnnecessaryStubbingException</code> only when none of the test methods use the stubbings.
+ * This means that it is ok to put default stubbing in a 'setup' method or in test class constructor.
+ * That default stubbing needs to be used at least once by one of the test methods.
+ * <p>
* To find out more about detecting unused stubbings see {@link org.mockito.quality.MockitoHint}.
+ * See javadoc for {@link org.mockito.runners.MockitoJUnitRunner} to find out how Mockito JUnit Runner detects unused stubs.
+ * See javadoc for {@link org.mockito.junit.MockitoRule} to understand the behavior or Mockito JUnit Rules.
*/
public class UnnecessaryStubbingException extends RuntimeException {
public UnnecessaryStubbingException(String message) {
diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 807bdee3a3..86e284b22c 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -839,7 +839,7 @@ public static UnnecessaryStubbingException formatUnncessaryStubbingException(Cla
"Unnecessary stubbings detected in test class: " + testClass.getSimpleName(),
"Clean & maintainable test code requires zero unnecessary code.",
"Following stubbings are unnecessary (click to navigate to relevant line of code):" + stubbings,
- "Please remove unnecessary stubbings. More info: javadoc for UnnecessaryStubbingException class."
+ "Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class."
));
}
}
| diff --git a/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java b/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java
index 3760e64467..637f7acac5 100644
--- a/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java
+++ b/src/test/java/org/mockitousage/junitrunner/UnusedStubsExceptionMessageTest.java
@@ -49,7 +49,7 @@ public void lists_all_unused_stubs_cleanly() {
"Following stubbings are unnecessary (click to navigate to relevant line of code):\n" +
" 1. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.<init>(UnusedStubsExceptionMessageTest.java:0)\n" +
" 2. -> at org.mockitousage.junitrunner.UnusedStubsExceptionMessageTest$HasUnnecessaryStubs.<init>(UnusedStubsExceptionMessageTest.java:0)\n" +
- "Please remove unnecessary stubbings. More info: javadoc for UnnecessaryStubbingException class.",
+ "Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.",
filterLineNo(failure.getException().getMessage()));
}
}
| train | train | 2016-11-12T17:08:33 | "2016-08-29T16:18:39Z" | mockitoguy | train |
mockito/mockito/762_763 | mockito/mockito | mockito/mockito/762 | mockito/mockito/763 | [
"keyword_pr_to_issue"
] | b30b33f8b56605d9dd7711d0b25e704b2e419eed | 235fd4d850a2fe25a2c871bfacf35d7672708e3c | [] | [
"This change does not work, see https://github.com/mockito/mockito/pull/760#issuecomment-261229080\n"
] | "2016-11-17T13:13:53Z" | [
"docs"
] | Public javadoc offers links to internal classes | In few places in public javadoc we offer links to internal classes. Instead, we should document the public API without links to private classes. How to find offenders? Generate javadoc and look for:
- \<code\>ReturnsEmptyValues
- \<code\>org.mockito.internal | [
"build.gradle",
"buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java",
"gradle/javadoc.gradle",
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/configuration/IMockitoConfiguration.java",
"src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [
"build.gradle",
"gradle/javadoc.gradle",
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/configuration/IMockitoConfiguration.java",
"src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [
"subprojects/testng/testng.gradle"
] | diff --git a/build.gradle b/build.gradle
index ada4849ffb..4a6588f14f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -6,7 +6,7 @@ buildscript {
dependencies {
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2' //publishing to bintray
- classpath'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0' // later versions don't work on JDK6
+ classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0' // later versions don't work on JDK6
//Needed so that release notes and release workflow plugin can be applied in separate gradle/*.gradle build files
classpath project.'dependencies.mockito-release-tools'
@@ -103,7 +103,7 @@ task javadocJar(type: Jar) {
baseName = 'mockito-core'
classifier = "javadoc"
with licenseFiles
- from mockitoJavadoc
+ from javadoc
}
task coverageReport(dependsOn: ["test", "mockitoCoverage"]) {}
@@ -165,4 +165,4 @@ compileTestJava.finalizedBy removeTestResources
buildScan {
licenseAgreementUrl = 'https://gradle.com/terms-of-service'
licenseAgree = 'yes'
-}
\ No newline at end of file
+}
diff --git a/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java b/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java
deleted file mode 100644
index 3464f0b426..0000000000
--- a/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package org.mockito.javadoc;
-
-import com.sun.javadoc.*;
-import com.sun.tools.doclets.formats.html.HtmlDoclet;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Doclet built to exclude mockito internal packages from the outputted Javadoc.
- * All methods except the start method are copied from {@link com.sun.tools.doclets.standard.Standard}.
- * Inspired by https://gist.github.com/benjchristensen/1410681
- */
-public class JavadocExclude {
-
- public static int optionLength(String var0) {
- return HtmlDoclet.optionLength(var0);
- }
-
- public static boolean start(RootDoc root) {
- Class clz = root.getClass();
- return HtmlDoclet.start((RootDoc) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), new ExcludeHandler(root)));
- }
-
- public static boolean validOptions(String[][] var0, DocErrorReporter var1) {
- return HtmlDoclet.validOptions(var0, var1);
- }
-
- public static LanguageVersion languageVersion() {
- return HtmlDoclet.languageVersion();
- }
-
- /**
- * Proxy which filters the {@link RootDoc#classes()} method to filter {@link ClassDoc} based on their package name.
- */
- private static class ExcludeHandler implements InvocationHandler {
- private final RootDoc root;
-
- private ExcludeHandler(RootDoc root) {
- this.root = root;
- }
-
- @Override
- public Object invoke(Object o, Method method, Object[] args) throws Throwable {
- Object result = method.invoke(root, args);
- if (result instanceof Object[]) {
- List<ClassDoc> filteredDocs = new ArrayList<ClassDoc>();
- Object[] array = (Object[]) result;
- for (Object entry : array) {
- if (entry instanceof ClassDoc) {
- ClassDoc doc = (ClassDoc) entry;
- if (!doc.containingPackage().name().startsWith("org.mockito.internal")) {
- filteredDocs.add(doc);
- }
- }
- }
- // If no ClassDoc were found in the original array,
- // since PackageDoc area also included in the classes array.
- if (filteredDocs.size() > 0) {
- ClassDoc[] docArray = new ClassDoc[filteredDocs.size()];
- return filteredDocs.toArray(docArray);
- }
- }
- return result;
- }
- }
-}
diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 27aee3d2e6..5bb5203299 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -1,9 +1,7 @@
-//vanilla javadoc task does not work for us and it actually fails on java8
-tasks.javadoc.enabled = false
-
-task mockitoJavadoc(type: Javadoc) {
+//It seems the gradle javadoc task works file by file and as such disable some features of javadoc tool
+//such as link to packages, https://groups.google.com/d/msg/gradle-dev/R83dy_6PHMc/bgw0cUTMFAAJ
+javadoc {
description "Creates javadoc html for Mockito API."
- tasks.javadoc.dependsOn it //so that when the user invokes 'javadoc' right things happen
// For more details on the format
// see https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html
@@ -14,12 +12,26 @@ task mockitoJavadoc(type: Javadoc) {
title = "Mockito ${project.version} API"
def javadocJdk6Hack = "jdk6-project-version-insert.min.js"
- options.doclet "org.mockito.javadoc.JavadocExclude"
- options.docletpath = [rootProject.file('./buildSrc/build/classes/main/')]
+ // The way *gradle* javadoc task works and due to *gradle exclusion* the log output triggers javadoc warning and
+ // errors on internal classes that are not found, non-exhaustive list :
+ //
+ // * import org.mockito.internal.Internal <- error: package org.mockito.internal does not exists
+ // * import org.mockito.internal.Internal.util <- error: static import only from classes and interfaces
+ // * class Public extends Internal <- cannot find symbol
+ // * warning - Tag @linkplain: reference not found: org.mockito.internal.Internal internal stuff
+ // * warning - Tag @link: reference not found: org.mockito.stubbing
+ //
+ // While there's errors the javadoc is still generated without those symbols or links ;
+ // for this reason the javadoc output is suppressed and can be reactivated with --info option.
+ exclude 'org/mockito/internal'
+ logging.captureStandardError LogLevel.INFO
+ logging.captureStandardOutput LogLevel.INFO // suppress "## warnings" message
+
options.docTitle = """<h1><a href="org/mockito/Mockito.html">Click to see examples</a>. Mockito ${project.version} API.</h1>"""
options.windowTitle = "Mockito ${project.version} API"
options.group("Main package", ["org.mockito"])
options.memberLevel = JavadocMemberLevel.PROTECTED
+ options.outputLevel = JavadocOutputLevel.QUIET
options.charSet = 'UTF-8'
options.encoding = 'UTF-8'
options.docEncoding = 'UTF-8'
@@ -30,8 +42,11 @@ task mockitoJavadoc(type: Javadoc) {
options.noIndex = false
options.noNavBar = false
options.noTree = false
- options.links('http://docs.oracle.com/javase/8/docs/api/')
- options.header("""<script>var l = window.location; if (l.protocol === "http" && l.origin.indexOf("javadoc.io") > -1) { l.protocol = "https"; }</script><em id="mockito-version-header-javadoc7-header"><strong>Mockito ${project.version} API</strong></em>""")
+ options.links = ['https://docs.oracle.com/javase/6/docs/api/',
+ 'http://junit.org/junit4/javadoc/4.12/',
+ 'http://hamcrest.org/JavaHamcrest/javadoc/1.3/',
+ 'http://testng.org/javadocs/']
+ options.header("""<em id="mockito-version-header-javadoc7-header"><strong>Mockito ${project.version} API</strong></em>""")
options.footer("""<em id="mockito-version-header-javadoc7-footer"><strong>Mockito ${project.version} API</strong></em>""")
options.bottom("""
<script type="text/javascript" src="{@docRoot}/js/${javadocJdk6Hack}"></script>
@@ -40,9 +55,15 @@ task mockitoJavadoc(type: Javadoc) {
<link rel="stylesheet" type="text/css" href="{@docRoot}/js/highlight-8.6-java/styles/obsidian.css"/>
<script type="text/javascript" src="{@docRoot}/js/index.js" async defer></script>
- """.replaceAll(/\r|\n/, ""))
- options.stylesheetFile file("src/javadoc/stylesheet.css")
-// options.addStringOption('top', 'some html')
+ """.replaceAll(/\r|\n|[ ]{8}/, ""))
+ options.stylesheetFile rootProject.file("src/javadoc/stylesheet.css")
+ options.addStringOption('top', """<script type="text/javascript" >
+ var l = window.location;
+ if (l.protocol === "http" && l.origin.indexOf("javadoc.io") > -1) {
+ l.protocol = "https";
+ }
+ </script>
+ """.replaceAll(/\r|\n|[ ]{8}/, ""))
if (JavaVersion.current().isJava8Compatible()) {
options.addStringOption('Xdoclint:none', '-quiet')
}
diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java
index ade1ce30cf..348743da04 100644
--- a/src/main/java/org/mockito/AdditionalAnswers.java
+++ b/src/main/java/org/mockito/AdditionalAnswers.java
@@ -4,7 +4,6 @@
*/
package org.mockito;
-import static org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces.toAnswer;
import java.util.Collection;
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
import org.mockito.internal.stubbing.answers.ReturnsElementsOf;
@@ -21,12 +20,14 @@
import org.mockito.stubbing.VoidAnswer4;
import org.mockito.stubbing.VoidAnswer5;
+import static org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces.toAnswer;
+
/**
* Additional answers provides factory methods for answers.
*
* <p>Currently offer answers that can return the parameter of an invocation at a certain position,
- * along with answers that draw on a strongly typed interface from {@link org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces}
- * to provide a neater way to write custom answers that either return a value or are void.
+ * along with answers that draw on a strongly typed interface to provide a neater way to write custom answers
+ * that either return a value or are void (see answer interfaces in {@link org.mockito.stubbing}).
*
* <p>See factory methods for more information : {@link #returnsFirstArg}, {@link #returnsSecondArg},
* {@link #returnsLastArg}, {@link #returnsArgAt}, {@link #answer} and {@link #answerVoid}
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 4d759e0ddc..45f6558843 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -8,17 +8,21 @@
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.debugging.MockitoDebuggerImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
import org.mockito.mock.SerializableMode;
-import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.Answer1;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
-import org.mockito.verification.*;
+import org.mockito.stubbing.VoidAnswer1;
+import org.mockito.verification.After;
+import org.mockito.verification.Timeout;
+import org.mockito.verification.VerificationAfterDelay;
+import org.mockito.verification.VerificationMode;
+import org.mockito.verification.VerificationWithTimeout;
/**
* <p align="left"><img src="logo.png" srcset="logo@2x.png 2x" alt="Mockito logo"/></p>
@@ -1154,9 +1158,9 @@
* as Java 8 lambdas. Even in Java 7 and lower these custom answers based on a typed interface can reduce boilerplate.
* In particular, this approach will make it easier to test functions which use callbacks.
*
- * The functions answer and answerVoid can be found in {@link AdditionalAnswers} to create the answer object
- * using the interfaces in {@link org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces} support is provided
- * for functions with up to 5 parameters
+ * The methods {@link AdditionalAnswers#answer(Answer1) answer} and {@link AdditionalAnswers#answerVoid(VoidAnswer1) answerVoid}
+ * can be used to create the answer. They rely on the related answer interfaces in {@link org.mockito.stubbing} that
+ * support answers up to 5 parameters.
*
* <p>
* Examples:
@@ -1187,7 +1191,7 @@
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 7
- * doAnswer(answerVoid(new AnswerFunctionalInterfaces.VoidAnswer2<String, Callback>() {
+ * doAnswer(answerVoid(new VoidAnswer2<String, Callback>() {
* public void answer(String operation, Callback callback) {
* callback.receive("dummy");
* }})).when(mock).execute(anyString(), any(Callback.class));
@@ -1203,7 +1207,7 @@
* .when(mock).execute(anyString(), anyString());
*
* // Java 7
- * doAnswer(answer(new AnswerFunctionalInterfaces.Answer2<String, String, String>() {
+ * doAnswer(answer(new Answer2<String, String, String>() {
* public String answer(String input1, String input2) {
* return input1 + input2;
* }})).when(mock).execute(anyString(), anyString());
@@ -1287,12 +1291,13 @@ public class Mockito extends ArgumentMatchers {
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
+ *
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
- * This implementation first tries the global configuration.
- * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
+ * This implementation first tries the global configuration and if there is no global configuration then
+ * it will use a default answer that returns zeros, empty collections, nulls, etc.
*/
public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
@@ -1306,8 +1311,8 @@ public class Mockito extends ArgumentMatchers {
* This implementation of Answer <b>returns SmartNull instead of null</b>.
* <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
* <p>
- * <code>ReturnsSmartNulls</code> first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
- * then it tries to return SmartNull. If the return type is final then plain null is returned.
+ * <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)
+ * then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.
* <p>
* <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
* <p>
@@ -1335,8 +1340,8 @@ public class Mockito extends ArgumentMatchers {
* <p>
* This implementation can be helpful when working with legacy code.
* <p>
- * ReturnsMocks first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
- * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain null is returned.
+ * ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)
+ * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.
* <p>
*/
public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
diff --git a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
index cebd25f366..2ab19671e8 100644
--- a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
+++ b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
@@ -4,26 +4,36 @@
*/
package org.mockito.configuration;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.stubbing.Answer;
/**
* Use it to configure Mockito. For now there are not many configuration options but it may change in future.
+ *
* <p>
- * In most cases you don't really need to configure Mockito. For example in case of working with legacy code,
+ * In most cases you don't really need to configure Mockito. For example in case of working with legacy code,
* when you might want to have different 'mocking style' this interface might be helpful.
- * A reason of configuring Mockito might be if you disagree with the {@link ReturnsEmptyValues} unstubbed mocks return.
+ * A reason of configuring Mockito might be if you disagree with the {@link org.mockito.Answers#RETURNS_DEFAULTS}
+ * unstubbed mocks return.
+ *
* <p>
- * To configure Mockito create exactly <b>org.mockito.configuration.MockitoConfiguration</b> class that implements this interface.
+ * To configure Mockito create exactly <b>org.mockito.configuration.MockitoConfiguration</b> class
+ * that implements this interface.
+ *
* <p>
- * Configuring Mockito is completely <b>optional</b> - nothing happens if there isn't any <b>org.mockito.configuration.MockitoConfiguration</b> on the classpath.
+ * Configuring Mockito is completely <b>optional</b> - nothing happens if there isn't any
+ * <b>org.mockito.configuration.MockitoConfiguration</b> on the classpath.
+ *
* <p>
- * <b>org.mockito.configuration.MockitoConfiguration</b> must implement IMockitoConfiguration or extend {@link DefaultMockitoConfiguration}
+ * <b>org.mockito.configuration.MockitoConfiguration</b> must implement <code>IMockitoConfiguration</code> or
+ * extend {@link DefaultMockitoConfiguration}
+ *
* <p>
- * Mockito will store single instance of org.mockito.configuration.MockitoConfiguration per thread (using ThreadLocal).
+ * Mockito will store single instance of <code>org.mockito.configuration.MockitoConfiguration</code>
+ * per thread (using <code>ThreadLocal</code>).
* For sanity of your tests, don't make the implementation stateful.
+ *
* <p>
- * If you have comments on Mockito configuration feature don't hesitate to write to mockito@googlegroups.com
+ * If you have comments on Mockito configuration feature don't hesitate to write to mockito@googlegroups.com.
*/
public interface IMockitoConfiguration {
@@ -57,4 +67,4 @@ public interface IMockitoConfiguration {
* are dynamically reloaded, you can disable this to avoid classcast exceptions.
*/
boolean enableClassCache();
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java b/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
index af44a63914..a3229a8c80 100644
--- a/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
+++ b/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
@@ -9,14 +9,12 @@
* Mockito stack trace filtering mechanism uses this information.
* <p>
* Excluding an element will make it not show in the cleaned stack trace.
- * Not-excluding an element does not guarantee it will be shown
- * (e.g. it depends on the implementation of
- * Mockito internal {@link org.mockito.internal.exceptions.stacktrace.StackTraceFilter}).
+ * Not-excluding an element does not guarantee it will be shown (e.g. it depends on the implementation of
+ * {@linkplain org.mockito.internal.exceptions.stacktrace.StackTraceFilter Mockito internal cleaner}).
* <p>
- * The implementations are required to be thread safe. For example, make them stateless.
+ * The implementations are required to be thread safe ; for example, make them stateless.
* <p>
- * See the default implementation: {@link org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleaner}.
- *
+ * See also the {@linkplain org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleaner Mockito default implementation}
*/
public interface StackTraceCleaner {
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
index 2c20525057..179f7ddc8b 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
@@ -5,13 +5,12 @@
package org.mockito.internal.stubbing.defaultanswers;
+import java.io.Serializable;
+import java.lang.reflect.Array;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.io.Serializable;
-import java.lang.reflect.Array;
-
/**
* It's likely this implementation will be used by default by every Mockito 3.0.0 mock.
* <p>
@@ -67,9 +66,9 @@ Object returnValueFor(Class<?> type) {
if (type == String.class) {
return "";
} else if (type.isArray()) {
- Class<?> componenetType = type.getComponentType();
- return Array.newInstance(componenetType, 0);
+ Class<?> componentType = type.getComponentType();
+ return Array.newInstance(componentType, 0);
}
return null;
}
-}
\ No newline at end of file
+}
| diff --git a/subprojects/testng/testng.gradle b/subprojects/testng/testng.gradle
index 42f2c1a17c..ac90dac0eb 100644
--- a/subprojects/testng/testng.gradle
+++ b/subprojects/testng/testng.gradle
@@ -35,6 +35,8 @@ artifacts {
archives sourcesJar
}
+tasks.javadoc.enabled = false
+
uploadArchives {
repositories {
mavenDeployer {
@@ -53,4 +55,4 @@ test {
useTestNG() {
suites file('src/test/resources/mockito-testng.xml')
}
-}
\ No newline at end of file
+}
| train | train | 2016-11-17T13:41:02 | "2016-11-17T05:52:17Z" | mockitoguy | train |
mockito/mockito/755_763 | mockito/mockito | mockito/mockito/755 | mockito/mockito/763 | [
"keyword_issue_to_pr"
] | b30b33f8b56605d9dd7711d0b25e704b2e419eed | 235fd4d850a2fe25a2c871bfacf35d7672708e3c | [
"Was fixed in #763"
] | [
"This change does not work, see https://github.com/mockito/mockito/pull/760#issuecomment-261229080\n"
] | "2016-11-17T13:13:53Z" | [
"docs"
] | Tidy-up javadoc generation | I investigated the need for Javadoc doclet rule that currently is kept in buildSrc.
- currently, some javadoc links from public API lead to internal API, which gives 404 error (search for ReturnEmptyValues in public Mockito.html, click the link, 404).
- excluding files at the Javadoc task level does not prevent Javadoc from being generated for the internal classes. However, it does turn links to private API into non-clickable \<code\>\</code\> links.
I'm tempted to just start generating Javadoc for internals, and be very explicit that internal API is not intended for public use and can be changed at any time. Thoughts? | [
"build.gradle",
"buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java",
"gradle/javadoc.gradle",
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/configuration/IMockitoConfiguration.java",
"src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [
"build.gradle",
"gradle/javadoc.gradle",
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/configuration/IMockitoConfiguration.java",
"src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [
"subprojects/testng/testng.gradle"
] | diff --git a/build.gradle b/build.gradle
index ada4849ffb..4a6588f14f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -6,7 +6,7 @@ buildscript {
dependencies {
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2' //publishing to bintray
- classpath'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0' // later versions don't work on JDK6
+ classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0' // later versions don't work on JDK6
//Needed so that release notes and release workflow plugin can be applied in separate gradle/*.gradle build files
classpath project.'dependencies.mockito-release-tools'
@@ -103,7 +103,7 @@ task javadocJar(type: Jar) {
baseName = 'mockito-core'
classifier = "javadoc"
with licenseFiles
- from mockitoJavadoc
+ from javadoc
}
task coverageReport(dependsOn: ["test", "mockitoCoverage"]) {}
@@ -165,4 +165,4 @@ compileTestJava.finalizedBy removeTestResources
buildScan {
licenseAgreementUrl = 'https://gradle.com/terms-of-service'
licenseAgree = 'yes'
-}
\ No newline at end of file
+}
diff --git a/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java b/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java
deleted file mode 100644
index 3464f0b426..0000000000
--- a/buildSrc/src/main/java/org/mockito/javadoc/JavadocExclude.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package org.mockito.javadoc;
-
-import com.sun.javadoc.*;
-import com.sun.tools.doclets.formats.html.HtmlDoclet;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Doclet built to exclude mockito internal packages from the outputted Javadoc.
- * All methods except the start method are copied from {@link com.sun.tools.doclets.standard.Standard}.
- * Inspired by https://gist.github.com/benjchristensen/1410681
- */
-public class JavadocExclude {
-
- public static int optionLength(String var0) {
- return HtmlDoclet.optionLength(var0);
- }
-
- public static boolean start(RootDoc root) {
- Class clz = root.getClass();
- return HtmlDoclet.start((RootDoc) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), new ExcludeHandler(root)));
- }
-
- public static boolean validOptions(String[][] var0, DocErrorReporter var1) {
- return HtmlDoclet.validOptions(var0, var1);
- }
-
- public static LanguageVersion languageVersion() {
- return HtmlDoclet.languageVersion();
- }
-
- /**
- * Proxy which filters the {@link RootDoc#classes()} method to filter {@link ClassDoc} based on their package name.
- */
- private static class ExcludeHandler implements InvocationHandler {
- private final RootDoc root;
-
- private ExcludeHandler(RootDoc root) {
- this.root = root;
- }
-
- @Override
- public Object invoke(Object o, Method method, Object[] args) throws Throwable {
- Object result = method.invoke(root, args);
- if (result instanceof Object[]) {
- List<ClassDoc> filteredDocs = new ArrayList<ClassDoc>();
- Object[] array = (Object[]) result;
- for (Object entry : array) {
- if (entry instanceof ClassDoc) {
- ClassDoc doc = (ClassDoc) entry;
- if (!doc.containingPackage().name().startsWith("org.mockito.internal")) {
- filteredDocs.add(doc);
- }
- }
- }
- // If no ClassDoc were found in the original array,
- // since PackageDoc area also included in the classes array.
- if (filteredDocs.size() > 0) {
- ClassDoc[] docArray = new ClassDoc[filteredDocs.size()];
- return filteredDocs.toArray(docArray);
- }
- }
- return result;
- }
- }
-}
diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle
index 27aee3d2e6..5bb5203299 100644
--- a/gradle/javadoc.gradle
+++ b/gradle/javadoc.gradle
@@ -1,9 +1,7 @@
-//vanilla javadoc task does not work for us and it actually fails on java8
-tasks.javadoc.enabled = false
-
-task mockitoJavadoc(type: Javadoc) {
+//It seems the gradle javadoc task works file by file and as such disable some features of javadoc tool
+//such as link to packages, https://groups.google.com/d/msg/gradle-dev/R83dy_6PHMc/bgw0cUTMFAAJ
+javadoc {
description "Creates javadoc html for Mockito API."
- tasks.javadoc.dependsOn it //so that when the user invokes 'javadoc' right things happen
// For more details on the format
// see https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html
@@ -14,12 +12,26 @@ task mockitoJavadoc(type: Javadoc) {
title = "Mockito ${project.version} API"
def javadocJdk6Hack = "jdk6-project-version-insert.min.js"
- options.doclet "org.mockito.javadoc.JavadocExclude"
- options.docletpath = [rootProject.file('./buildSrc/build/classes/main/')]
+ // The way *gradle* javadoc task works and due to *gradle exclusion* the log output triggers javadoc warning and
+ // errors on internal classes that are not found, non-exhaustive list :
+ //
+ // * import org.mockito.internal.Internal <- error: package org.mockito.internal does not exists
+ // * import org.mockito.internal.Internal.util <- error: static import only from classes and interfaces
+ // * class Public extends Internal <- cannot find symbol
+ // * warning - Tag @linkplain: reference not found: org.mockito.internal.Internal internal stuff
+ // * warning - Tag @link: reference not found: org.mockito.stubbing
+ //
+ // While there's errors the javadoc is still generated without those symbols or links ;
+ // for this reason the javadoc output is suppressed and can be reactivated with --info option.
+ exclude 'org/mockito/internal'
+ logging.captureStandardError LogLevel.INFO
+ logging.captureStandardOutput LogLevel.INFO // suppress "## warnings" message
+
options.docTitle = """<h1><a href="org/mockito/Mockito.html">Click to see examples</a>. Mockito ${project.version} API.</h1>"""
options.windowTitle = "Mockito ${project.version} API"
options.group("Main package", ["org.mockito"])
options.memberLevel = JavadocMemberLevel.PROTECTED
+ options.outputLevel = JavadocOutputLevel.QUIET
options.charSet = 'UTF-8'
options.encoding = 'UTF-8'
options.docEncoding = 'UTF-8'
@@ -30,8 +42,11 @@ task mockitoJavadoc(type: Javadoc) {
options.noIndex = false
options.noNavBar = false
options.noTree = false
- options.links('http://docs.oracle.com/javase/8/docs/api/')
- options.header("""<script>var l = window.location; if (l.protocol === "http" && l.origin.indexOf("javadoc.io") > -1) { l.protocol = "https"; }</script><em id="mockito-version-header-javadoc7-header"><strong>Mockito ${project.version} API</strong></em>""")
+ options.links = ['https://docs.oracle.com/javase/6/docs/api/',
+ 'http://junit.org/junit4/javadoc/4.12/',
+ 'http://hamcrest.org/JavaHamcrest/javadoc/1.3/',
+ 'http://testng.org/javadocs/']
+ options.header("""<em id="mockito-version-header-javadoc7-header"><strong>Mockito ${project.version} API</strong></em>""")
options.footer("""<em id="mockito-version-header-javadoc7-footer"><strong>Mockito ${project.version} API</strong></em>""")
options.bottom("""
<script type="text/javascript" src="{@docRoot}/js/${javadocJdk6Hack}"></script>
@@ -40,9 +55,15 @@ task mockitoJavadoc(type: Javadoc) {
<link rel="stylesheet" type="text/css" href="{@docRoot}/js/highlight-8.6-java/styles/obsidian.css"/>
<script type="text/javascript" src="{@docRoot}/js/index.js" async defer></script>
- """.replaceAll(/\r|\n/, ""))
- options.stylesheetFile file("src/javadoc/stylesheet.css")
-// options.addStringOption('top', 'some html')
+ """.replaceAll(/\r|\n|[ ]{8}/, ""))
+ options.stylesheetFile rootProject.file("src/javadoc/stylesheet.css")
+ options.addStringOption('top', """<script type="text/javascript" >
+ var l = window.location;
+ if (l.protocol === "http" && l.origin.indexOf("javadoc.io") > -1) {
+ l.protocol = "https";
+ }
+ </script>
+ """.replaceAll(/\r|\n|[ ]{8}/, ""))
if (JavaVersion.current().isJava8Compatible()) {
options.addStringOption('Xdoclint:none', '-quiet')
}
diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java
index ade1ce30cf..348743da04 100644
--- a/src/main/java/org/mockito/AdditionalAnswers.java
+++ b/src/main/java/org/mockito/AdditionalAnswers.java
@@ -4,7 +4,6 @@
*/
package org.mockito;
-import static org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces.toAnswer;
import java.util.Collection;
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
import org.mockito.internal.stubbing.answers.ReturnsElementsOf;
@@ -21,12 +20,14 @@
import org.mockito.stubbing.VoidAnswer4;
import org.mockito.stubbing.VoidAnswer5;
+import static org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces.toAnswer;
+
/**
* Additional answers provides factory methods for answers.
*
* <p>Currently offer answers that can return the parameter of an invocation at a certain position,
- * along with answers that draw on a strongly typed interface from {@link org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces}
- * to provide a neater way to write custom answers that either return a value or are void.
+ * along with answers that draw on a strongly typed interface to provide a neater way to write custom answers
+ * that either return a value or are void (see answer interfaces in {@link org.mockito.stubbing}).
*
* <p>See factory methods for more information : {@link #returnsFirstArg}, {@link #returnsSecondArg},
* {@link #returnsLastArg}, {@link #returnsArgAt}, {@link #answer} and {@link #answerVoid}
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 4d759e0ddc..45f6558843 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -8,17 +8,21 @@
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.debugging.MockitoDebuggerImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
import org.mockito.mock.SerializableMode;
-import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.Answer1;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
-import org.mockito.verification.*;
+import org.mockito.stubbing.VoidAnswer1;
+import org.mockito.verification.After;
+import org.mockito.verification.Timeout;
+import org.mockito.verification.VerificationAfterDelay;
+import org.mockito.verification.VerificationMode;
+import org.mockito.verification.VerificationWithTimeout;
/**
* <p align="left"><img src="logo.png" srcset="logo@2x.png 2x" alt="Mockito logo"/></p>
@@ -1154,9 +1158,9 @@
* as Java 8 lambdas. Even in Java 7 and lower these custom answers based on a typed interface can reduce boilerplate.
* In particular, this approach will make it easier to test functions which use callbacks.
*
- * The functions answer and answerVoid can be found in {@link AdditionalAnswers} to create the answer object
- * using the interfaces in {@link org.mockito.internal.stubbing.answers.AnswerFunctionalInterfaces} support is provided
- * for functions with up to 5 parameters
+ * The methods {@link AdditionalAnswers#answer(Answer1) answer} and {@link AdditionalAnswers#answerVoid(VoidAnswer1) answerVoid}
+ * can be used to create the answer. They rely on the related answer interfaces in {@link org.mockito.stubbing} that
+ * support answers up to 5 parameters.
*
* <p>
* Examples:
@@ -1187,7 +1191,7 @@
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 7
- * doAnswer(answerVoid(new AnswerFunctionalInterfaces.VoidAnswer2<String, Callback>() {
+ * doAnswer(answerVoid(new VoidAnswer2<String, Callback>() {
* public void answer(String operation, Callback callback) {
* callback.receive("dummy");
* }})).when(mock).execute(anyString(), any(Callback.class));
@@ -1203,7 +1207,7 @@
* .when(mock).execute(anyString(), anyString());
*
* // Java 7
- * doAnswer(answer(new AnswerFunctionalInterfaces.Answer2<String, String, String>() {
+ * doAnswer(answer(new Answer2<String, String, String>() {
* public String answer(String input1, String input2) {
* return input1 + input2;
* }})).when(mock).execute(anyString(), anyString());
@@ -1287,12 +1291,13 @@ public class Mockito extends ArgumentMatchers {
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
+ *
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
- * This implementation first tries the global configuration.
- * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
+ * This implementation first tries the global configuration and if there is no global configuration then
+ * it will use a default answer that returns zeros, empty collections, nulls, etc.
*/
public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
@@ -1306,8 +1311,8 @@ public class Mockito extends ArgumentMatchers {
* This implementation of Answer <b>returns SmartNull instead of null</b>.
* <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
* <p>
- * <code>ReturnsSmartNulls</code> first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
- * then it tries to return SmartNull. If the return type is final then plain null is returned.
+ * <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)
+ * then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.
* <p>
* <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
* <p>
@@ -1335,8 +1340,8 @@ public class Mockito extends ArgumentMatchers {
* <p>
* This implementation can be helpful when working with legacy code.
* <p>
- * ReturnsMocks first tries to return ordinary return values (see {@link ReturnsMoreEmptyValues})
- * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain null is returned.
+ * ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)
+ * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.
* <p>
*/
public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
diff --git a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
index cebd25f366..2ab19671e8 100644
--- a/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
+++ b/src/main/java/org/mockito/configuration/IMockitoConfiguration.java
@@ -4,26 +4,36 @@
*/
package org.mockito.configuration;
-import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
import org.mockito.stubbing.Answer;
/**
* Use it to configure Mockito. For now there are not many configuration options but it may change in future.
+ *
* <p>
- * In most cases you don't really need to configure Mockito. For example in case of working with legacy code,
+ * In most cases you don't really need to configure Mockito. For example in case of working with legacy code,
* when you might want to have different 'mocking style' this interface might be helpful.
- * A reason of configuring Mockito might be if you disagree with the {@link ReturnsEmptyValues} unstubbed mocks return.
+ * A reason of configuring Mockito might be if you disagree with the {@link org.mockito.Answers#RETURNS_DEFAULTS}
+ * unstubbed mocks return.
+ *
* <p>
- * To configure Mockito create exactly <b>org.mockito.configuration.MockitoConfiguration</b> class that implements this interface.
+ * To configure Mockito create exactly <b>org.mockito.configuration.MockitoConfiguration</b> class
+ * that implements this interface.
+ *
* <p>
- * Configuring Mockito is completely <b>optional</b> - nothing happens if there isn't any <b>org.mockito.configuration.MockitoConfiguration</b> on the classpath.
+ * Configuring Mockito is completely <b>optional</b> - nothing happens if there isn't any
+ * <b>org.mockito.configuration.MockitoConfiguration</b> on the classpath.
+ *
* <p>
- * <b>org.mockito.configuration.MockitoConfiguration</b> must implement IMockitoConfiguration or extend {@link DefaultMockitoConfiguration}
+ * <b>org.mockito.configuration.MockitoConfiguration</b> must implement <code>IMockitoConfiguration</code> or
+ * extend {@link DefaultMockitoConfiguration}
+ *
* <p>
- * Mockito will store single instance of org.mockito.configuration.MockitoConfiguration per thread (using ThreadLocal).
+ * Mockito will store single instance of <code>org.mockito.configuration.MockitoConfiguration</code>
+ * per thread (using <code>ThreadLocal</code>).
* For sanity of your tests, don't make the implementation stateful.
+ *
* <p>
- * If you have comments on Mockito configuration feature don't hesitate to write to mockito@googlegroups.com
+ * If you have comments on Mockito configuration feature don't hesitate to write to mockito@googlegroups.com.
*/
public interface IMockitoConfiguration {
@@ -57,4 +67,4 @@ public interface IMockitoConfiguration {
* are dynamically reloaded, you can disable this to avoid classcast exceptions.
*/
boolean enableClassCache();
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java b/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
index af44a63914..a3229a8c80 100644
--- a/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
+++ b/src/main/java/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
@@ -9,14 +9,12 @@
* Mockito stack trace filtering mechanism uses this information.
* <p>
* Excluding an element will make it not show in the cleaned stack trace.
- * Not-excluding an element does not guarantee it will be shown
- * (e.g. it depends on the implementation of
- * Mockito internal {@link org.mockito.internal.exceptions.stacktrace.StackTraceFilter}).
+ * Not-excluding an element does not guarantee it will be shown (e.g. it depends on the implementation of
+ * {@linkplain org.mockito.internal.exceptions.stacktrace.StackTraceFilter Mockito internal cleaner}).
* <p>
- * The implementations are required to be thread safe. For example, make them stateless.
+ * The implementations are required to be thread safe ; for example, make them stateless.
* <p>
- * See the default implementation: {@link org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleaner}.
- *
+ * See also the {@linkplain org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleaner Mockito default implementation}
*/
public interface StackTraceCleaner {
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
index 2c20525057..179f7ddc8b 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
@@ -5,13 +5,12 @@
package org.mockito.internal.stubbing.defaultanswers;
+import java.io.Serializable;
+import java.lang.reflect.Array;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.io.Serializable;
-import java.lang.reflect.Array;
-
/**
* It's likely this implementation will be used by default by every Mockito 3.0.0 mock.
* <p>
@@ -67,9 +66,9 @@ Object returnValueFor(Class<?> type) {
if (type == String.class) {
return "";
} else if (type.isArray()) {
- Class<?> componenetType = type.getComponentType();
- return Array.newInstance(componenetType, 0);
+ Class<?> componentType = type.getComponentType();
+ return Array.newInstance(componentType, 0);
}
return null;
}
-}
\ No newline at end of file
+}
| diff --git a/subprojects/testng/testng.gradle b/subprojects/testng/testng.gradle
index 42f2c1a17c..ac90dac0eb 100644
--- a/subprojects/testng/testng.gradle
+++ b/subprojects/testng/testng.gradle
@@ -35,6 +35,8 @@ artifacts {
archives sourcesJar
}
+tasks.javadoc.enabled = false
+
uploadArchives {
repositories {
mavenDeployer {
@@ -53,4 +55,4 @@ test {
useTestNG() {
suites file('src/test/resources/mockito-testng.xml')
}
-}
\ No newline at end of file
+}
| val | train | 2016-11-17T13:41:02 | "2016-11-14T05:29:00Z" | mockitoguy | train |
mockito/mockito/781_782 | mockito/mockito | mockito/mockito/781 | mockito/mockito/782 | [
"timestamp(timedelta=1.0, similarity=0.9228255909277773)"
] | 2e0533f3ed48ea838cf38a7dbeaaf4bcc11317b8 | db40b8c2fb5436c47da33c753bf3c6482de8460f | [
"When mockito runs on Java 8 it already provide default answers for `Optional` / `Stream`",
"I tested that before filing this issue; that's true for `Optional`, but not for `OptionalInt` and friends.",
"Oh ok I read too fast the issue description. Sorry ;)\r\n\r\nlooking forward the PR.",
"No worries :). PR filed: #782.",
"NB: I opened this ticket before opening the PR only because the contribution guidelines [state](https://github.com/mockito/mockito/blob/release/2.x/.github/CONTRIBUTING.md) that at least one commit must be of the form `Fixes #id :`. But it seems a number of PRs (like the aforementioned #429) don't follow this guideline. Also, the guidelines indicate there should be a colon after the issue ID, but that rule seems to be followed \"almost never\". So what's your current view on this?",
"@Stephan202 Sorry for the late reply, I'm in the middle of painful refactoring at work.\r\n\r\nWell this generally apply when there's a separate issue either because it's the same person, or because there's delay between the issue and the pull request, but you can propose a pull request that fixes an issue, that's ok, just as long as you describe properly the problem or motivate properly the change ;)"
] | [
"It just asks to simplify it with parameterized tests, e.g. with https://github.com/Pragmatists/JUnitParams/wiki/Quickstart . @Stephan202, would you dare to do it? ;)",
"@szpak: I'm fine opening an extra PR, but I think the Mockito team should first decide on which parameterized test framework to use. The one you linked is an option, but JUnit also comes with built-in support for [`@RunWith(Theories.class)`](https://github.com/junit-team/junit4/wiki/Theories) and [`@RunWith(Parameterized.class)`](https://github.com/junit-team/junit4/wiki/parameterized-tests). There may be others, and it seems right now none of these approaches are used.\r\n\r\nAlternatively, the test duplication can be avoided as follows:\r\n```diff\r\ndiff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java\r\nindex 480a9a1..ab9aad9 100644\r\n--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java\r\n+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java\r\n@@ -90,70 +90,32 @@ public class ReturnsEmptyValuesTest extends TestBase {\r\n \r\n @Test\r\n public void should_return_empty_Optional() throws Exception {\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.Stream\");\r\n-\r\n- //given\r\n- Object stream = mock(streamType);\r\n- Object optional = streamType.getMethod(\"findAny\").invoke(stream);\r\n- assertNotNull(optional);\r\n- assertFalse((Boolean) Class.forName(\"java.util.Optional\").getMethod(\"isPresent\").invoke(optional));\r\n-\r\n- Invocation findAny = this.getLastInvocation();\r\n-\r\n- //when\r\n- Object result = values.answer(findAny);\r\n-\r\n- //then\r\n- assertEquals(optional, result);\r\n+ verify_empty_Optional_is_returned(\"java.util.stream.Stream\", \"java.util.Optional\");\r\n }\r\n \r\n @Test\r\n public void should_return_empty_OptionalDouble() throws Exception {\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.DoubleStream\");\r\n-\r\n- //given\r\n- Object stream = mock(streamType);\r\n- Object optional = streamType.getMethod(\"findAny\").invoke(stream);\r\n- assertNotNull(optional);\r\n- assertFalse((Boolean) Class.forName(\"java.util.OptionalDouble\").getMethod(\"isPresent\").invoke(optional));\r\n-\r\n- Invocation findAny = this.getLastInvocation();\r\n-\r\n- //when\r\n- Object result = values.answer(findAny);\r\n-\r\n- //then\r\n- assertEquals(optional, result);\r\n+ verify_empty_Optional_is_returned(\"java.util.stream.DoubleStream\", \"java.util.OptionalDouble\");\r\n }\r\n \r\n @Test\r\n public void should_return_empty_OptionalInt() throws Exception {\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.IntStream\");\r\n-\r\n- //given\r\n- Object stream = mock(streamType);\r\n- Object optional = streamType.getMethod(\"findAny\").invoke(stream);\r\n- assertNotNull(optional);\r\n- assertFalse((Boolean) Class.forName(\"java.util.OptionalInt\").getMethod(\"isPresent\").invoke(optional));\r\n-\r\n- Invocation findAny = this.getLastInvocation();\r\n-\r\n- //when\r\n- Object result = values.answer(findAny);\r\n-\r\n- //then\r\n- assertEquals(optional, result);\r\n+ verify_empty_Optional_is_returned(\"java.util.stream.IntStream\", \"java.util.OptionalInt\");\r\n }\r\n \r\n @Test\r\n public void should_return_empty_OptionalLong() throws Exception {\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.LongStream\");\r\n+ verify_empty_Optional_is_returned(\"java.util.stream.LongStream\", \"java.util.OptionalLong\");\r\n+ }\r\n+\r\n+ private void verify_empty_Optional_is_returned(String streamFqcn, String optionalFqcn) throws Exception {\r\n+ Class<?> streamType = getClassOrSkipTest(streamFqcn);\r\n \r\n //given\r\n Object stream = mock(streamType);\r\n Object optional = streamType.getMethod(\"findAny\").invoke(stream);\r\n assertNotNull(optional);\r\n- assertFalse((Boolean) Class.forName(\"java.util.OptionalLong\").getMethod(\"isPresent\").invoke(optional));\r\n+ assertFalse((Boolean) Class.forName(optionalFqcn).getMethod(\"isPresent\").invoke(optional));\r\n \r\n Invocation findAny = this.getLastInvocation();\r\n \r\n@@ -166,54 +128,34 @@ public class ReturnsEmptyValuesTest extends TestBase {\r\n \r\n @Test\r\n public void should_return_empty_Stream() throws Exception {\r\n- // given\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.Stream\");\r\n-\r\n- // when\r\n- Object stream = values.returnValueFor(streamType);\r\n- long count = (Long) streamType.getMethod(\"count\").invoke(stream);\r\n-\r\n- // then\r\n- assertEquals(\"count of empty Stream\", 0L, count);\r\n+ verify_empty_Stream_is_returned(\"java.util.stream.Stream\");\r\n }\r\n \r\n @Test\r\n public void should_return_empty_DoubleStream() throws Exception {\r\n- // given\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.DoubleStream\");\r\n-\r\n- // when\r\n- Object stream = values.returnValueFor(streamType);\r\n- long count = (Long) streamType.getMethod(\"count\").invoke(stream);\r\n-\r\n- // then\r\n- assertEquals(\"count of empty DoubleStream\", 0L, count);\r\n+ verify_empty_Stream_is_returned(\"java.util.stream.DoubleStream\");\r\n }\r\n \r\n @Test\r\n public void should_return_empty_IntStream() throws Exception {\r\n- // given\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.IntStream\");\r\n-\r\n- // when\r\n- Object stream = values.returnValueFor(streamType);\r\n- long count = (Long) streamType.getMethod(\"count\").invoke(stream);\r\n-\r\n- // then\r\n- assertEquals(\"count of empty IntStream\", 0L, count);\r\n+ verify_empty_Stream_is_returned(\"java.util.stream.IntStream\");\r\n }\r\n \r\n @Test\r\n public void should_return_empty_LongStream() throws Exception {\r\n+ verify_empty_Stream_is_returned(\"java.util.stream.LongStream\");\r\n+ }\r\n+\r\n+ private void verify_empty_Stream_is_returned(String streamFqcn) throws Exception {\r\n // given\r\n- Class<?> streamType = getClassOrSkipTest(\"java.util.stream.LongStream\");\r\n+ Class<?> streamType = getClassOrSkipTest(streamFqcn);\r\n \r\n // when\r\n Object stream = values.returnValueFor(streamType);\r\n long count = (Long) streamType.getMethod(\"count\").invoke(stream);\r\n \r\n // then\r\n- assertEquals(\"count of empty LongStream\", 0L, count);\r\n+ assertEquals(\"count of empty \" + streamFqcn, 0L, count);\r\n }\r\n \r\n /**\r\n```\r\n",
"I think that your proposed refactor is sufficient enough.",
"It's a poor man's parameterized tests, but just for that case it is probably enough.\r\n\r\nBtw, I haven't used `Theories`, but `Parameterized` from JUnit is very verbose and limited. To define one parameterized test you need to sacrifice the whole class (you need to use fields and a constructor). There's no way to create more than one parameterized test in the same test class (which very often is very handy). JUnitParams is much more flexible (no to mentioned Spock brings it to the another level :) ).",
"Alright, pending a decision on which framework to use, I opened PR #783 with the changes shown above.\r\n\r\n(Regarding Spock: my colleague @zshamrock gave a presentation/demo about that just last Thursday. It does look like a perfect fit for this sort of thing indeed.)",
"Is this a breaking change?",
"Well it's a behavioural change, so by definition one can write a test that passed prior but not afterwards. For this particular change that'd look something like the following:\r\n\r\n1. One has a class `C` with a method `m` returning `OptionalDouble`.\r\n2. One mocks `C`, producing an instance `c`.\r\n3. One fails to explicitly mock the behaviour of `c.m`.\r\n4. One uses `c` in some code that invokes `c.m` and relies on the result being `null`.\r\n\r\nI think the \"breakage\" in this case is acceptable for the following reasons:\r\n\r\n1. Since values of type `Optional*` should never be `null`, the failure points out a misuse of `Optional*`, and as such does the user a favour.\r\n2. If one insists on a \"nullable `Optional*`\", adding a simple mock statement in step 3 above clearly documents that contract, consistent with the [principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment).\r\n3. More generally, if a test crucially relies on a certain method's return value, then it's good practise to document this precondition explicitly.\r\n\r\nI feel the above arguments apply to `Stream*` as much as they do to `Optional*`, because a stream is a (proto) collection in some sense, and nullable collections are also decidedly an anti-pattern. WDYT?",
"Your change is really good, it improves Mockito behavior for Java8!\r\n\r\nRegardless of the final decision whether to merge it or not, I find it disturbing that it wasn't discussed as a breaking change in this PR. @bric3, @TimvdLippe thoughts?",
"To be honest, I had not realised this. Especially because I dont think someone relies on the previous null behavior.\r\n\r\nNonetheless we should have discussed this, good point.",
"JUnitParams is fine, I have nothing against, let's go for it, test readability and maintainability is just as important as production code.",
"Well my reasoning was fast : \r\n\r\n1. We forgot that in mockito 2, as a user I usually see that as a bug.\r\n2. The change is consistent with the goal of mockito 2 aka support java 8 best way.\r\n3. The change is breaking for users that uses primitive variant and that expect null for these stubs, which is not what those type are made for, so pretty rare.\r\n\r\nAll in a all this a reasonable change, that imo does not mean mockito should bump any version or postpone the change."
] | "2016-11-25T17:56:09Z" | [] | Add default answers for java.util.Optional{Double,Int,Long} and java.util.stream.{Double,Int,Long}Stream | A natural generalization of #191 and #429 is to add default answers for the primitive `Optional` and `Stream` variants as well. I'm working on a PR proposal; will file soonish. | [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java",
"src/main/java/org/mockito/internal/util/JavaEightUtil.java"
] | [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java",
"src/main/java/org/mockito/internal/util/JavaEightUtil.java"
] | [
"src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
index 58e40c2c01..2216cca7aa 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
@@ -37,7 +37,10 @@
* Returns zero if references are equals otherwise non-zero for Comparable#compareTo(T other) method (see issue 184)
* </li>
* <li>
- * Returns an {@code java.util.Optional#empty() empty Optional} for Optional (see issue 191).
+ * Returns an {@code java.util.Optional#empty() empty Optional} for Optional. Similarly for primitive optional variants.
+ * </li>
+ * <li>
+ * Returns an {@code java.util.stream.Stream#empty() empty Stream} for Stream. Similarly for primitive stream variants.
* </li>
* <li>
* Returns null for everything else
@@ -109,8 +112,20 @@ Object returnValueFor(Class<?> type) {
return new LinkedHashMap<Object, Object>();
} else if ("java.util.Optional".equals(type.getName())) {
return JavaEightUtil.emptyOptional();
+ } else if ("java.util.OptionalDouble".equals(type.getName())) {
+ return JavaEightUtil.emptyOptionalDouble();
+ } else if ("java.util.OptionalInt".equals(type.getName())) {
+ return JavaEightUtil.emptyOptionalInt();
+ } else if ("java.util.OptionalLong".equals(type.getName())) {
+ return JavaEightUtil.emptyOptionalLong();
} else if ("java.util.stream.Stream".equals(type.getName())) {
return JavaEightUtil.emptyStream();
+ } else if ("java.util.stream.DoubleStream".equals(type.getName())) {
+ return JavaEightUtil.emptyDoubleStream();
+ } else if ("java.util.stream.IntStream".equals(type.getName())) {
+ return JavaEightUtil.emptyIntStream();
+ } else if ("java.util.stream.LongStream".equals(type.getName())) {
+ return JavaEightUtil.emptyLongStream();
}
//Let's not care about the rest of collections.
diff --git a/src/main/java/org/mockito/internal/util/JavaEightUtil.java b/src/main/java/org/mockito/internal/util/JavaEightUtil.java
index f09ae7dcde..80ac6353c1 100644
--- a/src/main/java/org/mockito/internal/util/JavaEightUtil.java
+++ b/src/main/java/org/mockito/internal/util/JavaEightUtil.java
@@ -14,16 +14,18 @@
*/
public final class JavaEightUtil {
- // No need for volatile, Optional#empty() is already a safe singleton.
+ // No need for volatile, these optionals are already safe singletons.
private static Object emptyOptional;
+ private static Object emptyOptionalDouble;
+ private static Object emptyOptionalInt;
+ private static Object emptyOptionalLong;
private JavaEightUtil() {
// utility class
}
/**
- * Creates an empty Optional using reflection to stay backwards-compatible with older
- * JDKs (see issue 191).
+ * Creates an empty Optional using reflection to stay backwards-compatible with older JDKs.
*
* @return an empty Optional.
*/
@@ -33,35 +35,110 @@ public static Object emptyOptional() {
return emptyOptional;
}
- try {
- final Class<?> optionalClass = Class.forName("java.util.Optional");
- final Method emptyMethod = optionalClass.getMethod("empty");
+ return emptyOptional = invokeNullaryFactoryMethod("java.util.Optional", "empty");
+ }
- return emptyOptional = emptyMethod.invoke(null);
- // any exception is really unexpected since the type name has
- // already been verified to be java.util.Optional
- } catch (Exception e) {
- throw new InstantiationException("Could not create java.util.Optional#empty(): " + e, e);
+
+ /**
+ * Creates an empty OptionalDouble using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @return an empty OptionalDouble.
+ */
+ public static Object emptyOptionalDouble() {
+ // no need for double-checked locking
+ if (emptyOptionalDouble != null) {
+ return emptyOptionalDouble;
+ }
+
+ return emptyOptionalDouble = invokeNullaryFactoryMethod("java.util.OptionalDouble", "empty");
+ }
+
+ /**
+ * Creates an empty OptionalInt using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @return an empty OptionalInt.
+ */
+ public static Object emptyOptionalInt() {
+ // no need for double-checked locking
+ if (emptyOptionalInt != null) {
+ return emptyOptionalInt;
+ }
+
+ return emptyOptionalInt = invokeNullaryFactoryMethod("java.util.OptionalInt", "empty");
+ }
+
+ /**
+ * Creates an empty OptionalLong using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @return an empty OptionalLong.
+ */
+ public static Object emptyOptionalLong() {
+ // no need for double-checked locking
+ if (emptyOptionalLong != null) {
+ return emptyOptionalLong;
}
+
+ return emptyOptionalLong = invokeNullaryFactoryMethod("java.util.OptionalLong", "empty");
}
/**
- * Creates an empty Stream using reflection to stay backwards-compatible with older
- * JDKs.
+ * Creates an empty Stream using reflection to stay backwards-compatible with older JDKs.
*
* @return an empty Stream.
*/
public static Object emptyStream() {
// note: the empty stream can not be stored as a singleton.
+ return invokeNullaryFactoryMethod("java.util.stream.Stream", "empty");
+ }
+
+ /**
+ * Creates an empty DoubleStream using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @return an empty DoubleStream.
+ */
+ public static Object emptyDoubleStream() {
+ // note: the empty stream can not be stored as a singleton.
+ return invokeNullaryFactoryMethod("java.util.stream.DoubleStream", "empty");
+ }
+
+ /**
+ * Creates an empty IntStream using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @return an empty IntStream.
+ */
+ public static Object emptyIntStream() {
+ // note: the empty stream can not be stored as a singleton.
+ return invokeNullaryFactoryMethod("java.util.stream.IntStream", "empty");
+ }
+
+ /**
+ * Creates an empty LongStream using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @return an empty LongStream.
+ */
+ public static Object emptyLongStream() {
+ // note: the empty stream can not be stored as a singleton.
+ return invokeNullaryFactoryMethod("java.util.stream.LongStream", "empty");
+ }
+
+ /**
+ * Invokes a nullary static factory method using reflection to stay backwards-compatible with older JDKs.
+ *
+ * @param fqcn The fully qualified class name of the type to be produced.
+ * @param methodName The name of the factory method.
+ * @return the object produced.
+ */
+ private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) {
try {
- final Class<?> optionalClass = Class.forName("java.util.stream.Stream");
- final Method emptyMethod = optionalClass.getMethod("empty");
+ final Class<?> type = Class.forName(fqcn);
+ final Method method = type.getMethod(methodName);
- return emptyMethod.invoke(null);
+ return method.invoke(null);
// any exception is really unexpected since the type name has
// already been verified
- } catch (Exception e) {
- throw new InstantiationException("Could not create java.util.stream.Stream#empty(): " + e, e);
+ } catch (final Exception e) {
+ throw new InstantiationException(
+ String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e);
}
}
}
| diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
index b1553542b4..480a9a1c7f 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
@@ -89,7 +89,7 @@ public void should_return_zero_if_mock_is_compared_to_itself() {
}
@Test
- public void should_return_empty_optional() throws Exception {
+ public void should_return_empty_Optional() throws Exception {
Class<?> streamType = getClassOrSkipTest("java.util.stream.Stream");
//given
@@ -108,7 +108,64 @@ public void should_return_empty_optional() throws Exception {
}
@Test
- public void should_return_empty_stream() throws Exception {
+ public void should_return_empty_OptionalDouble() throws Exception {
+ Class<?> streamType = getClassOrSkipTest("java.util.stream.DoubleStream");
+
+ //given
+ Object stream = mock(streamType);
+ Object optional = streamType.getMethod("findAny").invoke(stream);
+ assertNotNull(optional);
+ assertFalse((Boolean) Class.forName("java.util.OptionalDouble").getMethod("isPresent").invoke(optional));
+
+ Invocation findAny = this.getLastInvocation();
+
+ //when
+ Object result = values.answer(findAny);
+
+ //then
+ assertEquals(optional, result);
+ }
+
+ @Test
+ public void should_return_empty_OptionalInt() throws Exception {
+ Class<?> streamType = getClassOrSkipTest("java.util.stream.IntStream");
+
+ //given
+ Object stream = mock(streamType);
+ Object optional = streamType.getMethod("findAny").invoke(stream);
+ assertNotNull(optional);
+ assertFalse((Boolean) Class.forName("java.util.OptionalInt").getMethod("isPresent").invoke(optional));
+
+ Invocation findAny = this.getLastInvocation();
+
+ //when
+ Object result = values.answer(findAny);
+
+ //then
+ assertEquals(optional, result);
+ }
+
+ @Test
+ public void should_return_empty_OptionalLong() throws Exception {
+ Class<?> streamType = getClassOrSkipTest("java.util.stream.LongStream");
+
+ //given
+ Object stream = mock(streamType);
+ Object optional = streamType.getMethod("findAny").invoke(stream);
+ assertNotNull(optional);
+ assertFalse((Boolean) Class.forName("java.util.OptionalLong").getMethod("isPresent").invoke(optional));
+
+ Invocation findAny = this.getLastInvocation();
+
+ //when
+ Object result = values.answer(findAny);
+
+ //then
+ assertEquals(optional, result);
+ }
+
+ @Test
+ public void should_return_empty_Stream() throws Exception {
// given
Class<?> streamType = getClassOrSkipTest("java.util.stream.Stream");
@@ -120,6 +177,45 @@ public void should_return_empty_stream() throws Exception {
assertEquals("count of empty Stream", 0L, count);
}
+ @Test
+ public void should_return_empty_DoubleStream() throws Exception {
+ // given
+ Class<?> streamType = getClassOrSkipTest("java.util.stream.DoubleStream");
+
+ // when
+ Object stream = values.returnValueFor(streamType);
+ long count = (Long) streamType.getMethod("count").invoke(stream);
+
+ // then
+ assertEquals("count of empty DoubleStream", 0L, count);
+ }
+
+ @Test
+ public void should_return_empty_IntStream() throws Exception {
+ // given
+ Class<?> streamType = getClassOrSkipTest("java.util.stream.IntStream");
+
+ // when
+ Object stream = values.returnValueFor(streamType);
+ long count = (Long) streamType.getMethod("count").invoke(stream);
+
+ // then
+ assertEquals("count of empty IntStream", 0L, count);
+ }
+
+ @Test
+ public void should_return_empty_LongStream() throws Exception {
+ // given
+ Class<?> streamType = getClassOrSkipTest("java.util.stream.LongStream");
+
+ // when
+ Object stream = values.returnValueFor(streamType);
+ long count = (Long) streamType.getMethod("count").invoke(stream);
+
+ // then
+ assertEquals("count of empty LongStream", 0L, count);
+ }
+
/**
* Tries to load the given class. If the class is not found, the complete test is skipped.
*/
| train | train | 2016-11-25T18:24:20 | "2016-11-25T17:37:36Z" | Stephan202 | train |
mockito/mockito/756_795 | mockito/mockito | mockito/mockito/756 | mockito/mockito/795 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8926900290820838)"
] | 75d7316fe9c80b7973597ba890c843b71c7a7a7e | d52d8f4d6c543a8666991f4aec41098434e27639 | [
"Fantastic bug report: reproducible sample, clear motivation. Thanks! I'm looking at it now.\n",
"I was able to repro this with a smaller example that does not use netty. It's a bug that needs to be fixed. Thank you for reporting!\n\n``` java\n@RunWith(MockitoJUnitRunner.class)\npublic class MockitoDeepStubsTest {\n\n private final ClassUnderTest classUnderTest = new ClassUnderTest();\n\n @Mock(answer = Answers.RETURNS_DEEP_STUBS) private ChannelFuture mockChannelFuture;\n\n @Test\n public void shouldAllowDeepStubsUnnecessaryStubbing() {\n classUnderTest.methodUnderTest(mockChannelFuture);\n }\n\n public static class ClassUnderTest {\n void methodUnderTest(ChannelFuture future) {\n future.getChannel().close();\n }\n }\n\n interface ChannelFuture {\n Channel getChannel();\n }\n\n interface Channel {\n void close();\n }\n}\n```\n",
"@bschelberg, thank you for reporting! Stay tuned for Mockito 2.3.0 that will come with even better support for cleaner and easier to debug tests!"
] | [
"Could you add one more call after `getFoo()` to make sure it does not crash on a second invocation? Just to make sure and base on the original bug report.",
"Absolutely, good idea.\r\n\r\n(My test does reproduce the incorrect the behavior)."
] | "2016-12-01T06:22:22Z" | [
"bug"
] | Deep stubbing and UnnecessaryStubbingException | Mocks that return deep stubs sometimes cause UnnecessaryStubbingExceptions to be thrown, when I don't think that they should. Here's a small self-contained example.
```
package some.package;
import org.jboss.netty.channel.ChannelFuture;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockitoDeepStubsTest {
private final ClassUnderTest classUnderTest = new ClassUnderTest();
@Mock(answer = Answers.RETURNS_DEEP_STUBS) private ChannelFuture mockChannelFuture;
@Test
public void shouldAllowDeepStubsUnnecessaryStubbing() {
classUnderTest.methodUnderTest(mockChannelFuture);
}
public static class ClassUnderTest {
public void methodUnderTest(ChannelFuture future) {
future.getChannel().close();
}
}
}
```
Running this test prints the following output:
```
org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected in test class: MockitoDeepStubsTest
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
1. -> at some.package.MockitoDeepStubsTest$ClassUnderTest.methodUnderTest(MockitoDeepStubsTest.java:25)
Please remove unnecessary stubbings. More info: javadoc for UnnecessaryStubbingException class.
at org.mockito.internal.exceptions.Reporter.formatUnncessaryStubbingException(Reporter.java:838)
at org.mockito.internal.junit.UnnecessaryStubbingsReporter.validateUnusedStubs(UnnecessaryStubbingsReporter.java:30)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:45)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:104)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
```
Versions: Mockito 2.2.8
JDK: OpenJDK 1.8.0_111
OS: CentOS 7
Netty: 3.10.6.Final
I know that I can suppress the error with the Silent runner, but I like the unnecessary stubbing checking and don't really want to disable it. For now, we're working around it, but this doesn't seem like correct behaviour. | [
"src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java"
] | [
"src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java"
] | [
"src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java
index f283f5227c..5fd76c096e 100644
--- a/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/InvocationContainerImpl.java
@@ -53,7 +53,10 @@ public void addConsecutiveAnswer(Answer answer) {
addAnswer(answer, true);
}
- public void addAnswer(Answer answer, boolean isConsecutive) {
+ /**
+ * Adds new stubbed answer and returns the invocation matcher the answer was added to.
+ */
+ public StubbedInvocationMatcher addAnswer(Answer answer, boolean isConsecutive) {
Invocation invocation = invocationForStubbing.getInvocation();
mockingProgress().stubbingCompleted();
AnswersValidator answersValidator = new AnswersValidator();
@@ -65,6 +68,7 @@ public void addAnswer(Answer answer, boolean isConsecutive) {
} else {
stubbed.addFirst(new StubbedInvocationMatcher(invocationForStubbing, answer));
}
+ return stubbed.getFirst();
}
}
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 9367a89091..84cd9574bf 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
@@ -68,10 +68,16 @@ private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport retu
}
// record deep stub answer
- return recordDeepStubAnswer(
+ StubbedInvocationMatcher stubbing = recordDeepStubAnswer(
newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()),
container
);
+
+ // deep stubbing creates a stubbing and immediately uses it
+ // so the stubbing is actually used by the same invocation
+ stubbing.markStubUsed(stubbing.getInvocation());
+
+ return stubbing.answer(invocation);
}
/**
@@ -110,9 +116,9 @@ private ReturnsDeepStubs returnsDeepStubsAnswerUsing(final GenericMetadataSuppor
return new ReturnsDeepStubsSerializationFallback(returnTypeGenericMetadata);
}
- private Object recordDeepStubAnswer(final Object mock, InvocationContainerImpl container) {
- container.addAnswer(new DeeplyStubbedAnswer(mock), false);
- return mock;
+ private StubbedInvocationMatcher recordDeepStubAnswer(final Object mock, InvocationContainerImpl container) {
+ DeeplyStubbedAnswer answer = new DeeplyStubbedAnswer(mock);
+ return container.addAnswer(answer, false);
}
protected GenericMetadataSupport actualParameterizedType(Object mock) {
| diff --git a/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java
new file mode 100644
index 0000000000..77ea85b879
--- /dev/null
+++ b/src/test/java/org/mockitousage/junitrunner/DeepStubbingWithJUnitRunnerTest.java
@@ -0,0 +1,41 @@
+package org.mockitousage.junitrunner;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class DeepStubbingWithJUnitRunnerTest {
+
+ private final SomeClass someClass = new SomeClass();
+
+ @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Root root;
+
+ @Test
+ public void deep_stubs_dont_trigger_unnecessary_stubbing_exception() {
+ //when
+ someClass.someMethod(root);
+
+ //then unnecessary stubbing exception is not thrown
+ }
+
+ public static class SomeClass {
+ void someMethod(Root root) {
+ root.getFoo().getBar();
+ }
+ }
+
+ interface Root {
+ Foo getFoo();
+ }
+
+ interface Foo {
+ Bar getBar();
+ }
+
+ interface Bar {
+
+ }
+}
\ No newline at end of file
| test | train | 2016-11-30T15:12:05 | "2016-11-14T22:01:19Z" | bschelberg | train |
mockito/mockito/798_813 | mockito/mockito | mockito/mockito/798 | mockito/mockito/813 | [
"timestamp(timedelta=43.0, similarity=0.9208988661090468)"
] | 6eaa2d0bab532196468d364d84cc1e9f44f77dea | 5ee677b834032c69edc430464d27b1e58916e364 | [
"Release approaching ;)",
"`0.7.8` has been released: https://github.com/jacoco/jacoco/issues/467#issuecomment-266305876",
"Fixed by #798."
] | [] | "2016-12-12T21:10:32Z" | [
"java-9"
] | Update Jacoco to stable minor version 0.7.8 when released | See https://github.com/jacoco/jacoco/issues/467#issuecomment-264311016
The snapshot version of Jacoco are removed and could fail our CI. The version of Jacoco is required to build on JDK9 | [
"gradle/coverage.gradle"
] | [
"gradle/coverage.gradle"
] | [] | diff --git a/gradle/coverage.gradle b/gradle/coverage.gradle
index 9ad6740879..86fc3a190b 100644
--- a/gradle/coverage.gradle
+++ b/gradle/coverage.gradle
@@ -2,14 +2,8 @@ apply plugin: 'jacoco'
// TODO later include subprojects, possible ideas https://gist.github.com/aalmiray/e6f54aa4b3803be0bcac
-repositories {
- // TODO go back to the latest release of Jacoco. We need this snapshot
- // because of https://github.com/jacoco/jacoco/pull/434 on JDK 9
- maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
-}
-
jacoco {
- toolVersion = "0.7.8-20161102.122531-23"
+ toolVersion = "0.7.8"
}
task mockitoCoverage(type: JacocoReport, dependsOn: "test") {
| null | val | train | 2016-12-02T01:16:19 | "2016-12-01T23:22:33Z" | TimvdLippe | train |
mockito/mockito/820_821 | mockito/mockito | mockito/mockito/820 | mockito/mockito/821 | [
"keyword_issue_to_pr",
"keyword_pr_to_issue"
] | c2261b5d6df55a68302875a5b70503856c51a296 | 40ab88b61d0a37c55d3f0bc39e07bb5c9efb8a49 | [
"I think your second example has a typo, since there are no var args in the example",
"thanks fixed",
"Good catch!\r\nBy the way, the mock reference is both foo and mock",
"While it is source and binary compatible, vararg method are different than plain old array method, reflection allows to distinguish that. The issue is in `ReturnsArgumentAt.returnedTypeOnSignature` where there's a special handling for varargs.",
"I'm working on the fix (currently adding some unit tests)",
"This should be fixed by #821"
] | [
"French comment? 😂 ",
"spacing",
"haha yes, I'm sick, so my brain had to think in french and slowly"
] | "2016-12-14T18:01:23Z" | [
"bug"
] | [VarArgs] unexpected behaviour of returnsArgAt(int) | I stumble about a test that failed after refactoring an array parameter to an varargs.
The following test succeed:
```java
interface Foo{
int[] getOdd(int[] input);
}
@Test
public void test() throws Exception {
when(foo.getOdd(any())).then(returnsArgAt(0));
int[] odd = mock.getOdd(new int[]{1,3,5});
assertThat(odd).contains(1,3,5);
}
```
Now lets change the parameter _input_ to an varargs.
```java
interface Foo{
int[] getOdd(int... input);
}
```
The test fails now with:
```
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
The argument of type 'int' cannot be returned because the following
method should return the type 'int[]'
-> foo.getOdd()
```
This is not expected cause the change is source and binary(?) compatible, an varargs-parameter is still an array. ReturnsArgumentAt interprets the vararg array items as real parameters. In other words it tries to return an element type where the array type is required.
Can the behaviour of interpreting vararg elements like parameters be changed so an vararg is treated as an array? E.g. in Mockito 3? There are several other cases were the current vararg handling leads to unexpected behaviour. | [
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java"
] | [
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java"
] | [
"src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java",
"src/test/java/org/mockitousage/IMethods.java",
"src/test/java/org/mockitousage/MethodsImpl.java"
] | diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java
index 348743da04..287e4b1830 100644
--- a/src/main/java/org/mockito/AdditionalAnswers.java
+++ b/src/main/java/org/mockito/AdditionalAnswers.java
@@ -36,20 +36,44 @@
*/
@SuppressWarnings("unchecked")
public class AdditionalAnswers {
- private static final ReturnsArgumentAt RETURNS_FIRST_ARGUMENT = new ReturnsArgumentAt(0);
- private static final ReturnsArgumentAt RETURNS_SECOND_ARGUMENT = new ReturnsArgumentAt(1);
- private static final ReturnsArgumentAt RETURNS_LAST_ARGUMENT = new ReturnsArgumentAt(-1);
-
/**
* Returns the first parameter of an invocation.
*
* <p>
* This additional answer could be used at stub time using the
* <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
+ *
+ * <pre class="code"><code class="java">
+ * given(carKeyFob.authenticate(carKey)).will(returnsFirstArg());
+ * doAnswer(returnsFirstArg()).when(carKeyFob).authenticate(carKey);
+ * </code></pre>
* </p>
*
- * <pre class="code"><code class="java">given(carKeyFob.authenticate(carKey)).will(returnsFirstArg());
- * doAnswer(returnsFirstArg()).when(carKeyFob).authenticate(carKey)</code></pre>
+ * <p>
+ * This methods works with varargs as well, mockito will expand the vararg to return the argument
+ * at the given position. Suppose the following signature :
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream remember(Dream... dreams);
+ * }
+ *
+ * // returns dream1
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsFirstArg());
+ * </code></pre>
+ *
+ * Mockito will return the vararg array if the first argument is a vararg in the method
+ * and if the return type has the same type as the vararg array.
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream[] remember(Dream... otherDreams);
+ * }
+ *
+ * // returns otherDreams (happens to be a 4 elements array)
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsFirstArg());
+ * </code></pre>
+ * </p>
*
* @param <T> Return type of the invocation.
* @return Answer that will return the first argument of the invocation.
@@ -57,7 +81,7 @@ public class AdditionalAnswers {
* @since 1.9.5
*/
public static <T> Answer<T> returnsFirstArg() {
- return (Answer<T>) RETURNS_FIRST_ARGUMENT;
+ return (Answer<T>) new ReturnsArgumentAt(0);
}
/**
@@ -66,10 +90,38 @@ public static <T> Answer<T> returnsFirstArg() {
* <p>
* This additional answer could be used at stub time using the
* <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
+ *
+ * <pre class="code"><code class="java">
+ * given(trader.apply(leesFormula, onCreditDefaultSwap)).will(returnsSecondArg());
+ * doAnswer(returnsSecondArg()).when(trader).apply(leesFormula, onCreditDefaultSwap);
+ * </code></pre>
* </p>
*
- * <pre class="code"><code class="java">given(trader.apply(leesFormula, onCreditDefaultSwap)).will(returnsSecondArg());
- * doAnswer(returnsSecondArg()).when(trader).apply(leesFormula, onCreditDefaultSwap)</code></pre>
+ * <p>
+ * This methods works with varargs as well, mockito will expand the vararg to return the argument
+ * at the given position. Suppose the following signature :
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream remember(Dream dream, Dream... otherDreams);
+ * }
+ *
+ * // returns dream2
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsSecondArg());
+ * </code></pre>
+ *
+ * Mockito will return the vararg array if the second argument is a vararg in the method
+ * and if the return type has the same type as the vararg array.
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream[] remember(Dream dream1, Dream... otherDreams);
+ * }
+ *
+ * // returns otherDreams (happens to be a 3 elements array)
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsSecondArg());
+ * </code></pre>
+ * </p>
*
* @param <T> Return type of the invocation.
* @return Answer that will return the second argument of the invocation.
@@ -77,7 +129,7 @@ public static <T> Answer<T> returnsFirstArg() {
* @since 1.9.5
*/
public static <T> Answer<T> returnsSecondArg() {
- return (Answer<T>) RETURNS_SECOND_ARGUMENT;
+ return (Answer<T>) new ReturnsArgumentAt(1);
}
/**
@@ -86,10 +138,38 @@ public static <T> Answer<T> returnsSecondArg() {
* <p>
* This additional answer could be used at stub time using the
* <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
+ *
+ * <pre class="code"><code class="java">
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
+ * doAnswer(returnsLastArg()).when(person).remember(dream1, dream2, dream3, dream4);
+ * </code></pre>
* </p>
*
- * <pre class="code"><code class="java">given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
- * doAnswer(returnsLastArg()).when(person).remember(dream1, dream2, dream3, dream4)</code></pre>
+ * <p>
+ * This methods works with varargs as well, mockito will expand the vararg to return the argument
+ * at the given position. Suppose the following signature :
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream remember(Dream dream, Dream... otherDreams);
+ * }
+ *
+ * // returns dream4
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
+ * </code></pre>
+ *
+ * Mockito will return the vararg array if the given {@code position} targets the vararg index in the method
+ * and if the return type has the same type as the vararg array.
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream[] remember(Dream dream1, Dream dream2, Dream dream3, Dream... otherDreams);
+ * }
+ *
+ * // returns otherDreams (happens to be a single element array)
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsLastArg());
+ * </code></pre>
+ * </p>
*
* @param <T> Return type of the invocation.
* @return Answer that will return the last argument of the invocation.
@@ -97,7 +177,7 @@ public static <T> Answer<T> returnsSecondArg() {
* @since 1.9.5
*/
public static <T> Answer<T> returnsLastArg() {
- return (Answer<T>) RETURNS_LAST_ARGUMENT;
+ return (Answer<T>) new ReturnsArgumentAt(ReturnsArgumentAt.LAST_ARGUMENT);
}
/**
@@ -106,10 +186,38 @@ public static <T> Answer<T> returnsLastArg() {
* <p>
* This additional answer could be used at stub time using the
* <code>then|do|will{@link org.mockito.stubbing.Answer}</code> methods. For example :
+ *
+ * <pre class="code"><code class="java">
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(3));
+ * doAnswer(returnsArgAt(3)).when(person).remember(dream1, dream2, dream3, dream4);
+ * </code></pre>
* </p>
*
- * <pre class="code"><code class="java">given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(3));
- * doAnswer(returnsArgAt(3)).when(person).remember(dream1, dream2, dream3, dream4)</code></pre>
+ * <p>
+ * This methods works with varargs as well, mockito will expand the vararg to return the argument
+ * at the given position. Suppose the following signature :
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream remember(Dream dream, Dream... otherDreams);
+ * }
+ *
+ * // returns dream 3
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(2));
+ * </code></pre>
+ *
+ * Mockito will return the vararg array if the given {@code position} targets the vararg index in the method
+ * and if the return type has the same type as the vararg array.
+ *
+ * <pre class="code"><code class="java">
+ * interface Person {
+ * Dream[] remember(Dream dream, Dream... otherDreams);
+ * }
+ *
+ * // returns otherDreams array (contains dream2, dream,3, dream4)
+ * given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(1));
+ * </code></pre>
+ * </p>
*
* @param <T> Return type of the invocation.
* @param position index of the argument from the list of arguments.
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
index c22746b568..7c0a144b71 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
@@ -5,17 +5,16 @@
package org.mockito.internal.stubbing.answers;
import java.io.Serializable;
+import java.lang.reflect.Method;
+import org.mockito.internal.exceptions.Reporter;
+import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.ValidableAnswer;
-import static org.mockito.internal.exceptions.Reporter.invalidArgumentPositionRangeAtInvocationTime;
-import static org.mockito.internal.exceptions.Reporter.invalidArgumentRangeAtIdentityAnswerCreationTime;
-import static org.mockito.internal.exceptions.Reporter.wrongTypeOfArgumentToReturn;
-
/**
* Returns the passed parameter identity at specified index.
- *
+ * <p>
* <p>The <code>argumentIndex</code> represents the index in the argument array of the invocation.</p>
* <p>If this number equals -1 then the last argument is returned.</p>
*
@@ -34,92 +33,102 @@ public class ReturnsArgumentAt implements Answer<Object>, ValidableAnswer, Seria
* Build the identity answer to return the argument at the given position in the argument array.
*
* @param wantedArgumentPosition The position of the argument identity to return in the invocation.
- * Using <code>-1</code> indicates the last argument.
+ * Using <code>-1</code> indicates the last argument ({@link #LAST_ARGUMENT}).
*/
public ReturnsArgumentAt(int wantedArgumentPosition) {
- this.wantedArgumentPosition = checkWithinAllowedRange(wantedArgumentPosition);
- }
-
- public Object answer(InvocationOnMock invocation) throws Throwable {
- validateIndexWithinInvocationRange(invocation);
- return invocation.getArgument(actualArgumentPosition(invocation));
+ if (wantedArgumentPosition != LAST_ARGUMENT && wantedArgumentPosition < 0) {
+ throw Reporter.invalidArgumentRangeAtIdentityAnswerCreationTime();
+ }
+ this.wantedArgumentPosition = wantedArgumentPosition;
}
@Override
- public void validateFor(InvocationOnMock invocation) {
- validateIndexWithinInvocationRange(invocation);
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ int argumentPosition = inferWantedArgumentPosition(invocation);
+ validateIndexWithinInvocationRange(invocation, argumentPosition);
- InvocationInfo invocationInfo = new InvocationInfo(invocation);
- if (!invocationInfo.isValidReturnType(returnedTypeOnSignature(invocation))) {
- throw wrongTypeOfArgumentToReturn(invocation, invocationInfo.printMethodReturnType(),
- returnedTypeOnSignature(invocation),
- wantedArgumentPosition());
+ if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentPosition)) {
+ // answer raw vararg array argument
+ return ((Invocation) invocation).getRawArguments()[argumentPosition];
+ } else {
+ // answer expanded argument at wanted position
+ return invocation.getArgument(argumentPosition);
}
}
- private int actualArgumentPosition(InvocationOnMock invocation) {
- return returningLastArg() ?
- lastArgumentIndexOf(invocation) :
- argumentIndexOf(invocation);
- }
-
- private boolean returningLastArg() {
- return wantedArgumentPosition == LAST_ARGUMENT;
+ @Override
+ public void validateFor(InvocationOnMock invocation) {
+ int argumentPosition = inferWantedArgumentPosition(invocation);
+ validateIndexWithinInvocationRange(invocation, argumentPosition);
+ validateArgumentTypeCompatibility(invocation, argumentPosition);
}
- private int argumentIndexOf(InvocationOnMock invocation) {
- return wantedArgumentPosition;
+ private int inferWantedArgumentPosition(InvocationOnMock invocation) {
+ return wantedArgumentPosition == LAST_ARGUMENT ?
+ invocation.getArguments().length - 1 :
+ wantedArgumentPosition;
}
- private int lastArgumentIndexOf(InvocationOnMock invocation) {
- return invocation.getArguments().length - 1;
+ private void validateIndexWithinInvocationRange(InvocationOnMock invocation, int argumentPosition) {
+ if (!wantedArgumentPositionIsValidForInvocation(invocation, argumentPosition)) {
+ throw Reporter.invalidArgumentPositionRangeAtInvocationTime(invocation,
+ wantedArgumentPosition == LAST_ARGUMENT,
+ wantedArgumentPosition);
+ }
}
- private int checkWithinAllowedRange(int argumentPosition) {
- if (argumentPosition != LAST_ARGUMENT && argumentPosition < 0) {
- throw invalidArgumentRangeAtIdentityAnswerCreationTime();
+ private void validateArgumentTypeCompatibility(InvocationOnMock invocation, int argumentPosition) {
+ InvocationInfo invocationInfo = new InvocationInfo(invocation);
+ Class<?> inferredArgumentType = inferWantedArgumentType(invocation, argumentPosition);
+ if (!invocationInfo.isValidReturnType(inferredArgumentType)) {
+ throw Reporter.wrongTypeOfArgumentToReturn(invocation,
+ invocationInfo.printMethodReturnType(),
+ inferredArgumentType,
+ wantedArgumentPosition);
}
- return argumentPosition;
}
- private int wantedArgumentPosition() {
- return wantedArgumentPosition;
+ private boolean wantedArgIndexIsVarargAndSameTypeAsReturnType(Method method, int argumentPosition) {
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ return method.isVarArgs()
+ && argumentPosition == /* vararg index */ parameterTypes.length - 1
+ && method.getReturnType().isAssignableFrom(parameterTypes[argumentPosition]);
}
- private void validateIndexWithinInvocationRange(InvocationOnMock invocation) {
- if (!argumentPositionInRange(invocation)) {
- throw invalidArgumentPositionRangeAtInvocationTime(invocation,
- returningLastArg(),
- wantedArgumentPosition);
- }
- }
-
- private boolean argumentPositionInRange(InvocationOnMock invocation) {
- int actualArgumentPosition = actualArgumentPosition(invocation);
- if (actualArgumentPosition < 0) {
+ private boolean wantedArgumentPositionIsValidForInvocation(InvocationOnMock invocation, int argumentPosition) {
+ if (argumentPosition < 0) {
return false;
}
if (!invocation.getMethod().isVarArgs()) {
- return invocation.getArguments().length > actualArgumentPosition;
+ return invocation.getArguments().length > argumentPosition;
}
// for all varargs accepts positive ranges
return true;
}
- private Class<?> returnedTypeOnSignature(InvocationOnMock invocation) {
- int actualArgumentPosition = actualArgumentPosition(invocation);
-
- if(!invocation.getMethod().isVarArgs()) {
- return invocation.getMethod().getParameterTypes()[actualArgumentPosition];
+ private Class<?> inferWantedArgumentType(InvocationOnMock invocation, int argumentPosition) {
+ Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
+ // Easy when the method is not a vararg
+ if (!invocation.getMethod().isVarArgs()) {
+ return parameterTypes[argumentPosition];
}
- Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
- int varargPosition = parameterTypes.length - 1;
+ // Now for varargs
+ int varargIndex = parameterTypes.length - 1; // vararg always last
- if(actualArgumentPosition < varargPosition) {
- return parameterTypes[actualArgumentPosition];
+ if (argumentPosition < varargIndex) {
+ // Same for non vararg arguments
+ return parameterTypes[argumentPosition];
} else {
- return parameterTypes[varargPosition].getComponentType();
+ // if wanted argument is vararg
+ if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentPosition)) {
+ // return the vararg array if return type is compatible
+ // because the user probably want to return the array itself if the return type is compatible
+ return parameterTypes[argumentPosition]; // move to MethodInfo ?
+ } else {
+ // return the type in this vararg array
+ return parameterTypes[varargIndex].getComponentType();
+ }
}
}
}
| diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
index 5ccdbd0926..f72005aeaa 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
@@ -4,10 +4,12 @@
*/
package org.mockito.internal.stubbing.answers;
+import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;
import org.mockito.internal.invocation.InvocationBuilder;
+import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationOnMock;
import static org.assertj.core.api.Assertions.assertThat;
@@ -38,27 +40,82 @@ public void should_be_able_to_return_the_specified_parameter() throws Throwable
assertThat(new ReturnsArgumentAt(2).answer(invocationWith("A", "B", "C"))).isEqualTo("C");
}
+ @Test
+ public void should_identify_bad_parameter_type_for_invocation() throws Exception {
+ try {
+ new ReturnsArgumentAt(1).validateFor(new InvocationBuilder().method("varargsReturningString")
+ .argTypes(Object[].class)
+ .args(new Object(), new Object(), new Object())
+ .toInvocation());
+ Assertions.fail("should scream");
+ } catch (WrongTypeOfReturnValue ignored) { }
+ try {
+ new ReturnsArgumentAt(0).validateFor(new InvocationBuilder().method("oneArray")
+ .argTypes(boolean[].class)
+ .args(true, false, false)
+ .toInvocation());
+ Assertions.fail("should scream");
+ } catch (WrongTypeOfReturnValue ignored) { }
+ try {
+ new ReturnsArgumentAt(0).validateFor(new InvocationBuilder().method("mixedVarargsReturningString")
+ .argTypes(Object.class, String[].class)
+ .args(new Object(), new String[]{"A", "B", "C"})
+ .toInvocation());
+ Assertions.fail("should scream");
+ } catch (WrongTypeOfReturnValue ignored) { }
+ }
+
+ @Test
+ public void should_not_scream_when_mixed_vararg_parameter_is_compatible_with_invocation() throws Exception {
+ new ReturnsArgumentAt(1).validateFor(new InvocationBuilder().method("mixedVarargsReturningString")
+ .argTypes(Object.class, String[].class)
+ .args(new Object(), new String[]{"A", "B", "C"})
+ .toInvocation());
+ }
+
+ @Test
+ public void should_handle_returning_vararg_as_array() throws Throwable {
+ Invocation mixedVarargsReturningStringArray = new InvocationBuilder().method("mixedVarargsReturningStringArray")
+ .argTypes(Object.class, String[].class)
+ .args(new Object(), new String[]{"A", "B", "C"})
+ .toInvocation();
+ new ReturnsArgumentAt(1).validateFor(mixedVarargsReturningStringArray);
+ assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningStringArray)).isEqualTo(new String[]{"A", "B", "C"});
+
+ Invocation mixedVarargsReturningObjectArray = new InvocationBuilder().method("mixedVarargsReturningStringArray")
+ .argTypes(Object.class, String[].class)
+ .args(new Object(), new String[]{"A", "B", "C"})
+ .toInvocation();
+ new ReturnsArgumentAt(1).validateFor(mixedVarargsReturningObjectArray);
+ assertThat(new ReturnsArgumentAt(1).answer(mixedVarargsReturningObjectArray)).isEqualTo(new String[]{"A", "B", "C"});
+ }
+
@Test
public void should_raise_an_exception_if_index_is_not_in_allowed_range_at_creation_time() throws Throwable {
try {
new ReturnsArgumentAt(-30);
fail();
} catch (Exception e) {
- assertThat(e.getMessage())
- .containsIgnoringCase("argument index")
- .containsIgnoringCase("positive number")
- .contains("1")
- .containsIgnoringCase("last argument");
+ assertThat(e.getMessage()).containsIgnoringCase("argument index")
+ .containsIgnoringCase("positive number")
+ .contains("1")
+ .containsIgnoringCase("last argument");
}
}
@Test
public void should_allow_possible_argument_types() throws Exception {
new ReturnsArgumentAt(0).validateFor(
- new InvocationBuilder().method("intArgumentReturningInt").argTypes(int.class).arg(1000).toInvocation()
+ new InvocationBuilder().method("intArgumentReturningInt")
+ .argTypes(int.class)
+ .arg(1000)
+ .toInvocation()
);
new ReturnsArgumentAt(0).validateFor(
- new InvocationBuilder().method("toString").argTypes(String.class).arg("whatever").toInvocation()
+ new InvocationBuilder().method("toString")
+ .argTypes(String.class)
+ .arg("whatever")
+ .toInvocation()
);
new ReturnsArgumentAt(2).validateFor(
new InvocationBuilder().method("varargsObject")
@@ -77,7 +134,9 @@ public void should_allow_possible_argument_types() throws Exception {
@Test
public void should_fail_if_index_is_not_in_range_for_one_arg_invocation() throws Throwable {
try {
- new ReturnsArgumentAt(30).validateFor(new InvocationBuilder().method("oneArg").arg("A").toInvocation());
+ new ReturnsArgumentAt(30).validateFor(new InvocationBuilder().method("oneArg")
+ .arg("A")
+ .toInvocation());
fail();
} catch (MockitoException e) {
assertThat(e.getMessage())
@@ -127,7 +186,8 @@ public void should_fail_if_argument_type_of_signature_is_incompatible_with_retur
}
private static InvocationOnMock invocationWith(Object... parameters) {
- return new InvocationBuilder().method("varargsReturningString").argTypes(Object[].class)
+ return new InvocationBuilder().method("varargsReturningString")
+ .argTypes(Object[].class)
.args(parameters).toInvocation();
}
diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java
index 7234bd7976..c3d510f5ac 100644
--- a/src/test/java/org/mockitousage/IMethods.java
+++ b/src/test/java/org/mockitousage/IMethods.java
@@ -172,6 +172,12 @@ public interface IMethods {
void mixedVarargs(Object i, String ... string);
+ String mixedVarargsReturningString(Object i, String ... string);
+
+ String[] mixedVarargsReturningStringArray(Object i, String ... string);
+
+ Object[] mixedVarargsReturningObjectArray(Object i, String ... string);
+
List<String> listReturningMethod(Object ... objects);
LinkedList<String> linkedListReturningMethod();
@@ -225,4 +231,4 @@ public interface IMethods {
Integer toIntWrapper(int i);
String forObject(Object object);
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/mockitousage/MethodsImpl.java b/src/test/java/org/mockitousage/MethodsImpl.java
index 4f4bdcc8d8..0fb965c3ae 100644
--- a/src/test/java/org/mockitousage/MethodsImpl.java
+++ b/src/test/java/org/mockitousage/MethodsImpl.java
@@ -328,6 +328,18 @@ public int varargs(String... string) {
public void mixedVarargs(Object i, String... string) {
}
+ public String mixedVarargsReturningString(Object i, String... string) {
+ return null;
+ }
+
+ public String[] mixedVarargsReturningStringArray(Object i, String... string) {
+ return null;
+ }
+
+ public Object[] mixedVarargsReturningObjectArray(Object i, String... string) {
+ return null;
+ }
+
public void varargsbyte(byte... bytes) {
}
| train | train | 2017-01-02T17:48:41 | "2016-12-14T14:40:38Z" | ChristianSchwarz | train |
mockito/mockito/838_839 | mockito/mockito | mockito/mockito/838 | mockito/mockito/839 | [
"keyword_pr_to_issue"
] | 799b70da90b75982746665fed7e2533b9b5e1fc7 | 1193d14587bfa2344ce07e2e16adbc5ba32c4be4 | [
"As the question is answered in SO, you can negate matchers using `AdditionalMatchers.not()`.\r\n\r\nI think I can close this issue.",
"OK... but this question highlights the fact that the online documentation and tutorials are not optional, they are essential ... and they are currently inadequate. People who are willing to learn shouldn't have to pose a question for such an obvious use case on SO.",
"Hi,\r\n\r\nI closed the issue because it is about a feature request that is not valid since the feature is already present in a different form. Now documentation and tutorial is another thing.\r\n\r\n`AdditionalMatchers` is mentionned on the first line of the [ArgumentMatchers javadoc](https://static.javadoc.io/org.mockito/mockito-core/2.4.0/org/mockito/ArgumentMatchers.html). The Mockito javadoc gives plenty of code examples on the public API, which is already more than most javadoc in almost every project. \r\n\r\nI'm not saying it can't improved or we won't improve it, it can and we will! On the matter at hand those matchers can be promoted a bit more to enhance discoverability.\r\n\r\nRegarding tutorials I believe it is the responsibility of respective blog authors.\r\n\r\nIn the mean time pull requests are welcome, and the wiki can be edited by any benevolent soul.",
"Also it seems I skipped the part on the `Pattern` class, reopening for the `matches(Pattern)` matcher.\r\n\r\n",
"Oh... good. No really! The multi-line challenge has me foxed... indeed. :)",
"The builds should propagate within an hour (note that badges or search.maven.org may not be up to date)",
"Hi Brice... thanks for doing this so quickly. I have upgraded my gradle.build and got hold of your new build. But I am still having problems using \"not\" with this... if you have a moment maybe you might look at my new edit at [SO](http://stackoverflow.com/questions/41270738/mockito-argumentmatchers-doesnotmatch).",
"It looks like an import issue, either for `not` or `matches`. I've tested it yesterday, when I added the API.",
"Yes, you're right: it's an AssertJ confusion: Eclipse imported NotFilter.not() automatically. Apologies."
] | [] | "2016-12-22T13:50:01Z" | [
"enhancement"
] | Feature request: ArgumentMatchers.matches(Pattern regex) | you ladies and gentlemen are geniuses by the way.
ArgumentMatchers.match( String regex ) exists... but wouldn't it be slightly better if it were match( Pattern regex )? (i.e. catering for multi-line Strings, etc.).
Also, devising a regex which distinctly does NOT match a given String is non-trivial. And yet not atypical of a mocking use case. Hence I suggest you clever people take the heavy lifting away from grunts like me by offering ArgumentMatchers.doesNotMatch( Pattern regex ).
I posed this question today on Stack Overflow [here](http://stackoverflow.com/questions/41270738/mockito-argumentmatchers-doesnotmatch?noredirect=1#comment69745269_41270738).
------
**EDIT 1** by @bric3 : removed the issue guidelines
**EDIT 2** by @bric3 : Renamed the issue title. Previous title was `Feature request: ArgumentMatchers.doesNotMatch( Pattern regex )` | [
"src/main/java/org/mockito/ArgumentMatchers.java",
"src/main/java/org/mockito/internal/matchers/Matches.java"
] | [
"src/main/java/org/mockito/ArgumentMatchers.java",
"src/main/java/org/mockito/internal/matchers/Matches.java"
] | [
"src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java",
"src/test/java/org/mockitousage/matchers/MatchersTest.java"
] | diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java
index 66d05a7ac0..56ff53311f 100644
--- a/src/main/java/org/mockito/ArgumentMatchers.java
+++ b/src/main/java/org/mockito/ArgumentMatchers.java
@@ -4,8 +4,6 @@
*/
package org.mockito;
-import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
-import static org.mockito.internal.util.Primitives.defaultValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -13,6 +11,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Pattern;
import org.mockito.internal.matchers.Any;
import org.mockito.internal.matchers.Contains;
import org.mockito.internal.matchers.EndsWith;
@@ -26,6 +25,9 @@
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
import org.mockito.internal.util.Primitives;
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+import static org.mockito.internal.util.Primitives.defaultValue;
+
/**
* Allow flexible verification or stubbing. See also {@link AdditionalMatchers}.
*
@@ -93,6 +95,12 @@
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
* </p>
*
+ * <h1>Additional matchers</h1>
+ * <p>
+ * The class {@link AdditionalMatchers} offers rarely used matchers, although they can be useful, when
+ * it is useful to combine multiple matchers or when it is useful to negate a matcher necessary.
+ * </p>
+ *
* <h1>Custom Argument ArgumentMatchers</h1>
* <p>
* It is important to understand the use cases and available options for dealing with non-trivial arguments
@@ -1104,12 +1112,29 @@ public static String contains(String substring) {
*
* @param regex the regular expression.
* @return empty String ("").
+ *
+ * @see AdditionalMatchers#not(boolean)
*/
public static String matches(String regex) {
reportMatcher(new Matches(regex));
return "";
}
+ /**
+ * <code>Pattern</code> argument that matches the given regular expression.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param pattern the regular expression pattern.
+ * @return empty String ("").
+ *
+ * @see AdditionalMatchers#not(boolean)
+ */
+ public static String matches(Pattern pattern) {
+ reportMatcher(new Matches(pattern));
+ return "";
+ }
+
/**
* <code>String</code> argument that ends with the given suffix.
* <p>
diff --git a/src/main/java/org/mockito/internal/matchers/Matches.java b/src/main/java/org/mockito/internal/matchers/Matches.java
index 6ebb4a8368..2a15c47480 100644
--- a/src/main/java/org/mockito/internal/matchers/Matches.java
+++ b/src/main/java/org/mockito/internal/matchers/Matches.java
@@ -5,23 +5,27 @@
package org.mockito.internal.matchers;
-import org.mockito.ArgumentMatcher;
-
import java.io.Serializable;
+import java.util.regex.Pattern;
+import org.mockito.ArgumentMatcher;
public class Matches implements ArgumentMatcher<Object>, Serializable {
- private final String regex;
+ private final Pattern pattern;
public Matches(String regex) {
- this.regex = regex;
+ this(Pattern.compile(regex));
+ }
+
+ public Matches(Pattern pattern) {
+ this.pattern = pattern;
}
public boolean matches(Object actual) {
- return (actual instanceof String) && ((String) actual).matches(regex);
+ return (actual instanceof String) && pattern.matcher((String) actual).matches();
}
public String toString() {
- return "matches(\"" + regex.replaceAll("\\\\", "\\\\\\\\") + "\")";
+ return "matches(\"" + pattern.pattern().replaceAll("\\\\", "\\\\\\\\") + "\")";
}
-}
\ No newline at end of file
+}
| diff --git a/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java b/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java
index c62756bcd4..9611dee2a6 100644
--- a/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java
+++ b/src/test/java/org/mockito/internal/matchers/MatchersToStringTest.java
@@ -5,6 +5,7 @@
package org.mockito.internal.matchers;
+import java.util.regex.Pattern;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockitoutil.TestBase;
@@ -113,6 +114,7 @@ public void findToString() {
@Test
public void matchesToString() {
assertEquals("matches(\"\\\\s+\")", new Matches("\\s+").toString());
+ assertEquals("matches(\"\\\\s+\")", new Matches(Pattern.compile("\\s+")).toString());
}
}
diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java
index 762d0ee3e5..f151a84396 100644
--- a/src/test/java/org/mockitousage/matchers/MatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java
@@ -5,6 +5,22 @@
package org.mockitousage.matchers;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.RandomAccess;
+import java.util.regex.Pattern;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.exceptions.verification.WantedButNotInvoked;
+import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.assertNotSame;
+import static junit.framework.TestCase.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalMatchers.and;
import static org.mockito.AdditionalMatchers.aryEq;
@@ -43,20 +59,6 @@
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import static junit.framework.TestCase.assertEquals;
-import static junit.framework.TestCase.assertNotSame;
-import static junit.framework.TestCase.fail;
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.RandomAccess;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
-import org.mockitousage.IMethods;
-import org.mockitoutil.TestBase;
@SuppressWarnings("unchecked")
@@ -499,6 +501,16 @@ public void matches_matcher() {
assertEquals(null, mock.oneArg("blah"));
}
+ @Test
+ public void matches_Pattern_matcher() {
+ when(mock.oneArg(matches(Pattern.compile("[a-z]+\\d\\d")))).thenReturn("1");
+ when(mock.oneArg(matches(Pattern.compile("\\d\\d\\d")))).thenReturn("2");
+
+ assertEquals("1", mock.oneArg("a12"));
+ assertEquals("2", mock.oneArg("131"));
+ assertEquals(null, mock.oneArg("blah"));
+ }
+
@Test
public void contains_matcher() {
when(mock.oneArg(contains("ell"))).thenReturn("1");
@@ -600,4 +612,4 @@ public void nullable_matcher() throws Exception {
verify(mock, times(2)).oneArg(nullable(Character.class));
}
-}
\ No newline at end of file
+}
| train | train | 2016-12-21T06:35:10 | "2016-12-21T21:27:04Z" | Mrodent | train |
mockito/mockito/845_847 | mockito/mockito | mockito/mockito/845 | mockito/mockito/847 | [
"timestamp(timedelta=1.0, similarity=0.8883307402829964)"
] | 18320605e0f1b161581263864c97848f41b1a9f6 | 228e3a5b171a782cc5dcf022d123064c23ef2d31 | [
"If the renaming is only needed when creating a distribution jar, you can customize the jar task with something like this:\r\n\r\n`jar {\r\n rename \"org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.class\", \"org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.raw\"\r\n}`\r\n\r\nIf you need to rename this file after compilation, you could use the `doLast` section of the `classes` task:\r\n\r\n`doLast {\r\n file(\"${buildDir}/main/org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.class\").renameTo(\"${buildDir}/main/org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.raw\")\r\n}`",
"I discovered the Robolectric ClassLoader issue as well while updating the Mockito mockmaker to ByteBuddy internally. My fix now has the correct class hierarchy, but it now fails to properly resolve the `MockMethodDispatcher`. Should we revert this change (and figure out a way to work with both the broken ClassLoader and the fixed version)?",
"For now, I have patched the Robolectric ClassLoader to special case the class:\r\n\r\n```java\r\nString extension = className.equals(\"org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher\") ? \"raw\" : \"class\";\r\n String classFilename = className.replace('.', '/') + \".\" + extension;\r\n```\r\nHowever, this introduces a version complexity matrix. E.g.:\r\n\r\nbroken Robolectric works with current Mockito\r\nfixed Robolectric does not work with current Mockito\r\nfixed Robolectric + workaround works with current Mockito\r\n\r\nHow can we remove the workaround in Robolectric while at the same time remove the workaround in Mockito while adhering to SemVer in BOTH projects?",
"Current thinking is (on Mockito build time) keep the `.class` and copying to `.raw`. Then we can update Mockito to just use `.class` and old Robolectric ignores `.raw`, while the new Robolectric uses the original `.class`."
] | [
"In order for this to work reliably, we need to also set one more task dependency on compileJava. Let me try to update the code in the branch...",
"Above change makes the compiled classes directory contain both: the 'raw' and normal class. Is this what we want?",
"Yes, for the time until packaging the jar. This is required to make IDEs work with Mockito which do otherwise claim that there is a class missing (experienced with IntellIJ). It does not hurt us as we know that our unit tests are run by a parent-first class loader where class loading works as expected. This is only an issue when dealing with parent-first loaders where the `.class` file must not exist."
] | "2016-12-26T15:08:05Z" | [
"android",
"final-class-or-methods"
] | Rename MockMethodDispatcher.class to MockMethodDispatcher.raw on build | The `org.mockito.internal.creation.bytebuddy.MockMethodDispatcher.class` file should be renamed to `org.mockito.internal.creation.bytebuddy.MockMethodDispatcher.raw` on building Mockito. This way, class loaders are no longer capable of loading the class directly what should never happen. Doing so, the bootstrap injection mechanism cannot be superseeded by child-first class loaders which break mockability due to the dispatcher class being loaded twice by two different class loaders.
This problem was observed with the Robolectrics class loader.
Additionally, the following change is required in the `InlineByteBuddyMockMaker` when creating the boot jar
```java
String source = "org/mockito/internal/creation/bytebuddy/MockMethodDispatcher";
outputStream.putNextEntry(new JarEntry(source + ".class"));
InputStream inputStream = InlineByteBuddyMockMaker.class.getClassLoader().getResourceAsStream(source + ".raw");
if (inputStream == null) {
throw new MockitoInitializationException(join(
"The MockMethodDispatcher class file could not be located " + source,
"",
"The class loader responsible: " + InlineByteBuddyMockMaker.class.getClassLoader()
));
}
try {
int length;
byte[] buffer = new byte[1024];
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
} finally {
inputStream.close();
}
outputStream.closeEntry();
``` | [
"build.gradle",
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java"
] | [
"build.gradle",
"gradle/mockito-core/inline-mock.gradle",
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java"
] | [
"src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java",
"src/test/java/org/mockito/internal/junit/JUnitRuleTest.java",
"src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java"
] | diff --git a/build.gradle b/build.gradle
index fdd11d9b4a..08d1c3d37b 100644
--- a/build.gradle
+++ b/build.gradle
@@ -23,7 +23,7 @@ ext {
artifactName = 'mockito-core'
bintrayAutoPublish = true
bintrayRepo = 'maven'
- mavenCentralSync = false
+ mavenCentralSync = true
}
allprojects {
@@ -69,6 +69,7 @@ apply from: 'gradle/root/coverage.gradle'
apply from: 'gradle/root/gradle-fix.gradle'
apply from: 'gradle/root/release.gradle'
+apply from: 'gradle/mockito-core/inline-mock.gradle'
apply from: 'gradle/mockito-core/osgi.gradle'
apply from: 'gradle/mockito-core/javadoc.gradle'
apply from: 'gradle/mockito-core/license.gradle'
diff --git a/gradle/mockito-core/inline-mock.gradle b/gradle/mockito-core/inline-mock.gradle
new file mode 100644
index 0000000000..b67300a26d
--- /dev/null
+++ b/gradle/mockito-core/inline-mock.gradle
@@ -0,0 +1,14 @@
+task copyMockMethodDispatcher(type: Copy) {
+ dependsOn compileJava
+ from "${buildDir}/classes/main/org/mockito/internal/creation/bytebuddy"
+ into "${buildDir}/classes/main/org/mockito/internal/creation/bytebuddy"
+ include "MockMethodDispatcher.class"
+ rename { String fileName ->
+ fileName.replace('.class', '.raw')
+ }
+}
+classes.dependsOn(copyMockMethodDispatcher)
+
+jar {
+ exclude("org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.class")
+}
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 c747e94605..882d12b768 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
@@ -5,7 +5,6 @@
package org.mockito.internal.creation.bytebuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
-import net.bytebuddy.dynamic.ClassFileLocator;
import org.mockito.Incubating;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.base.MockitoInitializationException;
@@ -20,6 +19,7 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Modifier;
import java.util.jar.JarEntry;
@@ -90,59 +90,91 @@
@Incubating
public class InlineByteBuddyMockMaker implements ClassCreatingMockMaker {
- private final Instrumentation instrumentation;
+ private static final Instrumentation INSTRUMENTATION;
- private final BytecodeGenerator bytecodeGenerator;
-
- private final WeakConcurrentMap<Object, MockMethodInterceptor> mocks = new WeakConcurrentMap.WithInlinedExpunction<Object, MockMethodInterceptor>();
+ private static final Throwable INITIALIZATION_ERROR;
- public InlineByteBuddyMockMaker() {
+ static {
+ Instrumentation instrumentation;
+ Throwable initializationError = null;
try {
- instrumentation = ByteBuddyAgent.install();
- if (!instrumentation.isRetransformClassesSupported()) {
- throw new MockitoInitializationException(join(
- "Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.",
- "",
- "You cannot use this mock maker on this VM:",
- Platform.describe()));
- }
- File boot = File.createTempFile("mockitoboot", "jar");
- boot.deleteOnExit();
- JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(boot));
try {
- outputStream.putNextEntry(new JarEntry("org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.class"));
- outputStream.write(ClassFileLocator.ForClassLoader.of(InlineByteBuddyMockMaker.class.getClassLoader())
- .locate("org.mockito.internal.creation.bytebuddy.MockMethodDispatcher")
- .resolve());
- outputStream.closeEntry();
- } finally {
- outputStream.close();
- }
- instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(boot));
- try {
- Class<?> dispatcher = Class.forName("org.mockito.internal.creation.bytebuddy.MockMethodDispatcher");
- if (dispatcher.getClassLoader() != null) {
- throw new MockitoInitializationException(join(
- "The MockMethodDispatcher must not be loaded manually but must be injected into the bootstrap class loader.",
+ instrumentation = ByteBuddyAgent.install();
+ if (!instrumentation.isRetransformClassesSupported()) {
+ throw new IllegalStateException(join(
+ "Byte Buddy requires retransformation for creating inline mocks. This feature is unavailable on the current VM.",
+ "",
+ "You cannot use this mock maker on this VM"));
+ }
+ File boot = File.createTempFile("mockitoboot", ".jar");
+ boot.deleteOnExit();
+ JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(boot));
+ try {
+ String source = "org/mockito/internal/creation/bytebuddy/MockMethodDispatcher";
+ InputStream inputStream = InlineByteBuddyMockMaker.class.getClassLoader().getResourceAsStream(source + ".raw");
+ if (inputStream == null) {
+ throw new IllegalStateException(join(
+ "The MockMethodDispatcher class file is not locatable: " + source + ".raw",
+ "",
+ "The class loader responsible for looking up the resource: " + InlineByteBuddyMockMaker.class.getClassLoader()
+ ));
+ }
+ outputStream.putNextEntry(new JarEntry(source + ".class"));
+ try {
+ int length;
+ byte[] buffer = new byte[1024];
+ while ((length = inputStream.read(buffer)) != -1) {
+ outputStream.write(buffer, 0, length);
+ }
+ } finally {
+ inputStream.close();
+ }
+ outputStream.closeEntry();
+ } finally {
+ outputStream.close();
+ }
+ instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(boot));
+ try {
+ 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",
"",
- "The dispatcher class was already loaded by: " + dispatcher.getClassLoader()));
+ "It seems like your current VM does not support the instrumentation API correctly."), cnfe);
}
- } catch (ClassNotFoundException cnfe) {
- throw new MockitoInitializationException(join(
- "Mockito failed to inject the MockMethodDispatcher class into the bootstrap class loader",
+ } catch (IOException ioe) {
+ throw new IllegalStateException(join(
+ "Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.",
+ "This error occured due to an I/O error during the creation of this agent: " + ioe,
"",
- "It seems like your current VM does not support the instrumentation API correctly:",
- Platform.describe()), cnfe);
+ "Potentially, the current VM does not support the instrumentation API correctly"), ioe);
}
- bytecodeGenerator = new TypeCachingBytecodeGenerator(new InlineBytecodeGenerator(instrumentation, mocks), true);
- } catch (IOException ioe) {
+ } catch (Throwable throwable) {
+ instrumentation = null;
+ initializationError = throwable;
+ }
+ INSTRUMENTATION = instrumentation;
+ INITIALIZATION_ERROR = initializationError;
+ }
+
+ private final BytecodeGenerator bytecodeGenerator;
+
+ private final WeakConcurrentMap<Object, MockMethodInterceptor> mocks = new WeakConcurrentMap.WithInlinedExpunction<Object, MockMethodInterceptor>();
+
+ public InlineByteBuddyMockMaker() {
+ if (INITIALIZATION_ERROR != null) {
throw new MockitoInitializationException(join(
- "Mockito could not self-attach a Java agent to the current VM. This feature is required for inline mocking.",
- "This error occured due to an I/O error during the creation of this agent: " + ioe,
+ "Could not initialize inline Byte Buddy mock maker. (This mock maker is not supported on Android.)",
"",
- "Potentially, the current VM does not support the instrumentation API correctly:",
- Platform.describe()), ioe);
+ Platform.describe()), INITIALIZATION_ERROR);
}
+ bytecodeGenerator = new TypeCachingBytecodeGenerator(new InlineBytecodeGenerator(INSTRUMENTATION, mocks), true);
}
@Override
@@ -260,7 +292,7 @@ public TypeMockability isTypeMockable(final Class<?> type) {
return new TypeMockability() {
@Override
public boolean mockable() {
- return instrumentation.isModifiableClass(type) && !EXCLUDES.contains(type);
+ return INSTRUMENTATION.isModifiableClass(type) && !EXCLUDES.contains(type);
}
@Override
@@ -278,4 +310,24 @@ public String nonMockableReason() {
}
};
}
+
+ static Throwable hideRecursiveCall(Throwable throwable, int current, Class<?> targetType) {
+ try {
+ StackTraceElement[] stack = throwable.getStackTrace();
+ int skip = 0;
+ StackTraceElement next;
+ do {
+ next = stack[stack.length - current - ++skip];
+ } while (!next.getClassName().equals(targetType.getName()));
+ int top = stack.length - current - skip;
+ StackTraceElement[] cleared = new StackTraceElement[stack.length - skip];
+ System.arraycopy(stack, 0, cleared, 0, top);
+ System.arraycopy(stack, top + skip, cleared, top, current);
+ throwable.setStackTrace(cleared);
+ return throwable;
+ } catch (RuntimeException ignored) {
+ // This should not happen unless someone instrumented or manipulated exception stack traces.
+ return throwable;
+ }
+ }
}
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 7f6483fc7a..394bd2d2eb 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
@@ -23,6 +23,8 @@
import java.lang.reflect.Modifier;
import java.util.concurrent.Callable;
+import static org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.hideRecursiveCall;
+
public class MockMethodAdvice extends MockMethodDispatcher {
final WeakConcurrentMap<Object, MockMethodInterceptor> interceptors;
@@ -180,26 +182,6 @@ private static Object tryInvoke(Method origin, Object instance, Object[] argumen
}
}
- static Throwable hideRecursiveCall(Throwable throwable, int current, Class<?> targetType) {
- try {
- StackTraceElement[] stack = throwable.getStackTrace();
- int skip = 0;
- StackTraceElement next;
- do {
- next = stack[stack.length - current - ++skip];
- } while (!next.getClassName().equals(targetType.getName()));
- int top = stack.length - current - skip;
- StackTraceElement[] cleared = new StackTraceElement[stack.length - skip];
- System.arraycopy(stack, 0, cleared, 0, top);
- System.arraycopy(stack, top + skip, cleared, top, current);
- throwable.setStackTrace(cleared);
- return throwable;
- } catch (RuntimeException ignored) {
- // This should not happen unless someone instrumented or manipulated exception stack traces.
- return throwable;
- }
- }
-
private static class ReturnValueWrapper implements Callable<Object> {
private final Object returned;
| 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 3b5256dae4..ee36f6de77 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
@@ -1,10 +1,5 @@
package org.mockito.internal.creation.bytebuddy;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Observable;
-import java.util.Observer;
-import java.util.regex.Pattern;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.modifier.Visibility;
@@ -21,6 +16,12 @@
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.regex.Pattern;
+
import static net.bytebuddy.ClassFileVersion.JAVA_V8;
import static net.bytebuddy.ClassFileVersion.JAVA_V9;
import static net.bytebuddy.matcher.ElementMatchers.named;
@@ -157,7 +158,7 @@ public void should_remove_recursive_self_call_from_stack_trace() throws Exceptio
Throwable throwable = new Throwable();
throwable.setStackTrace(stack);
- throwable = MockMethodAdvice.hideRecursiveCall(throwable, 2, SampleInterface.class);
+ throwable = InlineByteBuddyMockMaker.hideRecursiveCall(throwable, 2, SampleInterface.class);
assertThat(throwable.getStackTrace()).isEqualTo(new StackTraceElement[]{
new StackTraceElement("foo", "", "", -1),
@@ -170,7 +171,7 @@ public void should_remove_recursive_self_call_from_stack_trace() throws Exceptio
public void should_handle_missing_or_inconsistent_stack_trace() throws Exception {
Throwable throwable = new Throwable();
throwable.setStackTrace(new StackTraceElement[0]);
- assertThat(MockMethodAdvice.hideRecursiveCall(throwable, 0, SampleInterface.class)).isSameAs(throwable);
+ assertThat(InlineByteBuddyMockMaker.hideRecursiveCall(throwable, 0, SampleInterface.class)).isSameAs(throwable);
}
@Test
@@ -263,6 +264,11 @@ private static <T> MockCreationSettings<T> settingsFor(Class<T> type, Class<?>..
return mockSettings;
}
+ @Test
+ public void testMockDispatcherIsRelocated() throws Exception {
+ assertThat(InlineByteBuddyMockMaker.class.getClassLoader().getResource("org/mockito/internal/creation/bytebuddy/MockMethodDispatcher.raw")).isNotNull();
+ }
+
private static final class FinalClass {
public String foo() {
diff --git a/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java b/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java
index b7da8bb5f7..8ae318b576 100644
--- a/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java
+++ b/src/test/java/org/mockito/internal/junit/JUnitRuleTest.java
@@ -44,4 +44,4 @@ public void does_not_check_invalid_mockito_usage_on_failure() throws Throwable {
Mockito.when(mock.simpleMethod()); // <--- unfinished stubbing
throw new RuntimeException("foo"); // <--- some failure
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
index 59f766fed9..d39fa14290 100644
--- a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
+++ b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
@@ -1,6 +1,7 @@
package org.mockitointegration;
import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.agent.ByteBuddyAgent;
import org.hamcrest.Matcher;
import org.junit.Assume;
import org.junit.Test;
@@ -9,6 +10,7 @@
import org.mockitoutil.ClassLoaders;
import org.objenesis.Objenesis;
+import java.util.Arrays;
import java.util.Set;
import static org.mockitoutil.ClassLoaders.coverageTool;
@@ -24,6 +26,7 @@ public void pure_mockito_should_not_depend_JUnit___ByteBuddy() throws Exception
Mockito.class,
Matcher.class,
ByteBuddy.class,
+ ByteBuddyAgent.class,
Objenesis.class
)
.withCodeSourceUrlOf(coverageTool())
@@ -32,6 +35,10 @@ public void pure_mockito_should_not_depend_JUnit___ByteBuddy() throws Exception
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");
+ pureMockitoAPIClasses.remove("org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker");
+
for (String pureMockitoAPIClass : pureMockitoAPIClasses) {
checkDependency(classLoader_without_JUnit, pureMockitoAPIClass);
}
| test | train | 2016-12-26T06:52:39 | "2016-12-26T12:25:45Z" | raphw | train |
mockito/mockito/866_867 | mockito/mockito | mockito/mockito/866 | mockito/mockito/867 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8665890352634279)"
] | d972c99572ed038078c5a755c4afd41b0e8f9d28 | f86a598594e4c732a13193fc95a00b5775099631 | [
"This is a bug in the user code. Yet Mockito should handle that gracefully.\r\n\r\nThanks for reporting."
] | [
"Actually I'd rather make the check in `ConditionalStackTraceFilter.filter()`. And if throwable is null, just return.",
"Ok! already changed,please review. ",
"Sorry it seems I was wrong. It seems that indeed your previous attempt was correct.\r\n\r\n```java\r\n if (t == null) {\r\n throw throwable;\r\n }\r\n```",
"Ok, But I don't know why the build is failing?\r\n\r\n> Execution failed for task ':assertEnvVariables'.\r\n> Please export 'GH_TOKEN' env variable first. Expression: java.lang.System.env[it]. Values: it = GH_TOKEN",
"Yes I'm sure your change is correct, it's something else.",
"Discarding this comment as it requires to rewrite `filter` a bit more."
] | "2017-01-04T14:16:26Z" | [
"bug"
] | When custom exception fillInstackTrace() returns null, Exception mock cannot work properly | ```java
public class CustomException extends Exception {
public CustomException() {
super();
}
@Override
public Exception fillInStackTrace() {
return null;
}
}
```
TestCase like this
```java
when(demo.process()).thenThrow(new CustomException())
//... test code
```
```
java.lang.NullPointerException
at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.filter(ConditionalStackTraceFilter.java:23)
at org.mockito.internal.stubbing.answers.ThrowsException.answer(ThrowsException.java:32)
at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:35)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:95)
```
| [
"src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java"
] | [
"src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java"
] | [
"src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java
index d323e80b9e..037520fee3 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java
@@ -29,6 +29,10 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
throw throwable;
}
Throwable t = throwable.fillInStackTrace();
+
+ if (t == null) {
+ throw throwable;
+ }
filter.filter(t);
throw t;
}
| diff --git a/src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.java b/src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.java
new file mode 100644
index 0000000000..50acbad954
--- /dev/null
+++ b/src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.java
@@ -0,0 +1,32 @@
+package org.mockitousage.bugs;
+
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+import static junit.framework.TestCase.fail;
+import static org.mockito.Mockito.when;
+
+public class NPEWhenCustomExceptionStackTraceReturnNullTest extends TestBase {
+
+ @Mock
+ IMethods mock;
+
+ class NullStackTraceException extends RuntimeException {
+ @Override
+ public Exception fillInStackTrace() {
+ return null;
+ }
+ }
+
+ //issue 866
+ @Test
+ public void shouldNotThrowNPE() {
+ when(mock.simpleMethod()).thenThrow(new NullStackTraceException());
+ try {
+ mock.simpleMethod();
+ fail();
+ } catch(NullStackTraceException e) {}
+ }
+}
| val | train | 2017-01-04T15:52:28 | "2017-01-03T08:29:31Z" | wuwen5 | train |
mockito/mockito/879_880 | mockito/mockito | mockito/mockito/879 | mockito/mockito/880 | [
"timestamp(timedelta=50952.0, similarity=0.9218907831467025)"
] | 64c2f61274a59eb3d86f1f122d71a80d9a1231be | fd2a49b33d878d5080c70dfe876bc5da2fed7cf1 | [
"@TimvdLippe should this issue be closed now that the PR is merged, or should this fix be backported to the 2.x branch too?",
"@mureinik Oh right it was to the wrong branch 😭 That's my mistake. I will backport it manually"
] | [] | "2017-01-12T20:38:56Z" | [] | Grammar issue in ArgumentMatchers' javadoc. | [`ArgumentMatchers`' javadoc](https://static.javadoc.io/org.mockito/mockito-core/2.6.1/org/mockito/ArgumentMatchers.html) states that:
> This implementation is due static type safety imposed by java compiler.
There's a word missing there. It should read:
> This implementation is due **to** static type safety imposed by java compiler.
Version info:
- First noticed this on 2.5.5
- Confirmed it still existed in 2.5.6, 2.5.7 and 2.6.1
- Probably also existed in previous versions. | [
"src/main/java/org/mockito/ArgumentMatchers.java"
] | [
"src/main/java/org/mockito/ArgumentMatchers.java"
] | [] | diff --git a/src/main/java/org/mockito/ArgumentMatchers.java b/src/main/java/org/mockito/ArgumentMatchers.java
index 56ff53311f..a28eaafe36 100644
--- a/src/main/java/org/mockito/ArgumentMatchers.java
+++ b/src/main/java/org/mockito/ArgumentMatchers.java
@@ -91,7 +91,7 @@
* <p>
* Matcher methods like <code>anyObject()</code>, <code>eq()</code> <b>do not</b> return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
- * This implementation is due static type safety imposed by java compiler.
+ * This implementation is due to static type safety imposed by java compiler.
* The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
* </p>
*
| null | val | train | 2017-01-04T16:02:14 | "2017-01-12T20:35:12Z" | mureinik | train |
mockito/mockito/882_884 | mockito/mockito | mockito/mockito/882 | mockito/mockito/884 | [
"timestamp(timedelta=42649.0, similarity=0.9349826054048819)"
] | fd2a49b33d878d5080c70dfe876bc5da2fed7cf1 | 695eb9bf2cd8c76cdcdb91bf68b9292894249d44 | [] | [] | "2017-01-14T09:11:11Z" | [
"java-9"
] | Upgrading to Objenesis 2.5 | Mockito already uses Objenesis 2.4.
However Objenesis 2.5 was just released and supports the latest [JDK 9 build 151 jigsaw](http://objenesis.org/notes.html) | [
"build.gradle",
"gradle/mockito-core/osgi.gradle"
] | [
"build.gradle",
"gradle/mockito-core/osgi.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index f363fd2557..72a2e65524 100644
--- a/build.gradle
+++ b/build.gradle
@@ -50,7 +50,7 @@ dependencies {
compile 'net.bytebuddy:byte-buddy-agent:1.5.12'
provided "junit:junit:4.12", "org.hamcrest:hamcrest-core:1.3"
- compile "org.objenesis:objenesis:2.4"
+ compile "org.objenesis:objenesis:2.5"
testCompile 'org.ow2.asm:asm:5.1'
@@ -94,4 +94,4 @@ buildScan {
licenseAgree = 'yes'
recipes 'git-commit', 'travis-ci'
-}
\ No newline at end of file
+}
diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle
index dfed1fe321..227b116b10 100644
--- a/gradle/mockito-core/osgi.gradle
+++ b/gradle/mockito-core/osgi.gradle
@@ -20,7 +20,7 @@ afterEvaluate {
'junit.*;resolution:=optional',
'org.junit.*;resolution:=optional',
'org.hamcrest;resolution:=optional',
- 'org.objenesis;version="[2.4,3.0)"',
+ 'org.objenesis;version="[2.5,3.0)"',
'org.mockito.*'
instruction 'Private-Package',
| null | train | train | 2017-01-12T21:45:02 | "2017-01-13T15:05:44Z" | bric3 | train |
mockito/mockito/871_886 | mockito/mockito | mockito/mockito/871 | mockito/mockito/886 | [
"keyword_pr_to_issue"
] | 9ff4fa2e0e6246035c3441fac172cc179590e4f3 | 307cffd4201395ab304c3842bc74dc11336243ae | [
"I think the easiest solution is to not assert the GH_TOKEN if the build is a pull request",
"Can't we just disable the checks if the repo is not mockito/mockito ?",
"Pull requests always have `mockito/mockito` as repository?",
"No only ours, external contributors have a fork. Since the GH_TOKEN assertion don't fail for our pull request I think this is safe assumption.",
"@szczepiq could you make this high priority on your list? Failing builds discourages external developers from publishing their work"
] | [] | "2017-01-15T18:57:07Z" | [
"bug",
"continuous integration"
] | Travis builds from non-core developers fail on assertEnvVariables | Example build: https://travis-ci.org/mockito/mockito/jobs/188911380
Seems that this does not affect core developers, as my build has been succesful: https://travis-ci.org/mockito/mockito/builds/188321204 as well as those in #865 and #859 | [
"gradle/root/release.gradle"
] | [
"gradle/root/release.gradle"
] | [] | diff --git a/gradle/root/release.gradle b/gradle/root/release.gradle
index 44d938bc72..821070ff99 100644
--- a/gradle/root/release.gradle
+++ b/gradle/root/release.gradle
@@ -254,10 +254,10 @@ task pushChanges(type: Exec) {
}
releaseWorkflow {
- step assertEnvVariables
- step assertCleanWorkingCopy
step releaseNeeded
onlyIf { releaseNeeded.needed }
+ step assertEnvVariables
+ step assertCleanWorkingCopy
step bintrayUploadAll //TODO make upload task the very last task or very close to push so that the most invasive steps go last
step pullCommits
step configureGenericGitUser, [cleanup: restoreGitUser]
| null | val | train | 2017-01-13T11:58:06 | "2017-01-06T14:41:43Z" | TimvdLippe | train |
mockito/mockito/882_887 | mockito/mockito | mockito/mockito/882 | mockito/mockito/887 | [
"timestamp(timedelta=0.0, similarity=0.9349826054048819)"
] | 307cffd4201395ab304c3842bc74dc11336243ae | b6e844d69b0cbec90fc5714513b09be7c0676a4e | [] | [] | "2017-01-15T20:51:27Z" | [
"java-9"
] | Upgrading to Objenesis 2.5 | Mockito already uses Objenesis 2.4.
However Objenesis 2.5 was just released and supports the latest [JDK 9 build 151 jigsaw](http://objenesis.org/notes.html) | [
"build.gradle",
"gradle/mockito-core/osgi.gradle"
] | [
"build.gradle",
"gradle/mockito-core/osgi.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index 2eac447f58..7b9b8da4a3 100644
--- a/build.gradle
+++ b/build.gradle
@@ -49,7 +49,7 @@ dependencies {
compile 'net.bytebuddy:byte-buddy-agent:1.6.2'
provided "junit:junit:4.12", "org.hamcrest:hamcrest-core:1.3"
- compile "org.objenesis:objenesis:2.4"
+ compile "org.objenesis:objenesis:2.5"
testCompile 'org.ow2.asm:asm:5.1'
@@ -91,4 +91,4 @@ release.mustRunAfter ciBuild //Making sure that release task is only invoked aft
buildScan {
licenseAgreementUrl = 'https://gradle.com/terms-of-service'
licenseAgree = 'yes'
-}
\ No newline at end of file
+}
diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle
index 05d99eec94..2b0eb65fee 100644
--- a/gradle/mockito-core/osgi.gradle
+++ b/gradle/mockito-core/osgi.gradle
@@ -20,7 +20,7 @@ afterEvaluate {
'junit.*;resolution:=optional',
'org.junit.*;resolution:=optional',
'org.hamcrest;resolution:=optional',
- 'org.objenesis;version="[2.4,3.0)"',
+ 'org.objenesis;version="[2.5,3.0)"',
'org.mockito.*'
instruction 'Private-Package',
| null | test | train | 2017-01-15T20:13:00 | "2017-01-13T15:05:44Z" | bric3 | train |
mockito/mockito/895_896 | mockito/mockito | mockito/mockito/895 | mockito/mockito/896 | [
"timestamp(timedelta=0.0, similarity=0.9721334097970477)",
"keyword_pr_to_issue"
] | e983acdef8da0076f1980f622363d179e1eff680 | 46aab5420904b731c4351c6fcd250f647a8f90ba | [
"I am going to submit a Pull Request, adding an additional clarification with code example in the docs."
] | [
"I'd rephrase to : \r\n\r\n```\r\n<strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with same matchers or arguments are used then each stubbing will override the previous one :\r\n```",
"Sure, sounds much better. I'm going to update the PR to this."
] | "2017-01-20T15:51:46Z" | [
"docs"
] | Documentation missing clarification for consecutive stubbing | The [documentation](https://static.javadoc.io/org.mockito/mockito-core/2.6.3/org/mockito/Mockito.html#10) for consecutive stubbing is missing a clarification.
When multiple when/thenReturn statements are being used instead of chaining .thenReturn() statements, each stubbing overrides the existing one.
| [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 228997d4b0..27f0768054 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -452,6 +452,16 @@
* .thenReturn("one", "two", "three");
* </code></pre>
*
+ * <strong>Warning</strong> : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments
+ * is used, then each stubbing will override the previous one:
+ *
+ * <pre class="code"><code class="java">
+ * //All mock.someMethod("some arg") calls will return "two"
+ * when(mock.someMethod("some arg"))
+ * .thenReturn("one")
+ * when(mock.someMethod("some arg"))
+ * .thenReturn("two")
+ * </code></pre>
*
*
*
| null | train | train | 2017-01-19T18:12:14 | "2017-01-20T15:42:19Z" | dimosr | train |
mockito/mockito/876_897 | mockito/mockito | mockito/mockito/876 | mockito/mockito/897 | [
"keyword_pr_to_issue"
] | 695eb9bf2cd8c76cdcdb91bf68b9292894249d44 | 783d1fa37e3a7d483ed56907262424631a3442d9 | [
"Do you mean argument matcher or mock return values?",
"I mean default return value of a mock.",
"Here is a quick fix, sadly I can't push throu the firewall.\r\n\r\n```java\r\nif (type.isArray()) {\r\n Class<?> componentType = type.getComponentType();\r\n return Array.newInstance(componentType, 0);\r\n}\r\n```\r\n\r\nneeds to added to [ReturnsEmptyValues::returnValueFor(Class)](https://github.com/mockito/mockito/blob/release/2.x/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java#L79).",
"Seems like String has also no empty return value.",
"Yes the fix is quite easy. I haven't pushed it yet. I'm focused on the selection of the Devoxx France CFP right now.\r\n\r\n`String` was discussed, at some point but most people felt `null` was a sane default even for `String`.",
"Please consider backwards compatibility when implementing the fix. Thanks!\r\n",
"That's indeed a good point, I'm hesitating. Since mockito returns non null collections, it seems a consistent to return a non null array by default too.\r\n\r\nIf merging this one in mockito 2, that may break tests that rely on the default behavior only.\r\nThat requires at the very least a minor version bumb. I'm quite enclined to get it right in mockito 2, but it could it wait for mockito 3.\r\n\r\n",
"While cleaning stuff, just noticed there's a `ReturnsMoreEmptyValues` that already do that.\r\n\r\nHowever it does more things than simply retuning non emtpy arrays. It returns empty strings too.",
"Nice catch! ReturnsMoreEmptyValues was intended to replace ReturnEmptyValues in the next major version of Mockito. However, it was deprioritized and/or forgotten and we never got to do it.\r\n\r\nIncluding this change in Mockito 2 will potentially break tests. The failure may not be easy to debug / understand (sudden change of behavior of test). Such changes should only be included in major version update and well documented. Given our strong desire for compatibility, let's include it in Mockito 3. I suggest we also review other empty / default return values in Mockito 3.",
"@szczepiq Yes in the end I only pushed the change to target master in #897 "
] | [
"If this class now only returns an emptry String, why don't we remove this class and move the empty string to `ReturnsEmptyValues`?",
"Actually I don't think that's part of this PR. And I find that returning empty string instead of `null` more debattable (hence a separate PR).",
"Oh nice! It's good to take advantage of Java8!",
"Fantastic! Less code to maintain.",
"I like the idea to condense the tests into 2 methods.",
"As general feedback, not particularly to this PR, I'm +1 to returning empty String. We can poll more feedback from the community. Empty String seems like a better default, avoiding potential NPE. The idea behind the defaults is to return the most sensible value if the user does not care about the mock.",
"@szczepiq Let's create another PR for default Strings, it'll be easier to track for end users as it will appear in the changelog."
] | "2017-01-21T13:48:22Z" | [
"enhancement",
"in progress"
] | Mockito should return an empty array for default values | Mockito returns by default interesting default values for some types :
* Long ⇒ 0
* Optional ⇒ Optional.empty
* List => new ArrayList(0)
But it don't return an empty array currently. | [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java",
"src/main/java/org/mockito/internal/util/JavaEightUtil.java"
] | [
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java",
"src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java"
] | [
"src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java",
"src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java",
"src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValuesTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
index 2216cca7aa..e667b19811 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
@@ -4,9 +4,31 @@
*/
package org.mockito.internal.stubbing.defaultanswers;
-import org.mockito.internal.util.JavaEightUtil;
+import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalDouble;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.Stream;
import org.mockito.internal.util.MockUtil;
-import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.internal.util.Primitives;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.mock.MockName;
@@ -15,36 +37,19 @@
import static org.mockito.internal.util.ObjectMethodsGuru.isCompareToMethod;
import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
-import java.io.Serializable;
-import java.util.*;
-
/**
* Default answer of every Mockito mock.
* <ul>
- * <li>
- * Returns appropriate primitive for primitive-returning methods
- * </li>
- * <li>
- * Returns consistent values for primitive wrapper classes (e.g. int-returning method returns 0 <b>and</b> Integer-returning method returns 0, too)
- * </li>
- * <li>
- * Returns empty collection for collection-returning methods (works for most commonly used collection types)
- * </li>
- * <li>
- * Returns description of mock for toString() method
- * </li>
- * <li>
- * Returns zero if references are equals otherwise non-zero for Comparable#compareTo(T other) method (see issue 184)
- * </li>
- * <li>
- * Returns an {@code java.util.Optional#empty() empty Optional} for Optional. Similarly for primitive optional variants.
- * </li>
- * <li>
- * Returns an {@code java.util.stream.Stream#empty() empty Stream} for Stream. Similarly for primitive stream variants.
- * </li>
- * <li>
- * Returns null for everything else
- * </li>
+ * <li>Returns appropriate primitive for primitive-returning methods</li>
+ * <li>Returns consistent values for primitive wrapper classes (e.g. int-returning method returns 0 <strong>and</strong>
+ * Integer-returning method returns 0, too)</li>
+ * <li>Returns empty collection for collection-returning methods (works for most commonly used collection types)</li>
+ * <li>Returns empty array for array-returning methods</li>
+ * <li>Returns description of mock for toString() method</li>
+ * <li>Returns zero if references are equals otherwise non-zero for Comparable#compareTo(T other) method (see issue 184)</li>
+ * <li>Returns an {@link java.util.Optional#empty() empty Optional} for Optional. Similarly for primitive optional variants.</li>
+ * <li>Returns an {@link java.util.stream.Stream#empty() empty Stream} for Stream. Similarly for primitive stream variants.</li>
+ * <li>Returns null for everything else</li>
* </ul>
*/
public class ReturnsEmptyValues implements Answer<Object>, Serializable {
@@ -52,9 +57,6 @@ public class ReturnsEmptyValues implements Answer<Object>, Serializable {
private static final long serialVersionUID = 1998191268711234347L;
- /* (non-Javadoc)
- * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
- */
public Object answer(InvocationOnMock invocation) {
if (isToStringMethod(invocation.getMethod())) {
Object mock = invocation.getMock();
@@ -80,6 +82,9 @@ Object returnValueFor(Class<?> type) {
return Primitives.defaultValue(type);
//new instances are used instead of Collections.emptyList(), etc.
//to avoid UnsupportedOperationException if code under test modifies returned collection
+ } else if (type.isArray()) {
+ Class<?> componentType = type.getComponentType();
+ return Array.newInstance(componentType, 0);
} else if (type == Iterable.class) {
return new ArrayList<Object>(0);
} else if (type == Collection.class) {
@@ -110,22 +115,22 @@ Object returnValueFor(Class<?> type) {
return new TreeMap<Object, Object>();
} else if (type == LinkedHashMap.class) {
return new LinkedHashMap<Object, Object>();
- } else if ("java.util.Optional".equals(type.getName())) {
- return JavaEightUtil.emptyOptional();
- } else if ("java.util.OptionalDouble".equals(type.getName())) {
- return JavaEightUtil.emptyOptionalDouble();
- } else if ("java.util.OptionalInt".equals(type.getName())) {
- return JavaEightUtil.emptyOptionalInt();
- } else if ("java.util.OptionalLong".equals(type.getName())) {
- return JavaEightUtil.emptyOptionalLong();
- } else if ("java.util.stream.Stream".equals(type.getName())) {
- return JavaEightUtil.emptyStream();
- } else if ("java.util.stream.DoubleStream".equals(type.getName())) {
- return JavaEightUtil.emptyDoubleStream();
- } else if ("java.util.stream.IntStream".equals(type.getName())) {
- return JavaEightUtil.emptyIntStream();
- } else if ("java.util.stream.LongStream".equals(type.getName())) {
- return JavaEightUtil.emptyLongStream();
+ } else if (type == Optional.class) {
+ return Optional.empty();
+ } else if (type == OptionalDouble.class) {
+ return OptionalDouble.empty();
+ } else if (type == OptionalInt.class) {
+ return OptionalInt.empty();
+ } else if (type == OptionalLong.class) {
+ return OptionalLong.empty();
+ } else if (type == Stream.class) {
+ return Stream.empty();
+ } else if (type == DoubleStream.class) {
+ return DoubleStream.empty();
+ } else if (type == IntStream.class) {
+ return IntStream.empty();
+ } else if (type == LongStream.class) {
+ return LongStream.empty();
}
//Let's not care about the rest of collections.
diff --git a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
index 179f7ddc8b..0b612ef4c9 100644
--- a/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
+++ b/src/main/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
@@ -6,7 +6,6 @@
package org.mockito.internal.stubbing.defaultanswers;
import java.io.Serializable;
-import java.lang.reflect.Array;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -16,42 +15,18 @@
* <p>
* Currently <b>used only</b> by {@link Mockito#RETURNS_SMART_NULLS}
* <p>
- * Current version of Mockito mocks by deafult use {@link ReturnsEmptyValues}
+ * Current version of Mockito mocks by default use {@link ReturnsEmptyValues}
* <ul>
- * <li>
- * Returns appropriate primitive for primitive-returning methods
- * </li>
- * <li>
- * Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 <b>and</b> Integer-returning method returns 0, too)
- * </li>
- * <li>
- * Returns empty collection for collection-returning methods (works for most commonly used collection types)
- * </li>
- * <li>
- * Returns empty array for array-returning methods
- * </li>
- * <li>
- * Returns "" for String-returning method
- * </li>
- * <li>
- * Returns description of mock for toString() method
- * </li>
- * <li>
- * Returns non-zero for Comparable#compareTo(T other) method (see issue 184)
- * </li>
- * <li>
- * Returns null for everything else
- * </li>
+ * <li>Returns empty values of {@link ReturnsEmptyValues}</li>
+ * <li>Returns "" for String-returning method</li>
+ * <li>Returns null for everything else</li>
* </ul>
*/
public class ReturnsMoreEmptyValues implements Answer<Object>, Serializable {
-
+
private static final long serialVersionUID = -2816745041482698471L;
private final Answer<Object> delegate = new ReturnsEmptyValues();
-
- /* (non-Javadoc)
- * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
- */
+
public Object answer(InvocationOnMock invocation) throws Throwable {
Object ret = delegate.answer(invocation);
if (ret != null) {
@@ -61,13 +36,10 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
Class<?> returnType = invocation.getMethod().getReturnType();
return returnValueFor(returnType);
}
-
+
Object returnValueFor(Class<?> type) {
if (type == String.class) {
return "";
- } else if (type.isArray()) {
- Class<?> componentType = type.getComponentType();
- return Array.newInstance(componentType, 0);
}
return null;
}
diff --git a/src/main/java/org/mockito/internal/util/JavaEightUtil.java b/src/main/java/org/mockito/internal/util/JavaEightUtil.java
deleted file mode 100644
index 80ac6353c1..0000000000
--- a/src/main/java/org/mockito/internal/util/JavaEightUtil.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (c) 2016 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.util;
-
-import org.mockito.internal.creation.instance.InstantiationException;
-
-import java.lang.reflect.Method;
-
-/**
- * Helper class to work with features that were introduced in Java versions after 1.5.
- * This class uses reflection in most places to avoid coupling with a newer JDK.
- */
-public final class JavaEightUtil {
-
- // No need for volatile, these optionals are already safe singletons.
- private static Object emptyOptional;
- private static Object emptyOptionalDouble;
- private static Object emptyOptionalInt;
- private static Object emptyOptionalLong;
-
- private JavaEightUtil() {
- // utility class
- }
-
- /**
- * Creates an empty Optional using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty Optional.
- */
- public static Object emptyOptional() {
- // no need for double-checked locking
- if (emptyOptional != null) {
- return emptyOptional;
- }
-
- return emptyOptional = invokeNullaryFactoryMethod("java.util.Optional", "empty");
- }
-
-
- /**
- * Creates an empty OptionalDouble using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty OptionalDouble.
- */
- public static Object emptyOptionalDouble() {
- // no need for double-checked locking
- if (emptyOptionalDouble != null) {
- return emptyOptionalDouble;
- }
-
- return emptyOptionalDouble = invokeNullaryFactoryMethod("java.util.OptionalDouble", "empty");
- }
-
- /**
- * Creates an empty OptionalInt using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty OptionalInt.
- */
- public static Object emptyOptionalInt() {
- // no need for double-checked locking
- if (emptyOptionalInt != null) {
- return emptyOptionalInt;
- }
-
- return emptyOptionalInt = invokeNullaryFactoryMethod("java.util.OptionalInt", "empty");
- }
-
- /**
- * Creates an empty OptionalLong using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty OptionalLong.
- */
- public static Object emptyOptionalLong() {
- // no need for double-checked locking
- if (emptyOptionalLong != null) {
- return emptyOptionalLong;
- }
-
- return emptyOptionalLong = invokeNullaryFactoryMethod("java.util.OptionalLong", "empty");
- }
-
- /**
- * Creates an empty Stream using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty Stream.
- */
- public static Object emptyStream() {
- // note: the empty stream can not be stored as a singleton.
- return invokeNullaryFactoryMethod("java.util.stream.Stream", "empty");
- }
-
- /**
- * Creates an empty DoubleStream using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty DoubleStream.
- */
- public static Object emptyDoubleStream() {
- // note: the empty stream can not be stored as a singleton.
- return invokeNullaryFactoryMethod("java.util.stream.DoubleStream", "empty");
- }
-
- /**
- * Creates an empty IntStream using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty IntStream.
- */
- public static Object emptyIntStream() {
- // note: the empty stream can not be stored as a singleton.
- return invokeNullaryFactoryMethod("java.util.stream.IntStream", "empty");
- }
-
- /**
- * Creates an empty LongStream using reflection to stay backwards-compatible with older JDKs.
- *
- * @return an empty LongStream.
- */
- public static Object emptyLongStream() {
- // note: the empty stream can not be stored as a singleton.
- return invokeNullaryFactoryMethod("java.util.stream.LongStream", "empty");
- }
-
- /**
- * Invokes a nullary static factory method using reflection to stay backwards-compatible with older JDKs.
- *
- * @param fqcn The fully qualified class name of the type to be produced.
- * @param methodName The name of the factory method.
- * @return the object produced.
- */
- private static Object invokeNullaryFactoryMethod(final String fqcn, final String methodName) {
- try {
- final Class<?> type = Class.forName(fqcn);
- final Method method = type.getMethod(methodName);
-
- return method.invoke(null);
- // any exception is really unexpected since the type name has
- // already been verified
- } catch (final Exception e) {
- throw new InstantiationException(
- String.format("Could not create %s#%s(): %s", fqcn, methodName, e), e);
- }
- }
-}
| diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
index 4406499946..734a6ace7d 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
@@ -28,7 +28,7 @@ public void should_throw_mock_exception_without_stacktrace() throws Exception {
new ThrowsException(mock(Exception.class)).answer(new InvocationBuilder().method("canThrowException").toInvocation());
Assertions.fail("should have raised wanted exception");
} catch (Throwable throwable) {
- assertThat(throwable.getStackTrace()).describedAs("no stack trace, it's mock").isNull();
+ assertThat(throwable.getStackTrace()).describedAs("no stack trace, it's mock").isEmpty();
}
}
diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
index ab9aad9bd1..861dd5472a 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValuesTest.java
@@ -5,14 +5,38 @@
package org.mockito.internal.stubbing.defaultanswers;
-import org.junit.Assume;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalDouble;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.Stream;
import org.junit.Test;
import org.mockito.invocation.Invocation;
import org.mockitoutil.TestBase;
-import java.util.*;
-
-import static junit.framework.TestCase.*;
+import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.assertFalse;
+import static junit.framework.TestCase.assertNull;
+import static junit.framework.TestCase.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class ReturnsEmptyValuesTest extends TestBase {
@@ -21,6 +45,8 @@ public class ReturnsEmptyValuesTest extends TestBase {
@Test
public void should_return_empty_collections_or_null_for_non_collections() {
+ assertTrue(((Number[]) values.returnValueFor(Number[].class)).length == 0);
+
assertTrue(((Collection<?>) values.returnValueFor(Collection.class)).isEmpty());
assertTrue(((Set<?>) values.returnValueFor(Set.class)).isEmpty());
@@ -90,84 +116,18 @@ public void should_return_zero_if_mock_is_compared_to_itself() {
@Test
public void should_return_empty_Optional() throws Exception {
- verify_empty_Optional_is_returned("java.util.stream.Stream", "java.util.Optional");
- }
-
- @Test
- public void should_return_empty_OptionalDouble() throws Exception {
- verify_empty_Optional_is_returned("java.util.stream.DoubleStream", "java.util.OptionalDouble");
- }
-
- @Test
- public void should_return_empty_OptionalInt() throws Exception {
- verify_empty_Optional_is_returned("java.util.stream.IntStream", "java.util.OptionalInt");
- }
-
- @Test
- public void should_return_empty_OptionalLong() throws Exception {
- verify_empty_Optional_is_returned("java.util.stream.LongStream", "java.util.OptionalLong");
- }
-
- private void verify_empty_Optional_is_returned(String streamFqcn, String optionalFqcn) throws Exception {
- Class<?> streamType = getClassOrSkipTest(streamFqcn);
-
- //given
- Object stream = mock(streamType);
- Object optional = streamType.getMethod("findAny").invoke(stream);
- assertNotNull(optional);
- assertFalse((Boolean) Class.forName(optionalFqcn).getMethod("isPresent").invoke(optional));
-
- Invocation findAny = this.getLastInvocation();
-
- //when
- Object result = values.answer(findAny);
-
- //then
- assertEquals(optional, result);
- }
-
- @Test
- public void should_return_empty_Stream() throws Exception {
- verify_empty_Stream_is_returned("java.util.stream.Stream");
- }
-
- @Test
- public void should_return_empty_DoubleStream() throws Exception {
- verify_empty_Stream_is_returned("java.util.stream.DoubleStream");
- }
-
- @Test
- public void should_return_empty_IntStream() throws Exception {
- verify_empty_Stream_is_returned("java.util.stream.IntStream");
+ assertThat((Optional) values.returnValueFor(Optional.class)).isEmpty();
+ assertThat((OptionalInt) values.returnValueFor(OptionalInt.class)).isEmpty();
+ assertThat((OptionalLong) values.returnValueFor(OptionalLong.class)).isEmpty();
+ assertThat((OptionalDouble) values.returnValueFor(OptionalDouble.class)).isEmpty();
}
@Test
- public void should_return_empty_LongStream() throws Exception {
- verify_empty_Stream_is_returned("java.util.stream.LongStream");
- }
-
- private void verify_empty_Stream_is_returned(String streamFqcn) throws Exception {
- // given
- Class<?> streamType = getClassOrSkipTest(streamFqcn);
-
- // when
- Object stream = values.returnValueFor(streamType);
- long count = (Long) streamType.getMethod("count").invoke(stream);
-
- // then
- assertEquals("count of empty " + streamFqcn, 0L, count);
- }
-
- /**
- * Tries to load the given class. If the class is not found, the complete test is skipped.
- */
- private Class<?> getClassOrSkipTest(String className) {
- try {
- return Class.forName(className);
- } catch (ClassNotFoundException e) {
- Assume.assumeNoException("JVM does not support " + className, e);
- return null;
- }
+ public void should_return_empty_Streams() throws Exception {
+ assertThat((Stream) values.returnValueFor(Stream.class)).isEmpty();
+ assertThat(((DoubleStream) values.returnValueFor(DoubleStream.class)).count()).isEqualTo(0);
+ assertThat(((IntStream) values.returnValueFor(IntStream.class)).count()).isEqualTo(0);
+ assertThat(((LongStream) values.returnValueFor(LongStream.class)).count()).isEqualTo(0);
}
}
diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValuesTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValuesTest.java
index 2725c37df1..6105bde2bd 100644
--- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValuesTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValuesTest.java
@@ -8,21 +8,13 @@
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.assertEquals;
-import static junit.framework.TestCase.assertTrue;
public class ReturnsMoreEmptyValuesTest extends TestBase {
private ReturnsMoreEmptyValues rv = new ReturnsMoreEmptyValues();
-
- @Test
- public void shouldReturnEmptyArray() {
- String[] ret = (String[]) rv.returnValueFor((new String[0]).getClass());
- assertTrue(ret.getClass().isArray());
- assertTrue(ret.length == 0);
- }
@Test
- public void shouldReturnEmptyString() {
+ public void should_return_empty_string() {
assertEquals("", rv.returnValueFor(String.class));
}
-}
\ No newline at end of file
+}
| test | train | 2017-01-15T10:12:31 | "2017-01-11T15:48:36Z" | bric3 | train |
mockito/mockito/814_905 | mockito/mockito | mockito/mockito/814 | mockito/mockito/905 | [
"keyword_pr_to_issue"
] | de0a7725667bbc025f1bd78310fbbf8cde4d8bb6 | d8f529ee4b254c57edc1a97d0505ac57da7c7225 | [
"I don't see what you mean I have no problem for that : \r\n\r\n* https://static.javadoc.io/org.mockito/mockito-core/2.3.0/org/mockito/Mockito.html#40\r\n* https://static.javadoc.io/org.mockito/mockito-core/2.3.0/org/mockito/Mockito.html#strict_mockito",
"At first it seems to be working, but the actual issue is that the first link of @bric3 does work, but the second does not. The problem is that the headers have the second link, so they must be updated to use numbers instead."
] | [] | "2017-01-23T14:39:51Z" | [
"docs"
] | Javadoc links in main Mockito doc are not linkable | The links to line items in the main [Mockito documentation](https://static.javadoc.io/org.mockito/mockito-core/2.3.0/org/mockito/Mockito.html) are not linkable, e.g. I cannot create a link to item no. 40 in the list. | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 27f0768054..895607bd25 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -82,7 +82,7 @@
* <a href="#40">40. (**new**) Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)</a><br/>
* </b>
*
- * <h3 id="0">0. <a class="meaningful_link" href="#mockito2">Migrating to Mockito 2</a></h3>
+ * <h3 id="0">0. <a class="meaningful_link" href="#mockito2" name="mockito2">Migrating to Mockito 2</a></h3>
*
* In order to continue improving Mockito and further improve the unit testing experience, we want you to upgrade to 2.1.0!
* Mockito follows <a href="http://semver.org/">semantic versioning</a> and contains breaking changes only on major version upgrades.
@@ -92,7 +92,7 @@
* see '<a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2">What's new in Mockito 2</a>' wiki page.
* We hope that you enjoy Mockito 2!
*
- * <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito-android">Mockito Android support</a></h3>
+ * <h3 id="0.1">0.1. <a class="meaningful_link" href="#mockito" name="mockito-android">Mockito Android support</a></h3>
*
* With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency
* to your project. This artifact is published to the same mockito organization:
@@ -106,7 +106,7 @@
* with Android. If you encounter issues with mocking on Android, please open an issue <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>.
* Do provide the version of Android you are working on and dependencies of your project.
*
- * <h3 id="1">1. <a class="meaningful_link" href="#verification">Let's verify some behaviour!</a></h3>
+ * <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3>
*
* The following examples mock a List, because most people are familiar with the interface (such as the
* <code>add()</code>, <code>get()</code>, <code>clear()</code> methods). <br>
@@ -135,7 +135,7 @@
*
*
*
- * <h3 id="2">2. <a class="meaningful_link" href="#stubbing">How about some stubbing?</a></h3>
+ * <h3 id="2">2. <a class="meaningful_link" href="#stubbing" name="stubbing">How about some stubbing?</a></h3>
*
* <pre class="code"><code class="java">
* //You can mock concrete classes, not just interfaces
@@ -181,7 +181,7 @@
*
*
*
- * <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers">Argument matchers</a></h3>
+ * <h3 id="3">3. <a class="meaningful_link" href="#argument_matchers" name="argument_matchers">Argument matchers</a></h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* Sometimes, when extra flexibility is required then you might use argument matchers:
@@ -242,8 +242,8 @@
*
*
*
- * <h3 id="4">4. <a class="meaningful_link" href="#exact_verification">Verifying exact number of invocations</a> /
- * <a class="meaningful_link" href="#at_least_verification">at least x</a> / never</h3>
+ * <h3 id="4">4. <a class="meaningful_link" href="#exact_verification" name="exact_verification">Verifying exact number of invocations</a> /
+ * <a class="meaningful_link" href="#at_least_verification" name="at_least_verification">at least x</a> / never</h3>
*
* <pre class="code"><code class="java">
* //using mock
@@ -281,7 +281,7 @@
*
*
*
- * <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
+ * <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions" name="stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
*
* <pre class="code"><code class="java">
* doThrow(new RuntimeException()).when(mockedList).clear();
@@ -293,7 +293,7 @@
* Read more about <code>doThrow()</code>|<code>doAnswer()</code> family of methods in <a href="#12">section 12</a>.
* <p>
*
- * <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification">Verification in order</a></h3>
+ * <h3 id="6">6. <a class="meaningful_link" href="#in_order_verification" name="in_order_verification">Verification in order</a></h3>
*
* <pre class="code"><code class="java">
* // A. Single mock whose methods must be invoked in a particular order
@@ -338,7 +338,7 @@
*
*
*
- * <h3 id="7">7. <a class="meaningful_link" href="#never_verification">Making sure interaction(s) never happened on mock</a></h3>
+ * <h3 id="7">7. <a class="meaningful_link" href="#never_verification" name="never_verification">Making sure interaction(s) never happened on mock</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks - only mockOne is interacted
@@ -358,7 +358,7 @@
*
*
*
- * <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations">Finding redundant invocations</a></h3>
+ * <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations" name="finding_redundant_invocations">Finding redundant invocations</a></h3>
*
* <pre class="code"><code class="java">
* //using mocks
@@ -386,7 +386,7 @@
*
*
*
- * <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3>
+ * <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation" name="mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3>
*
* <ul>
* <li>Minimizes repetitive mock creation code.</li>
@@ -419,7 +419,7 @@
*
*
*
- * <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3>
+ * <h3 id="10">10. <a class="meaningful_link" href="#stubbing_consecutive_calls" name="stubbing_consecutive_calls">Stubbing consecutive calls</a> (iterator-style stubbing)</h3>
*
* Sometimes we need to stub with different return value/exception for the same
* method call. Typical use case could be mocking iterators.
@@ -465,7 +465,7 @@
*
*
*
- * <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs">Stubbing with callbacks</a></h3>
+ * <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs" name="answer_stubs">Stubbing with callbacks</a></h3>
*
* Allows stubbing with generic {@link Answer} interface.
* <p>
@@ -490,7 +490,7 @@
*
*
*
- * <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>|
+ * <h3 id="12">12. <a class="meaningful_link" href="#do_family_methods_stubs" name="do_family_methods_stubs"><code>doReturn()</code>|<code>doThrow()</code>|
* <code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a></h3>
*
* Stubbing void methods requires a different approach from {@link Mockito#when(Object)} because the compiler does not
@@ -533,7 +533,7 @@
*
*
*
- * <h3 id="13">13. <a class="meaningful_link" href="#spy">Spying on real objects</a></h3>
+ * <h3 id="13">13. <a class="meaningful_link" href="#spy" name="spy">Spying on real objects</a></h3>
*
* You can create spies of real objects. When you use the spy then the <b>real</b> methods are called
* (unless a method was stubbed).
@@ -605,7 +605,7 @@
*
*
*
- * <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3>
+ * <h3 id="14">14. Changing <a class="meaningful_link" href="#defaultreturn" name="defaultreturn">default return values of unstubbed invocations</a> (Since 1.7)</h3>
*
* You can create a mock with specified strategy for its return values.
* It's quite an advanced feature and typically you don't need it to write decent tests.
@@ -624,7 +624,7 @@
*
*
*
- * <h3 id="15">15. <a class="meaningful_link" href="#captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3>
+ * <h3 id="15">15. <a class="meaningful_link" href="#captors" name="captors">Capturing arguments</a> for further assertions (Since 1.8.0)</h3>
*
* Mockito verifies argument values in natural java style: by using an <code>equals()</code> method.
* This is also the recommended way of matching arguments because it makes tests clean & simple.
@@ -652,7 +652,7 @@
*
*
*
- * <h3 id="16">16. <a class="meaningful_link" href="#partial_mocks">Real partial mocks</a> (Since 1.8.0)</h3>
+ * <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 - more reading:
@@ -685,7 +685,7 @@
*
*
*
- * <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3>
+ * <h3 id="17">17. <a class="meaningful_link" href="#resetting_mocks" name="resetting_mocks">Resetting mocks</a> (Since 1.8.0)</h3>
*
* Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
* Normally, you don't need to reset your mocks, just create new mocks for each test method.
@@ -712,7 +712,7 @@
*
*
*
- * <h3 id="18">18. <a class="meaningful_link" href="#framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
+ * <h3 id="18">18. <a class="meaningful_link" href="#framework_validation" name="framework_validation">Troubleshooting & validating framework usage</a> (Since 1.8.0)</h3>
*
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ:
* <a href="https://github.com/mockito/mockito/wiki/FAQ">https://github.com/mockito/mockito/wiki/FAQ</a>
@@ -726,7 +726,7 @@
*
*
*
- * <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3>
+ * <h3 id="19">19. <a class="meaningful_link" href="#bdd_mockito" name="bdd_mockito">Aliases for behavior driven development</a> (Since 1.8.0)</h3>
*
* Behavior Driven Development style of writing tests uses <b>//given //when //then</b> comments as fundamental parts of your test methods.
* This is exactly how we write our tests and we warmly encourage you to do so!
@@ -760,7 +760,7 @@
*
*
*
- * <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3>
+ * <h3 id="20">20. <a class="meaningful_link" href="#serializable_mocks" name="serializable_mocks">Serializable mocks</a> (Since 1.8.1)</h3>
*
* Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
* <p>
@@ -791,9 +791,9 @@
*
*
*
- * <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation"><code>@Captor</code></a>,
- * <a class="meaningful_link" href="#spy_annotation"><code>@Spy</code></a>,
- * <a class="meaningful_link" href="#injectmocks_annotation"><code>@InjectMocks</code></a> (Since 1.8.3)</h3>
+ * <h3 id="21">21. New annotations: <a class="meaningful_link" href="#captor_annotation" name="captor_annotation"><code>@Captor</code></a>,
+ * <a class="meaningful_link" href="#spy_annotation" name="spy_annotation"><code>@Spy</code></a>,
+ * <a class="meaningful_link" href="#injectmocks_annotation" name="injectmocks_annotation"><code>@InjectMocks</code></a> (Since 1.8.3)</h3>
*
* <p>
* Release 1.8.3 brings new annotations that may be helpful on occasion:
@@ -819,7 +819,7 @@
*
*
*
- * <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3>
+ * <h3 id="22">22. <a class="meaningful_link" href="#verification_timeout" name="verification_timeout">Verification with timeout</a> (Since 1.8.5)</h3>
* <p>
* Allows verifying with timeout. It causes a verify to wait for a specified period of time for a desired
* interaction rather than fails immediately if had not already happened. May be useful for testing in concurrent
@@ -851,8 +851,8 @@
*
*
*
- * <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation">Automatic instantiation of <code>@Spies</code>,
- * <code>@InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3>
+ * <h3 id="23">23. <a class="meaningful_link" href="#automatic_instantiation" name="automatic_instantiation">Automatic instantiation of <code>@Spies</code>,
+ * <code>@InjectMocks</code></a> and <a class="meaningful_link" href="#constructor_injection" name="constructor_injection">constructor injection goodness</a> (Since 1.9.0)</h3>
*
* <p>
* Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields
@@ -875,7 +875,7 @@
*
*
*
- * <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3>
+ * <h3 id="24">24. <a class="meaningful_link" href="#one_liner_stub" name="one_liner_stub">One-liner stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow you to create mocks when stubbing.
* Basically, it allows to create a stub in one line of code.
@@ -891,7 +891,7 @@
*
*
*
- * <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3>
+ * <h3 id="25">25. <a class="meaningful_link" href="#ignore_stubs_verification" name="ignore_stubs_verification">Verification ignoring stubs</a> (Since 1.9.0)</h3>
* <p>
* Mockito will now allow to ignore stubbing for the sake of verification.
* Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
@@ -920,7 +920,7 @@
*
*
*
- * <h3 id="26">26. <a class="meaningful_link" href="#mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
+ * <h3 id="26">26. <a class="meaningful_link" href="#mocking_details" name="mocking_details">Mocking details</a> (Improved in 2.2.x)</h3>
* <p>
*
* Mockito offers API to inspect the details of a mock object.
@@ -947,7 +947,7 @@
*
* For more information see javadoc for {@link MockingDetails}.
*
- * <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3>
+ * <h3 id="27">27. <a class="meaningful_link" href="#delegating_call_to_real_instance" name="delegating_call_to_real_instance">Delegate calls to real instance</a> (Since 1.9.5)</h3>
*
* <p>Useful for spies or partial mocks of objects <strong>that are difficult to mock or spy</strong> using the usual spy API.
* Since Mockito 1.10.11, the delegate may or may not be of the same type as the mock.
@@ -983,7 +983,7 @@
*
*
*
- * <h3 id="28">28. <a class="meaningful_link" href="#mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3>
+ * <h3 id="28">28. <a class="meaningful_link" href="#mock_maker_plugin" name="mock_maker_plugin"><code>MockMaker</code> API</a> (Since 1.9.5)</h3>
* <p>Driven by requirements and patches from Google Android guys Mockito now offers an extension point
* that allows replacing the proxy generation engine. By default, Mockito uses <a href="https://github.com/raphw/byte-buddy">Byte Buddy</a>
* to create dynamic proxies.
@@ -995,7 +995,7 @@
*
*
*
- * <h3 id="29">29. <a class="meaningful_link" href="#BDD_behavior_verification">BDD style verification</a> (Since 1.10.0)</h3>
+ * <h3 id="29">29. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">BDD style verification</a> (Since 1.10.0)</h3>
*
* Enables Behavior Driven Development (BDD) style verification by starting verification with the BDD <b>then</b> keyword.
*
@@ -1013,7 +1013,7 @@
*
*
*
- * <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12)</a></h3>
+ * <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12)</a></h3>
*
* It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}).
* <p>
@@ -1040,7 +1040,7 @@
*
*
*
- * <h3 id="31">31. <a class="meaningful_link" href="#serilization_across_classloader">Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3>
+ * <h3 id="31">31. <a class="meaningful_link" href="#serilization_across_classloader" name="serilization_across_classloader">Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3>
*
* Mockito introduces serialization across classloader.
*
@@ -1060,7 +1060,7 @@
*
*
*
- * <h3 id="32">32. <a class="meaningful_link" href="#better_generic_support_with_deep_stubs">Better generic support with deep stubs (Since 1.10.0)</a></h3>
+ * <h3 id="32">32. <a class="meaningful_link" href="#better_generic_support_with_deep_stubs" name="better_generic_support_with_deep_stubs">Better generic support with deep stubs (Since 1.10.0)</a></h3>
*
* Deep stubbing has been improved to find generic information if available in the class.
* That means that classes like this can be used without having to mock the behavior.
@@ -1081,7 +1081,7 @@
*
*
*
- * <h3 id="33">33. <a class="meaningful_link" href="#mockito_junit_rule">Mockito JUnit rule (Since 1.10.17)</a></h3>
+ * <h3 id="33">33. <a class="meaningful_link" href="#mockito_junit_rule" name="mockito_junit_rule">Mockito JUnit rule (Since 1.10.17)</a></h3>
*
* Mockito now offers a JUnit rule. Until now in JUnit there were two ways to initialize fields annotated by Mockito annotations
* such as <code>@{@link Mock}</code>, <code>@{@link Spy}</code>, <code>@{@link InjectMocks}</code>, etc.
@@ -1106,14 +1106,14 @@
*
*
*
- * <h3 id="34">34. <a class="meaningful_link" href="#plugin_switch">Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a></h3>
+ * <h3 id="34">34. <a class="meaningful_link" href="#plugin_switch" name="plugin_switch">Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a></h3>
*
* An incubating feature made it's way in mockito that will allow to toggle a mockito-plugin.
*
* More information here {@link org.mockito.plugins.PluginSwitch}.
*
*
- * <h3 id="35">35. <a class="meaningful_link" href="#BDD_behavior_verification">Custom verification failure message</a> (Since 2.1.0)</h3>
+ * <h3 id="35">35. <a class="meaningful_link" href="#BDD_behavior_verification" name="BDD_behavior_verification">Custom verification failure message</a> (Since 2.1.0)</h3>
* <p>
* Allows specifying a custom message to be printed if verification fails.
* <p>
@@ -1128,7 +1128,7 @@
* verify(mock, times(2).description("someMethod should be called twice")).someMethod();
* </code></pre>
*
- * <h3 id="36">36. <a class="meaningful_link" href="#Java_8_Lambda_Matching">Java 8 Lambda Matcher Support</a> (Since 2.1.0)</h3>
+ * <h3 id="36">36. <a class="meaningful_link" href="#Java_8_Lambda_Matching" name="Java_8_Lambda_Matching">Java 8 Lambda Matcher Support</a> (Since 2.1.0)</h3>
* <p>
* You can use Java 8 lambda expressions with {@link ArgumentMatcher} to reduce the dependency on {@link ArgumentCaptor}.
* If you need to verify that the input to a function call on a mock was correct, then you would normally
@@ -1161,7 +1161,7 @@
* when(mock.someMethod(argThat(list -> list.size()<3))).willReturn(null);
* </code></pre>
*
- * <h3 id="37">37. <a class="meaningful_link" href="#Java_8_Custom_Answers">Java 8 Custom Answer Support</a> (Since 2.1.0)</h3>
+ * <h3 id="37">37. <a class="meaningful_link" href="#Java_8_Custom_Answers" name="Java_8_Custom_Answers">Java 8 Custom Answer Support</a> (Since 2.1.0)</h3>
* <p>
* As the {@link Answer} interface has just one method it is already possible to implement it in Java 8 using
* a lambda expression for very simple situations. The more you need to use the parameters of the method call,
@@ -1240,7 +1240,7 @@
* }})).when(mock).execute(anyString(), anyString());
* </code></pre>
*
- * <h3 id="38">38. <a class="meaningful_link" href="#Meta_Data_And_Generics">Meta data and generic type retention</a> (Since 2.1.0)</h3>
+ * <h3 id="38">38. <a class="meaningful_link" href="#Meta_Data_And_Generics" name="Meta_Data_And_Generics">Meta data and generic type retention</a> (Since 2.1.0)</h3>
*
* <p>
* Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve
@@ -1262,7 +1262,7 @@
* When using Java 8, Mockito now also preserves type annotations. This is default behavior and might not hold <a href="#28">if an
* alternative {@link org.mockito.plugins.MockMaker} is used</a>.
*
- * <h3 id="39">39. <a class="meaningful_link" href="#Mocking_Final">Mocking final types, enums and final methods</a> (Since 2.1.0)</h3>
+ * <h3 id="39">39. <a class="meaningful_link" href="#Mocking_Final" name="Mocking_Final">Mocking final types, enums and final methods</a> (Since 2.1.0)</h3>
*
* Mockito now offers an {@link Incubating}, optional support for mocking final classes and methods.
* This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving testing experience.
@@ -1311,7 +1311,7 @@
* If you are interested in more details of this feature please read the javadoc of
* <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>
*
- * <h3 id="40">40. <a class="meaningful_link" href="#strict_mockito">
+ * <h3 id="40">40. <a class="meaningful_link" href="#strict_mockito" name="strict_mockito">
* (**new**) Improved productivity and cleaner tests with "stricter" Mockito</a> (Since 2.+)</h3>
*
* To quickly find out how "stricter" Mockito can make you more productive and get your tests cleaner, see:
| null | val | train | 2017-01-23T14:52:08 | "2016-12-13T07:14:18Z" | mockitoguy | train |
mockito/mockito/426_907 | mockito/mockito | mockito/mockito/426 | mockito/mockito/907 | [
"keyword_pr_to_issue"
] | f967b930042c624fa75c059aa6a5b1c5d013f6af | 8f9d6ff2fd674bce3ee3aaba2a282d816eed2e60 | [
"@raphw thanks for merging the PR that fast! Would you mind reopening this ticket? There are more classes that can be refactored that way, I would like to extend the list.\n",
"Big :+1: for me btw, but please keep the pull requests managable and as small as possible. Preferably refactoring 1 method at a time. That way it is a lot easier to review.\n",
"I agree, there is nothing wrong with multiple PRs, the quick merge is a reaction to an easy overview (and being stuck at an Ukrainian airport without access to the Eurocup).\n",
"There are still two unit tests failing, could you have a look @ChristianSchwarz - I just had a quick look and there are two unit tests failing which seems related to the way you refactored the previous stubbing of the `Reporter`.\n\nI should have checked more thoroughly before merging, hopefully you can fix the problem soon. Alternatively, I will just rollback the one commit (the first one is good) and we can reapply the patch once you fixed the two unit tests. Thank you, really, this was great clean-up.\n",
"I fixed the one test error. I push it tonight.\n\nPS: I also fixed a bug in the stack trace cleaner. Not a biggy but please do not `@Ignore` tests. Especially in big commits, it is easy to miss that single annotation.\n",
"@raphw Which test(s) is/are failing? I will fix it asap! Too bad that some test fail on a regulare base, is it possible to ignore them in the ide only?\n",
"You can see the build output here: https://travis-ci.org/mockito/mockito#L254-L269\n\nI advise you to run the tests with `./gradlew build`. This should work.\n",
"@TimvdLippe know what you mean! The next PR's include only one refactored class at a time.\n",
"I have it all fixed on local but I did not have access to wifi without 22 blocked. Will commit soon.\n",
"@raphw can you please reopen this issue \n",
"Sorry, GitHub automatically closes issues that reference a PR.\n",
"@ChristianSchwarz If a commit contains a comment like \"Fixes #426\" the mentioned issue is automatically closed by github.\n",
"@PascalSchumacher Good to know! I will leave it out for the upcoming PR's. Thanks!\n",
"Now that we are pulling in static methods, I would like to propose a new (linter) rule. To make it easier to read a file, I would like that all methods invoked in the current class are referenced with `this.` (and `super.` for that matter). Therefore if we see `this.verify`, we know it is in the current class and the same object, whereas `verify` references a static method in this class, or an imported static method. Do you agree @mockito/developers ?\n",
"> I would like that all methods invoked in the current class are referenced with this. (and super. for that matter).\n\nTo me it feels like unnecessary/duplicate code cause `this` is implicit. Adding `this.` before every instance call would create a lot more text and would IMHO reduce readability. E.g.:\n\n`this.doSometing(this.withPrivateMethod())` vs. `doSomething(withPrivateMethod())`\n\n> Therefore if we see this.verify, we know it is in the current class and the same object, whereas verify references a static method in this class, or an imported static method.\n\nAn other option avoid ambiguity is to qualify static methods via its class name. This way you can also distinguish which verify(..) is called ( `MockitoCore.verify(..)` / `Mocktio.verify(..)`) , which is not an easy task when a static import is used.\n",
"I'm not coding too much in Mockito ATM (hopefully now after SpringOne conference I'll have more time) but I fully agree with @ChristianSchwarz . IMO the best solution is to: \n- omit `this` before method calls. \n- if necessary provide the class for static method call\n",
"Respectful -1\n\nI like when the class formally declares collaborators instead of calling out to static methods. This makes it easy to reason about the code. I don't need to read every line of code in the class to find out external couplings realized via static methods. I can see the couplings via fields, I can easily query how the field variable is used, etc. Another use case is when we discover missing/incorrect unit test coverage (or we do some larger refactorings) and we cannot easily write tests because code is too procedural.\n\nThe benefits for converting to static utilities have minimal significance to me. Yet, there is a downside I care about (e.g. maintainability of procedural code, static methods that consume static methods, that consume static methods...).\n\nHence, I down vote this sort of changes. Going down this path, all stateless classes in Mockito would become static utilities :)\n\nYou can get +1's from other maintainers and have your changes merged - I'm not here to block your changes but to give honest feedback. I see merit in arguments for static utilities. They do not outweigh the cost in my opinion.\n",
"I'm mitigated about this as well. I understand well that mockito creates garbage, but they are short lived and **most probably** won't go in the old generation especially in the test phase. Yet the faster the tests are the more developers will run them, it **may** have impacts on big projects. Also design wise I don't like much static methods too.\n\nHowever I don't totally agree with the above points : \n\n> I don't need to read every line of code in the class to find out external couplings realized via static methods. I can see the couplings via fields, I can easily query how the field variable is used, etc.\n\nCoupling appears also in the import section ; static methods are visible there. And modern IDE usually highlight this. IntelliJ even have a warning if import section is too big, just as there's warning if there's too many fields. This point should not be the reason to avoid static methods.\n\n> maintainability of procedural code, static methods that consume static methods, that consume static methods...\n\nHaving instance methods does not protect again procedural code.\n\n---\n\nI believe there's middle ground there : \n- Mockito project contains a lot of small utility stateless objects that are supporting mockito features, these are usually collections tools, reflection tools, those could are good candidate for static methods. Objects like `FieldSetter`, `FieldCopier`, `LenientCopyTool` could be nice candidate for static methods\n- Mockito features could be backed by object instances. Objects like `MockitoCore`, `MockCreationValidator`, `ArgumentMatchingTool` are candidate to stay objects.\n",
"Exactly the middle ground described by Brice is my motivation for merging most of the PRs. This is also the reason I have not yet merged the MockitoCore PR for this exact reason.\n\nIf an object is not a attribute or parameter, but an internal creation and immediately dismissed, I value a pure function more.\n",
"Thought: when we switch to Java 8, we can use interfaces with default\nmethods. The switch from static utility to interface is very easy now (just\na couple of text replaces, no method reference modifications).\n\nOn Fri, 12 Aug 2016, 17:23 Brice Dutheil, notifications@github.com wrote:\n\n> I'm mitigated about this as well. I understand well that mockito creates\n> garbage, but they are short lived and _most probably_ won't go in the old\n> generation especially in the test phase. Yet the faster the tests are the\n> more developers will run them, it _may_ have impacts on big projects.\n> Also design wise I don't like much static methods too.\n> \n> However I don't totally agree with the above points :\n> \n> I don't need to read every line of code in the class to find out external\n> couplings realized via static methods. I can see the couplings via fields,\n> I can easily query how the field variable is used, etc.\n> \n> Coupling appears also in the import section ; static methods are visible\n> there. And modern IDE usually highlight this. IntelliJ even have a warning\n> if import section is too big, just as there's warning if there's too many\n> fields. This point should not be the reason to avoid static methods.\n> \n> maintainability of procedural code, static methods that consume static\n> methods, that consume static methods...\n> \n> ## Having instance methods does not protect again procedural code.\n> \n> I believe there's middle ground there :\n> \n> -\n> \n> Mockito project contains a lot of small utility stateless objects that\n> are supporting mockito features, these are usually collections tools,\n> reflection tools, those could are good candidate for static methods.\n> Objects like FieldSetter, FieldCopier, LenientCopyTool could be nice\n> candidate for static methods\n> -\n> \n> Mockito features could be backed by object instances. Objects like\n> MockitoCore, MockCreationValidator, ArgumentMatchingTool are candidate\n> to stay objects.\n> \n> —\n> You are receiving this because you modified the open/close state.\n> Reply to this email directly, view it on GitHub\n> https://github.com/mockito/mockito/issues/426#issuecomment-239476519,\n> or mute the thread\n> https://github.com/notifications/unsubscribe-auth/AFrDb6QVlVesWgPAhurimgSUPQTRcTZSks5qfJALgaJpZM4IzjKm\n> .\n",
"This feels like a misuse of the default methods.\n",
"I think you mean static-methods in interfaces here? Default-methods require an instance to be called on.\nAnyway I don't think that it is a good idea. It would a result in an interface that is not intended to be implemented or extended and only serves as container for utility methods. IMHO a class with private constructor is the best construct to do this.\n",
"> > Thought: when we switch to Java 8, we can use interfaces with default\n> > methods.\n> \n> Default-methods require an instance to be called on.\n\nI was thinking exactly that, default methods in the interface plus instance (either as a separate file or as a singleton declared within the interface).\n",
"@ChristianSchwarz What do you think to continue the work here with the middle ground described [here](https://github.com/mockito/mockito/issues/426#issuecomment-239476519) ?\n",
"I am attempting to refactor the MatcherBinder class to a static utility class and am having trouble refactoring the following from MockHandlerImplTest.java: `\r\nhandler.matchersBinder = new MatchersBinder() {\r\n public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {\r\n throw new InvalidUseOfMatchersException();\r\n }\r\n}; `\r\nHow can I maintain the abstract class definition when I am not able to create an object of MatcherBinder?\r\n\r\nAny help is appreciated! ",
"Let's close this ticket. Refactorings can be done as needed as we work with the code."
] | [] | "2017-01-26T12:17:39Z" | [] | Refactor instance based utility classes to static utility classes | The internal implementation of Mockito contains numerous helper classed that serve as a container for useful methods. By its nature these classes don't have a state. Currently some them are instance based in other word you need to create the utility class to call a helper method. This not only pollutes the heap but also the code cause instance methods can't be imported statically.
Here is an example:
```java
Helper helper = new Helper();
if (helper.isInputValid(input)){
[...]
}
```
vs. static import of Helper.isInputValid
```java
if (isInputValid(input)){
[...]
}
```
The aim of this ticket is to identify canidates that can be refactored to static utility classes. If you like to refactoring and mockito feel free to send a PR and reference this issue.
Refactoring canidates:
- [ ] `AccessibilityChanger`
- [ ] `BeanPropertySetter`
- [ ] `ConditionalStackTraceFilter`
- [ ] `FieldCopier`
- [ ] `FieldReader`
- [ ] `GenericMaster` should be integrate into `GenericTypeResolver`
- [ ] `JUnitFailureHacker` can be removed when the deprecated `VerboseMockitoJUnitRunner` is removed
- [ ] `LenientCopyTool`
- [ ] `MatcherBinder`
- [ ] `MockitoCore` should better be a singleton
- [x] `MockCreationValidator`
- [ ] `RemoveFirstLine`
- [x] #591 `ArgumentMatchingTool`
- [x] #515 `AllInvocationsFinder`
- [x] #502 `ArgumentsComparator`
- [x] #540 `ArrayUtils`
- [x] #490 `AtLeastXNumberOfInvocationsChecker`
- [x] #490 `AtLeastXNumberOfInvocationsInOrderChecker`
- [ ] #912 `Constructors`
- [x] #427 `FieldSetter`
- [x] #908 `FriendlyExceptionMaker`
- [x] #431 `HandyReturnValues`
- [x] #432 `InvocationMarker`
- [x] #462 `InvocationsFinder`
- [x] #908 `JUnitDetecter`
- [x] #490 `MissingInvocationChecker`
- [x] #490 `MissingInvocationInOrderChecker`
- [x] #514 `MockUtil`
- [x] #503 `NonGreedyNumberOfInvocationsInOrderChecker`
- [x] #907 `NumberOfInvocationsInOrderChecker`
- [x] #907 `NumberOfInvocationsChecker`
- [x] #547 `ObjectMethodsGuru`
- [x] #427 `Reporter`
- [x] #535 `SuperTypesLastSorter`
- [x] #501 `TestMethodFinder`
- [x] #515 `VerifiableInvocationsFinder`
| [
"src/main/java/org/mockito/internal/verification/Calls.java",
"src/main/java/org/mockito/internal/verification/Times.java",
"src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java"
] | [
"src/main/java/org/mockito/internal/verification/Calls.java",
"src/main/java/org/mockito/internal/verification/Times.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/verification/Calls.java b/src/main/java/org/mockito/internal/verification/Calls.java
index e7e7eeef0d..3d9bc84fa7 100644
--- a/src/main/java/org/mockito/internal/verification/Calls.java
+++ b/src/main/java/org/mockito/internal/verification/Calls.java
@@ -5,20 +5,18 @@
package org.mockito.internal.verification;
+import static org.mockito.internal.verification.checkers.MissingInvocationChecker.checkMissingInvocation;
+import static org.mockito.internal.verification.checkers.NumberOfInvocationsChecker.checkNumberOfInvocationsNonGreedy;
+
+import java.util.List;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.internal.invocation.InvocationMatcher;
-import org.mockito.invocation.MatchableInvocation;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.internal.verification.api.VerificationDataInOrder;
import org.mockito.internal.verification.api.VerificationInOrderMode;
import org.mockito.invocation.Invocation;
+import org.mockito.invocation.MatchableInvocation;
import org.mockito.verification.VerificationMode;
-import static org.mockito.internal.verification.checkers.NonGreedyNumberOfInvocationsInOrderChecker.check;
-import static org.mockito.internal.verification.checkers.MissingInvocationChecker.checkMissingInvocation;
-
-import java.util.List;
-
public class Calls implements VerificationMode, VerificationInOrderMode {
final int wantedCount;
@@ -30,16 +28,18 @@ public Calls(int wantedNumberOfInvocations) {
this.wantedCount = wantedNumberOfInvocations;
}
+ @Override
public void verify(VerificationData data) {
throw new MockitoException( "calls is only intended to work with InOrder" );
}
+ @Override
public void verifyInOrder(VerificationDataInOrder data) {
List<Invocation> allInvocations = data.getAllInvocations();
MatchableInvocation wanted = data.getWanted();
checkMissingInvocation(allInvocations, wanted, data.getOrderingContext());
- check( allInvocations, wanted, wantedCount, data.getOrderingContext());
+ checkNumberOfInvocationsNonGreedy(allInvocations, wanted, wantedCount, data.getOrderingContext());
}
@Override
diff --git a/src/main/java/org/mockito/internal/verification/Times.java b/src/main/java/org/mockito/internal/verification/Times.java
index 5dbf0f444c..d2895c5446 100644
--- a/src/main/java/org/mockito/internal/verification/Times.java
+++ b/src/main/java/org/mockito/internal/verification/Times.java
@@ -6,16 +6,14 @@
package org.mockito.internal.verification;
import static org.mockito.internal.verification.checkers.MissingInvocationChecker.checkMissingInvocation;
+import static org.mockito.internal.verification.checkers.NumberOfInvocationsChecker.checkNumberOfInvocations;
import java.util.List;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.MatchableInvocation;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.internal.verification.api.VerificationDataInOrder;
import org.mockito.internal.verification.api.VerificationInOrderMode;
-import org.mockito.internal.verification.checkers.NumberOfInvocationsChecker;
-import org.mockito.internal.verification.checkers.NumberOfInvocationsInOrderChecker;
import org.mockito.invocation.Invocation;
import org.mockito.verification.VerificationMode;
@@ -30,6 +28,7 @@ public Times(int wantedNumberOfInvocations) {
this.wantedCount = wantedNumberOfInvocations;
}
+ @Override
public void verify(VerificationData data) {
List<Invocation> invocations = data.getAllInvocations();
MatchableInvocation wanted = data.getTarget();
@@ -37,10 +36,10 @@ public void verify(VerificationData data) {
if (wantedCount > 0) {
checkMissingInvocation(data.getAllInvocations(), data.getTarget());
}
- NumberOfInvocationsChecker numberOfInvocations = new NumberOfInvocationsChecker();
- numberOfInvocations.check(invocations, wanted, wantedCount);
+ checkNumberOfInvocations(invocations, wanted, wantedCount);
}
+ @Override
public void verifyInOrder(VerificationDataInOrder data) {
List<Invocation> allInvocations = data.getAllInvocations();
MatchableInvocation wanted = data.getWanted();
@@ -48,8 +47,7 @@ public void verifyInOrder(VerificationDataInOrder data) {
if (wantedCount > 0) {
checkMissingInvocation(allInvocations, wanted, data.getOrderingContext());
}
- NumberOfInvocationsInOrderChecker numberOfCalls = new NumberOfInvocationsInOrderChecker();
- numberOfCalls.check(allInvocations, wanted, wantedCount, data.getOrderingContext());
+ checkNumberOfInvocations(allInvocations, wanted, wantedCount, data.getOrderingContext());
}
@Override
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
deleted file mode 100644
index 3bccd0a396..0000000000
--- a/src/main/java/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.internal.verification.checkers;
-
-import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocationsInOrder;
-import static org.mockito.internal.invocation.InvocationMarker.markVerified;
-import static org.mockito.internal.invocation.InvocationsFinder.findFirstMatchingUnverifiedInvocation;
-
-import java.util.List;
-
-import org.mockito.internal.invocation.InvocationMatcher;
-import org.mockito.internal.reporting.Discrepancy;
-import org.mockito.internal.verification.api.InOrderContext;
-import org.mockito.invocation.Invocation;
-import org.mockito.invocation.Location;
-import org.mockito.invocation.MatchableInvocation;
-
-public class NonGreedyNumberOfInvocationsInOrderChecker {
-
- private NonGreedyNumberOfInvocationsInOrderChecker() {}
-
- public static void check(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) {
- int actualCount = 0;
- Location lastLocation = null;
- while( actualCount < wantedCount ){
- Invocation next = findFirstMatchingUnverifiedInvocation(invocations, wanted, context );
- if( next == null ){
- throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastLocation );
- }
- markVerified( next, wanted );
- context.markVerified( next );
- lastLocation = next.getLocation();
- actualCount++;
- }
- }
-}
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
index 938f8ffd32..531f4779c4 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
@@ -7,20 +7,29 @@
import java.util.List;
import org.mockito.internal.reporting.Discrepancy;
+import org.mockito.internal.verification.api.InOrderContext;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
import org.mockito.invocation.MatchableInvocation;
import static org.mockito.internal.exceptions.Reporter.neverWantedButInvoked;
import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocations;
+import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocationsInOrder;
import static org.mockito.internal.exceptions.Reporter.tooManyActualInvocations;
+import static org.mockito.internal.exceptions.Reporter.tooManyActualInvocationsInOrder;
import static org.mockito.internal.invocation.InvocationMarker.markVerified;
+import static org.mockito.internal.invocation.InvocationMarker.markVerifiedInOrder;
+import static org.mockito.internal.invocation.InvocationsFinder.findFirstMatchingUnverifiedInvocation;
import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
+import static org.mockito.internal.invocation.InvocationsFinder.findMatchingChunk;
import static org.mockito.internal.invocation.InvocationsFinder.getLastLocation;
public class NumberOfInvocationsChecker {
+
+ private NumberOfInvocationsChecker() {
+ }
- public void check(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount) {
+ public static void checkNumberOfInvocations(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount) {
List<Invocation> actualInvocations = findInvocations(invocations, wanted);
int actualCount = actualInvocations.size();
@@ -39,4 +48,36 @@ public void check(List<Invocation> invocations, MatchableInvocation wanted, int
markVerified(actualInvocations, wanted);
}
+
+ public static void checkNumberOfInvocations(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) {
+ List<Invocation> chunk = findMatchingChunk(invocations, wanted, wantedCount, context);
+
+ int actualCount = chunk.size();
+
+ if (wantedCount > actualCount) {
+ Location lastInvocation = getLastLocation(chunk);
+ throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastInvocation);
+ }
+ if (wantedCount < actualCount) {
+ Location firstUndesired = chunk.get(wantedCount).getLocation();
+ throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, firstUndesired);
+ }
+
+ markVerifiedInOrder(chunk, wanted, context);
+ }
+
+ public static void checkNumberOfInvocationsNonGreedy(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) {
+ int actualCount = 0;
+ Location lastLocation = null;
+ while( actualCount < wantedCount ){
+ Invocation next = findFirstMatchingUnverifiedInvocation(invocations, wanted, context );
+ if( next == null ){
+ throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastLocation );
+ }
+ markVerified( next, wanted );
+ context.markVerified( next );
+ lastLocation = next.getLocation();
+ actualCount++;
+ }
+ }
}
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
deleted file mode 100644
index 0445b383ee..0000000000
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.internal.verification.checkers;
-
-import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocationsInOrder;
-import static org.mockito.internal.exceptions.Reporter.tooManyActualInvocationsInOrder;
-import static org.mockito.internal.invocation.InvocationMarker.markVerifiedInOrder;
-import static org.mockito.internal.invocation.InvocationsFinder.findMatchingChunk;
-import static org.mockito.internal.invocation.InvocationsFinder.getLastLocation;
-
-import java.util.List;
-
-import org.mockito.internal.invocation.InvocationMatcher;
-import org.mockito.internal.reporting.Discrepancy;
-import org.mockito.internal.verification.api.InOrderContext;
-import org.mockito.invocation.Invocation;
-import org.mockito.invocation.Location;
-import org.mockito.invocation.MatchableInvocation;
-
-public class NumberOfInvocationsInOrderChecker {
-
- public void check(List<Invocation> invocations, MatchableInvocation wanted, int wantedCount, InOrderContext context) {
- List<Invocation> chunk = findMatchingChunk(invocations, wanted, wantedCount, context);
-
- int actualCount = chunk.size();
-
- if (wantedCount > actualCount) {
- Location lastInvocation = getLastLocation(chunk);
- throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastInvocation);
- }
- if (wantedCount < actualCount) {
- Location firstUndesired = chunk.get(wantedCount).getLocation();
- throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, firstUndesired);
- }
-
- markVerifiedInOrder(chunk, wanted, context);
- }
-}
| diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
index d692fac57d..af9d3cb801 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
@@ -5,10 +5,14 @@
package org.mockito.internal.verification.checkers;
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyList;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -24,17 +28,9 @@
import org.mockito.junit.MockitoJUnitRunner;
import org.mockitousage.IMethods;
-import java.util.List;
-
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static org.assertj.core.api.Assertions.assertThat;
-
@RunWith(MockitoJUnitRunner.class)
public class NumberOfInvocationsCheckerTest {
- private NumberOfInvocationsChecker checker;
-
private InvocationMatcher wanted;
private List<Invocation> invocations;
@@ -48,12 +44,6 @@ public class NumberOfInvocationsCheckerTest {
@Rule
public TestName testName = new TestName();
- @Before
- public void setup() {
- checker = new NumberOfInvocationsChecker();
-
- }
-
@Test
public void shouldReportTooLittleActual() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
@@ -64,7 +54,7 @@ public void shouldReportTooLittleActual() throws Exception {
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 2 times");
- checker.check(invocations, wanted, 100);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100);
}
@Test
@@ -78,7 +68,7 @@ public void shouldReportWithLastInvocationStackTrace() throws Exception {
exception.expectMessage("But was 2 times");
exception.expectMessage(containsTimes("-> at", 2));
- checker.check(invocations, wanted, 100);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100);
}
@Test
@@ -92,7 +82,7 @@ public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() th
exception.expectMessage("But was 0 times");
exception.expectMessage(containsTimes("-> at", 1));
- checker.check(invocations, wanted, 100);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100);
}
@Test
@@ -106,7 +96,7 @@ public void shouldReportWithFirstUndesiredInvocationStackTrace() throws Exceptio
exception.expect(TooManyActualInvocations.class);
exception.expectMessage("" + third.getLocation());
- checker.check(invocations, wanted, 2);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 2);
}
@Test
@@ -120,7 +110,7 @@ public void shouldReportTooManyActual() throws Exception {
exception.expectMessage("Wanted 1 time");
exception.expectMessage("But was 2 times");
- checker.check(invocations, wanted, 1);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1);
}
@Test
@@ -135,7 +125,7 @@ public void shouldReportNeverWantedButInvoked() throws Exception {
exception.expectMessage("But invoked here");
exception.expectMessage("" + first.getLocation());
- checker.check(invocations, wanted, 0);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0);
}
@Test
@@ -145,7 +135,7 @@ public void shouldMarkInvocationsAsVerified() throws Exception {
invocations = asList(invocation);
wanted = buildSimpleMethod().toInvocationMatcher();
- checker.check(invocations, wanted, 1);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1);
assertThat(invocation.isVerified()).isTrue();
}
diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
index 4b1784125d..2e72033238 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
@@ -12,7 +12,6 @@
import java.util.List;
-import org.assertj.core.api.Assertions;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
@@ -30,7 +29,6 @@
public class NumberOfInvocationsInOrderCheckerTest {
- private NumberOfInvocationsInOrderChecker checker;
private InvocationMatcher wanted;
private List<Invocation> invocations;
private InOrderContext context;
@@ -42,7 +40,6 @@ public class NumberOfInvocationsInOrderCheckerTest {
@Before
public void setup() {
- checker = new NumberOfInvocationsInOrderChecker();
context = new InOrderContextImpl();
mock = mock(IMethods.class, "mock");
@@ -53,14 +50,14 @@ public void shouldPassIfWantedIsZeroAndMatchingChunkIsEmpty() {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = emptyList();
- checker.check(invocations, wanted, 0, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0, context);
}
@Test
public void shouldPassIfChunkMatches() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = asList(buildSimpleMethod().toInvocation());
- checker.check(invocations, wanted, 1, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1, context);
}
@Test
@@ -76,7 +73,7 @@ public void shouldReportTooLittleInvocations() throws Exception {
exception.expectMessage("Wanted 4 times");
exception.expectMessage("But was 2 times");
- checker.check(invocations, wanted, 4, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 4, context);
}
@Test
@@ -87,7 +84,7 @@ public void shouldMarkAsVerifiedInOrder() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
assertThat(context.isVerified(invocation)).isFalse();
- checker.check(invocations, wanted, 1, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1, context);
assertThat(context.isVerified(invocation)).isTrue();
}
@@ -101,7 +98,7 @@ public void shouldReportTooLittleActual() throws Exception {
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 2 times");
- checker.check(invocations, wanted, 100, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context);
}
@Test
@@ -115,7 +112,7 @@ public void shouldReportWithLastInvocationStackTrace() throws Exception {
exception.expectMessage("But was 2 times");
exception.expectMessage(containsTimes("-> at", 2));
- checker.check(invocations, wanted, 100, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context);
}
@@ -130,7 +127,7 @@ public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() th
exception.expectMessage("But was 0 times");
exception.expectMessage(containsTimes("-> at", 1));
- checker.check(invocations, wanted, 100, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context);
}
@Test
@@ -144,7 +141,7 @@ public void shouldReportWithFirstUndesiredInvocationStackTrace() throws Exceptio
exception.expect(VerificationInOrderFailure.class);
exception.expectMessage("" + third.getLocation());
- checker.check(invocations, wanted, 2, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 2, context);
}
@Test
@@ -158,7 +155,7 @@ public void shouldReportTooManyActual() throws Exception {
exception.expectMessage("Wanted 1 time");
exception.expectMessage("But was 2 times");
- checker.check(invocations, wanted, 1, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1, context);
}
@Test
@@ -174,17 +171,17 @@ public void shouldReportNeverWantedButInvoked() throws Exception {
exception.expectMessage("But was 1 time. Undesired invocation");
exception.expectMessage("" + first.getLocation());
- checker.check(invocations, wanted, 0, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0, context);
}
@Test
public void shouldMarkInvocationsAsVerified() throws Exception {
Invocation invocation = buildSimpleMethod().toInvocation();
- Assertions.assertThat(invocation.isVerified()).isFalse();
+ assertThat(invocation.isVerified()).isFalse();
invocations = asList(invocation);
wanted = buildSimpleMethod().toInvocationMatcher();
- checker.check(invocations, wanted, 1, context);
+ NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1, context);
assertThat(invocation.isVerified()).isTrue();
}
@@ -203,6 +200,7 @@ private static class StringContainsNumberMatcher extends TypeSafeMatcher<String>
this.amount = amount;
}
+ @Override
public boolean matchesSafely(String text) {
int lastIndex = 0;
int count = 0;
@@ -216,6 +214,7 @@ public boolean matchesSafely(String text) {
return count == amount;
}
+ @Override
public void describeTo(Description description) {
description.appendText("containing '" + expected + "' exactly " + amount + " times");
}
| val | train | 2017-01-23T15:53:02 | "2016-06-11T13:23:18Z" | ChristianSchwarz | train |
mockito/mockito/903_932 | mockito/mockito | mockito/mockito/903 | mockito/mockito/932 | [
"keyword_pr_to_issue"
] | c81d80100f713c87dde74126e0352eb530931b99 | 441540c9c6cca8b58e822d39eda3d1dcefe309be | [
"I have to push the code style decided a few months ago, maybe gradle can generate a section with the mockito style for IDEA (and eclipse and netbeans)",
"Absolutely great idea. Perhaps it's worth waiting for Mockito3 before we do that to avoid merging problems?"
] | [
"Don't we also need the dev dependency for checkstyle?",
"Not sure what you mean by this. Could you please elaborate?\r\n",
"@TimvdLippe, we don't need any extra dependency. checkstyle plugin is a part of Gradle distribution. Good question!",
"@mureinik, do we need separate checker configurations per submodule? I'd rather us have a single consistent checkstyle rule for all java code.",
"Can you write a bit of xml comment here that we added the validation to make the git blame / git diff workflows easier? I suspect this rule can be annoying to engineers when the builds start failing (including me ;). It's nice to see the reminder in the code why we decided to apply those rules.",
"@szczepiq I tried to reduce the scope of the change as much as possible, but you're right - this is a bad idea, and we should use one conf file for the entire project. I'll update the PR.",
"@szczepiq will do, thanks for the idea.",
"Is it necessary to have a stylesheet ?",
"It makes searching for errors a lot easier. Else it would be thousands of rows with 0 information",
"Yup, what @TimvdLippe said. Actually, he authored this style sheet and asked me to include it in the patch."
] | "2017-02-05T21:37:13Z" | [
"refactoring"
] | Review usage of linter during build | Given the amount of stylistic changes lately in primarily @bric3 PRs, I think we should consider installing a linter to make sure the style is enforced project wide. In my opinion this linter should be extremely lenient, just enforce some very simple rules.
We can look into configuring Checkstyle such that it checks a handful of properties. We can always later decide to make the linter more strict. | [
"build.gradle",
"gradle/java-library.gradle",
"src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java"
] | [
"build.gradle",
"config/checkstyle/checkstyle.xml",
"config/checkstyle/checkstyle.xsl",
"gradle/java-library.gradle",
"src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java"
] | [
"src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java",
"src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java",
"src/test/java/org/mockitousage/IMethods.java"
] | diff --git a/build.gradle b/build.gradle
index 2f85ad0e54..f5ab5b4fbd 100644
--- a/build.gradle
+++ b/build.gradle
@@ -35,6 +35,10 @@ allprojects {
options.warnings = false
options.encoding = 'UTF-8'
}
+ apply plugin: 'checkstyle'
+ checkstyle {
+ configFile = rootProject.file('config/checkstyle/checkstyle.xml')
+ }
}
configurations {
diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml
new file mode 100644
index 0000000000..fe1ca7645e
--- /dev/null
+++ b/config/checkstyle/checkstyle.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE module PUBLIC
+ "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
+ "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
+<module name="Checker">
+ <!--
+ Different editors and IDEs may insert or remove trailing
+ whitespaces at the end of source lines or newline characyers
+ at the end of source files.
+
+ This changes have no actual meaning, but may cause visual spam
+ when [re]viewing diffs.
+ Having checkstyles rules to strictly enforce the defacto
+ standards of the project helps avoid such issues and make the
+ review process more efficient.
+
+ See also https://github.com/mockito/mockito/issues/903
+ -->
+ <module name="NewlineAtEndOfFile"/>
+ <module name="RegexpSingleline">
+ <!-- \s matches whitespace character, $ matches end of line. -->
+ <property name="format" value="\s+$"/>
+ <property name="message" value="Line has trailing spaces."/>
+ </module>
+</module>
+
diff --git a/config/checkstyle/checkstyle.xsl b/config/checkstyle/checkstyle.xsl
new file mode 100644
index 0000000000..c9337f4d95
--- /dev/null
+++ b/config/checkstyle/checkstyle.xsl
@@ -0,0 +1,207 @@
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+ <xsl:output method="html" indent="yes"/>
+ <xsl:decimal-format decimal-separator="." grouping-separator="," />
+
+ <xsl:key name="files" match="file" use="@name" />
+
+ <!-- Checkstyle XML Style Sheet by Rolf Wojtech <rolf@wojtech.de> -->
+ <!-- (based on checkstyle-noframe-sorted.xsl by Stephane Bailliez -->
+ <!-- <sbailliez@apache.org> and sf-patch 1721291 by Leo Liang) -->
+ <!-- Changes: -->
+ <!-- * Outputs seperate columns for error/warning/info -->
+ <!-- * Sorts primarily by #error, secondarily by #warning, tertiary by #info -->
+ <!-- * Compatible with windows path names (converts '\' to '/' for html anchor) -->
+ <!-- -->
+ <!-- Part of the Checkstyle distribution found at http://checkstyle.sourceforge.net -->
+ <!-- Usage (generates checkstyle_report.html): -->
+ <!-- <checkstyle failonviolation="false" config="${check.config}"> -->
+ <!-- <fileset dir="${src.dir}" includes="**/*.java"/> -->
+ <!-- <formatter type="xml" toFile="${doc.dir}/checkstyle_report.xml"/> -->
+ <!-- </checkstyle> -->
+ <!-- <style basedir="${doc.dir}" destdir="${doc.dir}" -->
+ <!-- includes="checkstyle_report.xml" -->
+ <!-- style="${doc.dir}/checkstyle-noframes-severity-sorted.xsl"/> -->
+
+ <xsl:template match="checkstyle">
+ <html>
+ <head>
+ <style type="text/css">
+ .bannercell {
+ border: 0px;
+ padding: 0px;
+ }
+ body {
+ margin-left: 10;
+ margin-right: 10;
+ font:normal 80% arial,helvetica,sanserif;
+ background-color:#FFFFFF;
+ color:#000000;
+ }
+ .a td {
+ background: #efefef;
+ }
+ .b td {
+ background: #fff;
+ }
+ th, td {
+ text-align: left;
+ vertical-align: top;
+ }
+ th {
+ font-weight:bold;
+ background: #ccc;
+ color: black;
+ }
+ table, th, td {
+ font-size:100%;
+ border: none
+ }
+ table.log tr td, tr th {
+
+ }
+ h2 {
+ font-weight:bold;
+ font-size:140%;
+ margin-bottom: 5;
+ }
+ h3 {
+ font-size:100%;
+ font-weight:bold;
+ background: #525D76;
+ color: white;
+ text-decoration: none;
+ padding: 5px;
+ margin-right: 2px;
+ margin-left: 2px;
+ margin-bottom: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <a name="top"></a>
+ <!-- jakarta logo -->
+ <table border="0" cellpadding="0" cellspacing="0" width="100%">
+ <tr>
+ <td class="bannercell" rowspan="2">
+ <!--a href="http://jakarta.apache.org/">
+ <img src="http://jakarta.apache.org/images/jakarta-logo.gif" alt="http://jakarta.apache.org" align="left" border="0"/>
+ </a-->
+ </td>
+ <td class="text-align:right"><h2>CheckStyle Audit</h2></td>
+ </tr>
+ <tr>
+ <td class="text-align:right">Designed for use with <a href='http://checkstyle.sourceforge.net/'>CheckStyle</a> and <a href='http://jakarta.apache.org'>Ant</a>.</td>
+ </tr>
+ </table>
+ <hr size="1"/>
+
+ <!-- Summary part -->
+ <xsl:apply-templates select="." mode="summary"/>
+ <hr size="1" width="100%" align="left"/>
+
+ <xsl:if test="count(descendant::file[error]) + count(descendant::file[warning]) + count(descendant::file[info]) > 0">
+ <!-- Package List part -->
+ <xsl:apply-templates select="." mode="filelist"/>
+ <hr size="1" width="100%" align="left"/>
+
+ <!-- For each package create its part -->
+ <xsl:apply-templates select="file[@name and generate-id(.) = generate-id(key('files', @name))][count(error) + count(warning) + count(info) > 0]" />
+ <hr size="1" width="100%" align="left"/>
+ </xsl:if>
+ </body>
+ </html>
+ </xsl:template>
+
+
+
+ <xsl:template match="checkstyle" mode="filelist">
+ <h3>Files</h3>
+ <table class="log" border="0" cellpadding="5" cellspacing="2" width="100%">
+ <tr>
+ <th>Name</th>
+ <th>Errors</th>
+ <th>Warnings</th>
+ <th>Infos</th>
+ </tr>
+ <xsl:for-each select="file[@name and generate-id(.) = generate-id(key('files', @name))][count(error) + count(warning) + count(info) > 0]">
+
+ <!-- Sort method 1: Primary by #error, secondary by #warning, tertiary by #info -->
+ <xsl:sort data-type="number" order="descending" select="count(key('files', @name)/error[@severity='error'])"/>
+ <xsl:sort data-type="number" order="descending" select="count(key('files', @name)/error[@severity='warning'])"/>
+ <xsl:sort data-type="number" order="descending" select="count(key('files', @name)/error[@severity='info'])"/>
+
+ <!-- Sort method 1: Sum(#error+#info+#warning) (uncomment to use, comment method 1) -->
+ <!--
+ <xsl:sort data-type="number" order="descending" select="count(key('files', @name)/error)"/>
+ -->
+
+ <xsl:variable name="errorCount" select="count(key('files', @name)/error[@severity='error'])"/>
+ <xsl:variable name="warningCount" select="count(key('files', @name)/error[@severity='warning'])"/>
+ <xsl:variable name="infoCount" select="count(key('files', @name)/error[@severity='info'])"/>
+
+ <tr>
+ <xsl:call-template name="alternated-row"/>
+ <td><a href="#f-{translate(@name,'\','/')}"><xsl:value-of select="@name"/></a></td>
+ <td><xsl:value-of select="$errorCount"/></td>
+ <td><xsl:value-of select="$warningCount"/></td>
+ <td><xsl:value-of select="$infoCount"/></td>
+ </tr>
+ </xsl:for-each>
+ </table>
+ </xsl:template>
+
+
+ <xsl:template match="file">
+ <a name="f-{translate(@name,'\','/')}"></a>
+ <h3>File <xsl:value-of select="@name"/></h3>
+
+ <table class="log" border="0" cellpadding="5" cellspacing="2" width="100%">
+ <tr>
+ <th>Severity</th>
+ <th>Error Description</th>
+ <th>Line</th>
+ </tr>
+ <xsl:for-each select="key('files', @name)/error">
+ <xsl:sort data-type="number" order="ascending" select="@line"/>
+ <tr>
+ <xsl:call-template name="alternated-row"/>
+ <td><xsl:value-of select="@severity"/></td>
+ <td><xsl:value-of select="@message"/></td>
+ <td><xsl:value-of select="@line"/></td>
+ </tr>
+ </xsl:for-each>
+ </table>
+ <a href="#top">Back to top</a>
+ </xsl:template>
+
+
+ <xsl:template match="checkstyle" mode="summary">
+ <h3>Summary</h3>
+ <xsl:variable name="fileCount" select="count(file[@name and generate-id(.) = generate-id(key('files', @name))])"/>
+ <xsl:variable name="errorCount" select="count(file/error[@severity='error'])"/>
+ <xsl:variable name="warningCount" select="count(file/error[@severity='warning'])"/>
+ <xsl:variable name="infoCount" select="count(file/error[@severity='info'])"/>
+ <table class="log" border="0" cellpadding="5" cellspacing="2" width="100%">
+ <tr>
+ <th>Files</th>
+ <th>Errors</th>
+ <th>Warnings</th>
+ <th>Infos</th>
+ </tr>
+ <tr>
+ <xsl:call-template name="alternated-row"/>
+ <td><xsl:value-of select="$fileCount"/></td>
+ <td><xsl:value-of select="$errorCount"/></td>
+ <td><xsl:value-of select="$warningCount"/></td>
+ <td><xsl:value-of select="$infoCount"/></td>
+ </tr>
+ </table>
+ </xsl:template>
+
+ <xsl:template name="alternated-row">
+ <xsl:attribute name="class">
+ <xsl:if test="position() mod 2 = 1">a</xsl:if>
+ <xsl:if test="position() mod 2 = 0">b</xsl:if>
+ </xsl:attribute>
+ </xsl:template>
+</xsl:stylesheet>
diff --git a/gradle/java-library.gradle b/gradle/java-library.gradle
index 9c34a86fea..4eb9814528 100644
--- a/gradle/java-library.gradle
+++ b/gradle/java-library.gradle
@@ -28,5 +28,13 @@ test {
}
}
+tasks.withType(Checkstyle) {
+ reports {
+ xml.enabled false
+ html.enabled true
+ html.stylesheet resources.text.fromFile("$rootDir/config/checkstyle/checkstyle.xsl")
+ }
+}
+
assert project.hasProperty("artifactName") : "Please configure 'ext.artifactName' for project that wants to use 'java-library.gradle' plugin"
-archivesBaseName = project.ext.artifactName
\ No newline at end of file
+archivesBaseName = project.ext.artifactName
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java b/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java
index 81e85144ee..bc625fb1bc 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java
@@ -17,13 +17,13 @@ public class DoesNothing implements Answer<Object>, ValidableAnswer, Serializabl
private static final long serialVersionUID = 4840880517740698416L;
private static final DoesNothing SINGLETON = new DoesNothing();
-
+
private DoesNothing() {}
-
+
public static DoesNothing doesNothing(){
return SINGLETON;
}
-
+
@Override
public Object answer(InvocationOnMock invocation){
return null;
| diff --git a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
index 06f950e2ba..f3c83ffad0 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
@@ -16,7 +16,7 @@
import org.mockitousage.IMethods;
public class DoesNothingTest {
-
+
private IMethods mock;
private Invocation invocation_Void;
private Invocation invocation_void;
@@ -25,17 +25,17 @@ public class DoesNothingTest {
@Before
public void init(){
mock = mock(IMethods.class);
-
+
mock.voidMethod();
invocation_Void = getLastInvocation();
-
+
mock.voidReturningMethod();
invocation_void = getLastInvocation();
-
+
mock.simpleMethod();
invocation_String = getLastInvocation();
}
-
+
@Test
public void answer_returnsNull() throws Throwable {
assertThat(doesNothing().answer(invocation_Void)).isNull();
@@ -52,11 +52,11 @@ public void validateFor_nonVoidReturnType_shouldFail() {
public void validateFor_voidReturnType_shouldPass() {
doesNothing().validateFor(invocation_void);
}
-
+
@Test
public void validateFor_voidObjectReturnType() throws Throwable {
doesNothing().validateFor(invocation_Void);
}
-
-
+
+
}
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java b/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
index 6d4a1ab5db..d683605392 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
@@ -76,31 +76,31 @@ public void should_know_method_is_declared_on_interface() throws Exception {
assertThat(new InvocationInfo(new InvocationBuilder().method(iAmAbstract()).toInvocation()).isDeclaredOnInterface()).isFalse();
assertThat(new InvocationInfo(new InvocationBuilder().method("voidMethod").toInvocation()).isDeclaredOnInterface()).isTrue();
}
-
+
@Test
public void isVoid_invocationOnVoidMethod_returnTrue(){
mock(IMethods.class).voidMethod();
-
+
InvocationInfo voidMethod = new InvocationInfo(getLastInvocation());
-
+
assertThat(voidMethod.isVoid()).isTrue();
}
-
+
@Test
public void isVoid_invocationOnVoidReturningMethod_returnTrue(){
mock(IMethods.class).voidReturningMethod();
-
+
InvocationInfo voidRetuningMethod = new InvocationInfo(getLastInvocation());
-
+
assertThat(voidRetuningMethod.isVoid()).isTrue();
}
-
+
@Test
public void isVoid_invocationNonVoidMethod_returnFalse(){
mock(IMethods.class).simpleMethod();
-
+
InvocationInfo stringReturningMethod = new InvocationInfo(getLastInvocation());
-
+
assertThat(stringReturningMethod.isVoid()).isFalse();
}
@@ -110,7 +110,7 @@ abstract class TheAbstract {
}
return TheAbstract.class.getDeclaredMethod("iAmAbstract");
}
-
+
private Method iAmNotAbstract() throws NoSuchMethodException {
abstract class TheNotAbstract {
void iAmNotAbstract() {};
diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java
index f360475bec..2d5663115c 100644
--- a/src/test/java/org/mockitousage/IMethods.java
+++ b/src/test/java/org/mockitousage/IMethods.java
@@ -187,7 +187,7 @@ public interface IMethods {
String toString(String foo);
void voidMethod();
-
+
Void voidReturningMethod();
String forList(List<String> list);
| val | train | 2017-02-16T22:12:08 | "2017-01-23T10:23:07Z" | TimvdLippe | train |
mockito/mockito/927_933 | mockito/mockito | mockito/mockito/927 | mockito/mockito/933 | [
"keyword_pr_to_issue"
] | 3e9a94b7b9938dbdb882e28c24c2b163c2d19390 | 275586ecf3a00da078b6fb7e9cc4508231cc4301 | [] | [
"Spacing around `=`",
"Very nice! Thank you for updating the documentation diligently."
] | "2017-02-06T12:43:14Z" | [] | Mockito can't unbox Void | Hi,
The following [bug](https://github.com/powermock/powermock/issues/708) was created for PowerMock:
> PowerMockito doesn't seem to unbox java.lang.Void.
> I am writing a test for my code that uses Google cloud storage API to delete a file. Google API returns Void for deleting a file. Code works fine but when I instruct my test as PowerMockito.doNothing().when(delete).execute(); It complains that execute has a return value of Void.
But PowerMock just delegates call to Mockito in this case and Mockito throws exception:
```
org.mockito.exceptions.base.MockitoException:
Only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
```
I have doubts about expected behaviour. For one side, method return something, but it return a `Void` which always is just `Void` and nothing could be changed.
Anyway, it could be fixed only on Mockito side (without dirty hacks). | [
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java",
"src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java",
"src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java"
] | [
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java",
"src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java",
"src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java"
] | [
"src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java",
"src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java",
"src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java",
"src/test/java/org/mockitousage/IMethods.java",
"src/test/java/org/mockitousage/MethodsImpl.java",
"src/test/java/org/mockitoutil/TestBase.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
index 9f1f8db523..f768cc829f 100644
--- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
@@ -6,12 +6,12 @@
import static org.mockito.internal.exceptions.Reporter.notAMockPassedToWhenMethod;
import static org.mockito.internal.exceptions.Reporter.nullPassedToWhenMethod;
+import static org.mockito.internal.stubbing.answers.DoesNothing.doesNothing;
import java.util.LinkedList;
import java.util.List;
import org.mockito.internal.stubbing.answers.CallsRealMethods;
-import org.mockito.internal.stubbing.answers.DoesNothing;
import org.mockito.internal.stubbing.answers.Returns;
import org.mockito.internal.stubbing.answers.ThrowsException;
import org.mockito.internal.stubbing.answers.ThrowsExceptionClass;
@@ -24,6 +24,7 @@ public class StubberImpl implements Stubber {
private final List<Answer<?>> answers = new LinkedList<Answer<?>>();
+ @Override
public <T> T when(T mock) {
if (mock == null) {
throw nullPassedToWhenMethod();
@@ -37,10 +38,12 @@ public <T> T when(T mock) {
return mock;
}
+ @Override
public Stubber doReturn(Object toBeReturned) {
return doReturnValues(toBeReturned);
}
+ @Override
public Stubber doReturn(Object toBeReturned, Object... nextToBeReturned) {
return doReturnValues(toBeReturned).doReturnValues(nextToBeReturned);
}
@@ -56,6 +59,7 @@ private StubberImpl doReturnValues(Object... toBeReturned) {
return this;
}
+ @Override
public Stubber doThrow(Throwable... toBeThrown) {
if(toBeThrown == null) {
answers.add(new ThrowsException(null));
@@ -67,10 +71,12 @@ public Stubber doThrow(Throwable... toBeThrown) {
return this;
}
+ @Override
public Stubber doThrow(Class<? extends Throwable> toBeThrown) {
return doThrowClasses(toBeThrown);
}
+ @Override
public Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
return doThrowClasses(toBeThrown).doThrowClasses(nextToBeThrown);
}
@@ -82,16 +88,19 @@ private StubberImpl doThrowClasses(Class<? extends Throwable>... toBeThrown) {
return this;
}
+ @Override
public Stubber doNothing() {
- answers.add(new DoesNothing());
+ answers.add(doesNothing());
return this;
}
+ @Override
public Stubber doAnswer(Answer answer) {
answers.add(answer);
return this;
}
+ @Override
public Stubber doCallRealMethod() {
answers.add(new CallsRealMethods());
return this;
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java b/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java
index 5d723b3ade..81e85144ee 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/DoesNothing.java
@@ -16,7 +16,16 @@ public class DoesNothing implements Answer<Object>, ValidableAnswer, Serializabl
private static final long serialVersionUID = 4840880517740698416L;
- public Object answer(InvocationOnMock invocation) throws Throwable {
+ private static final DoesNothing SINGLETON = new DoesNothing();
+
+ private DoesNothing() {}
+
+ public static DoesNothing doesNothing(){
+ return SINGLETON;
+ }
+
+ @Override
+ public Object answer(InvocationOnMock invocation){
return null;
}
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java b/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java
index a405b94cac..11498b793d 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/InvocationInfo.java
@@ -38,8 +38,13 @@ public boolean isValidReturnType(Class<?> clazz) {
}
}
+ /**
+ * Returns {@code true} is the return type is {@link Void} or represents the pseudo-type to the keyword {@code void}.
+ * E.g: {@code void foo()} or {@code Void bar()}
+ */
public boolean isVoid() {
- return this.method.getReturnType() == Void.TYPE;
+ Class<?> returnType = this.method.getReturnType();
+ return returnType == Void.TYPE|| returnType == Void.class;
}
public String printMethodReturnType() {
@@ -62,6 +67,7 @@ public boolean isDeclaredOnInterface() {
return method.getDeclaringClass().isInterface();
}
+ @Override
public boolean isAbstract() {
return (method.getModifiers() & Modifier.ABSTRACT) != 0;
}
| diff --git a/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java b/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java
index 5ea343a6c3..cfff121d7e 100644
--- a/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java
+++ b/src/test/java/org/mockito/internal/junit/UnusedStubbingsTest.java
@@ -11,6 +11,7 @@
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
+import static org.mockito.internal.stubbing.answers.DoesNothing.doesNothing;
public class UnusedStubbingsTest extends TestBase {
@@ -32,8 +33,8 @@ public void no_unused_stubbings() throws Exception {
public void unused_stubbings() throws Exception {
//given
UnusedStubbings stubbings = new UnusedStubbings((List) asList(
- new StubbedInvocationMatcher(new InvocationBuilder().toInvocationMatcher(), new DoesNothing()),
- new StubbedInvocationMatcher(new InvocationBuilder().toInvocationMatcher(), new DoesNothing())
+ new StubbedInvocationMatcher(new InvocationBuilder().toInvocationMatcher(), doesNothing()),
+ new StubbedInvocationMatcher(new InvocationBuilder().toInvocationMatcher(), doesNothing())
));
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
index 668bf82d56..06f950e2ba 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java
@@ -4,25 +4,59 @@
*/
package org.mockito.internal.stubbing.answers;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.internal.stubbing.answers.DoesNothing.doesNothing;
+import static org.mockitoutil.TestBase.getLastInvocation;
+
+import org.junit.Before;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.internal.invocation.InvocationBuilder;
+import org.mockito.invocation.Invocation;
+import org.mockitousage.IMethods;
-import static org.assertj.core.api.Assertions.assertThat;
+public class DoesNothingTest {
+
+ private IMethods mock;
+ private Invocation invocation_Void;
+ private Invocation invocation_void;
+ private Invocation invocation_String;
-public class DoesNothingTest {
+ @Before
+ public void init(){
+ mock = mock(IMethods.class);
+
+ mock.voidMethod();
+ invocation_Void = getLastInvocation();
+
+ mock.voidReturningMethod();
+ invocation_void = getLastInvocation();
+
+ mock.simpleMethod();
+ invocation_String = getLastInvocation();
+ }
+
@Test
- public void should_do_nothing() throws Throwable {
- assertThat(new DoesNothing().answer(new InvocationBuilder().method("voidMethod").toInvocation())).isNull();
+ public void answer_returnsNull() throws Throwable {
+ assertThat(doesNothing().answer(invocation_Void)).isNull();
+ assertThat(doesNothing().answer(invocation_void)).isNull();
+ assertThat(doesNothing().answer(invocation_String)).isNull();
}
@Test(expected = MockitoException.class)
- public void should_fail_when_non_void_method_does_nothing() throws Throwable {
- new DoesNothing().validateFor(new InvocationBuilder().simpleMethod().toInvocation());
+ public void validateFor_nonVoidReturnType_shouldFail() {
+ doesNothing().validateFor(invocation_String);
}
@Test
- public void should_allow_void_return_for_void_method() throws Throwable {
- new DoesNothing().validateFor(new InvocationBuilder().method("voidMethod").toInvocation());
+ public void validateFor_voidReturnType_shouldPass() {
+ doesNothing().validateFor(invocation_void);
+ }
+
+ @Test
+ public void validateFor_voidObjectReturnType() throws Throwable {
+ doesNothing().validateFor(invocation_Void);
}
+
+
}
diff --git a/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java b/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
index f104972858..6d4a1ab5db 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/InvocationInfoTest.java
@@ -7,10 +7,17 @@
import java.lang.reflect.Method;
import java.nio.charset.CharacterCodingException;
import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.invocation.Invocation;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockitoutil.TestBase.getLastInvocation;
public class InvocationInfoTest {
@@ -69,6 +76,33 @@ public void should_know_method_is_declared_on_interface() throws Exception {
assertThat(new InvocationInfo(new InvocationBuilder().method(iAmAbstract()).toInvocation()).isDeclaredOnInterface()).isFalse();
assertThat(new InvocationInfo(new InvocationBuilder().method("voidMethod").toInvocation()).isDeclaredOnInterface()).isTrue();
}
+
+ @Test
+ public void isVoid_invocationOnVoidMethod_returnTrue(){
+ mock(IMethods.class).voidMethod();
+
+ InvocationInfo voidMethod = new InvocationInfo(getLastInvocation());
+
+ assertThat(voidMethod.isVoid()).isTrue();
+ }
+
+ @Test
+ public void isVoid_invocationOnVoidReturningMethod_returnTrue(){
+ mock(IMethods.class).voidReturningMethod();
+
+ InvocationInfo voidRetuningMethod = new InvocationInfo(getLastInvocation());
+
+ assertThat(voidRetuningMethod.isVoid()).isTrue();
+ }
+
+ @Test
+ public void isVoid_invocationNonVoidMethod_returnFalse(){
+ mock(IMethods.class).simpleMethod();
+
+ InvocationInfo stringReturningMethod = new InvocationInfo(getLastInvocation());
+
+ assertThat(stringReturningMethod.isVoid()).isFalse();
+ }
private Method iAmAbstract() throws NoSuchMethodException {
abstract class TheAbstract {
@@ -76,6 +110,7 @@ abstract class TheAbstract {
}
return TheAbstract.class.getDeclaredMethod("iAmAbstract");
}
+
private Method iAmNotAbstract() throws NoSuchMethodException {
abstract class TheNotAbstract {
void iAmNotAbstract() {};
diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java
index 15971a546b..f360475bec 100644
--- a/src/test/java/org/mockitousage/IMethods.java
+++ b/src/test/java/org/mockitousage/IMethods.java
@@ -187,6 +187,8 @@ public interface IMethods {
String toString(String foo);
void voidMethod();
+
+ Void voidReturningMethod();
String forList(List<String> list);
diff --git a/src/test/java/org/mockitousage/MethodsImpl.java b/src/test/java/org/mockitousage/MethodsImpl.java
index 1470b8dc87..b9830579e7 100644
--- a/src/test/java/org/mockitousage/MethodsImpl.java
+++ b/src/test/java/org/mockitousage/MethodsImpl.java
@@ -446,4 +446,9 @@ public Integer toIntWrapper(int i) {
public String forObject(Object object) {
return null;
}
+
+ @Override
+ public Void voidReturningMethod() {
+ return null;
+ }
}
diff --git a/src/test/java/org/mockitoutil/TestBase.java b/src/test/java/org/mockitoutil/TestBase.java
index 0488532c19..464e2d5840 100644
--- a/src/test/java/org/mockitoutil/TestBase.java
+++ b/src/test/java/org/mockitoutil/TestBase.java
@@ -56,7 +56,7 @@ public void resetState() {
new StateMaster().reset();
}
- protected Invocation getLastInvocation() {
+ public static Invocation getLastInvocation() {
return new MockitoCore().getLastInvocation();
}
| train | train | 2017-02-06T16:04:22 | "2017-02-03T18:42:17Z" | thekingn0thing | train |
mockito/mockito/894_934 | mockito/mockito | mockito/mockito/894 | mockito/mockito/934 | [
"timestamp(timedelta=0.0, similarity=0.8756630753506662)",
"keyword_pr_to_issue"
] | 3e9a94b7b9938dbdb882e28c24c2b163c2d19390 | 64ab2f7f52c2cc8f0a3381df5fecbc8d30b5d765 | [
"I tried to add in previous Open JDK 8 (102) but the option is not recognized\r\n\r\n```\r\noption.addStringOption('--allow-script-in-comments')\r\noption.addStringOption('-allow-script-in-comments')\r\noption.addStringOption('allow-script-in-comments')\r\n```\r\n\r\nI'll try later with the same JDK (121)",
"Could it be related to #787 ?",
"I will also take another look at the service-worker thing, as it does not appear to work with javadoc.io. If I can't fix it (after exams :wink: ) then I will simply revert it.",
";)\r\n\r\nContiuous improvements",
"From the release notes: http://www.oracle.com/technetwork/java/javase/8u121-relnotes-3315208.html\r\n\r\n> The javadoc tool will now reject any occurrences of JavaScript code in the javadoc documentation comments and command-line options, unless the command-line option, --allow-script-in-comments is specified.\r\n> \r\n> With the --allow-script-in-comments option, the javadoc tool will preserve JavaScript code in documentation comments and command-line options. An error will be given by the javadoc tool if JavaScript code is found and the command-line option is not set.\r\n> JDK-8138725 (not public)"
] | [
"Thank you for fixing the problem and documenting it diligently!"
] | "2017-02-06T14:34:05Z" | [
"java-8",
"continuous integration"
] | Javadoc generation fails with jdk1.8.0_121 | When I set the jdk to jdk1.8.0_121 the build fails javadoc error.
Full log including steps to reproduce:
```
~/mockito/src$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/
~/mockito/src$ ./gradlew javadoc -i
...
javadoc: error - Argument for -top contains JavaScript.
Use --allow-script-in-comments to allow use of JavaScript.
1 error
100 warnings
Problems generating Javadoc.
...
:javadoc FAILED
:javadoc (Thread[Task worker,5,main]) completed. Took 1.936 secs.
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':javadoc'.
> Javadoc generation failed. Generated Javadoc options file (useful for troubleshooting): '/Users/sfaber/mockito/src/build/tmp/javadoc/javadoc.options'
* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.
BUILD FAILED
``` | [
"gradle/mockito-core/javadoc.gradle"
] | [
"gradle/mockito-core/javadoc.gradle"
] | [] | diff --git a/gradle/mockito-core/javadoc.gradle b/gradle/mockito-core/javadoc.gradle
index 5bb5203299..a8d4be36ec 100644
--- a/gradle/mockito-core/javadoc.gradle
+++ b/gradle/mockito-core/javadoc.gradle
@@ -66,8 +66,18 @@ javadoc {
""".replaceAll(/\r|\n|[ ]{8}/, ""))
if (JavaVersion.current().isJava8Compatible()) {
options.addStringOption('Xdoclint:none', '-quiet')
+
+ def minorVersion = System.getProperty("java.version") =~ /1.8.0_(.*)/
+
+ // Since JDK 8 version 121 scripts are not allowed in comments. However,
+ // earlier version throw an error if an unknown option is passed.
+ // Therefore only add this option if the JDK is actually correct.
+ if (minorVersion.size() > 0 && Integer.valueOf(minorVersion[0][1]) >= 121) {
+ options.addBooleanOption('-allow-script-in-comments', true)
+ }
}
+
doLast {
copy {
from "src/javadoc"
| null | val | train | 2017-02-06T16:04:22 | "2017-01-20T15:07:48Z" | mockitoguy | train |
mockito/mockito/680_942 | mockito/mockito | mockito/mockito/680 | mockito/mockito/942 | [
"timestamp(timedelta=0.0, similarity=0.9999999999999999)",
"keyword_pr_to_issue"
] | 64ab2f7f52c2cc8f0a3381df5fecbc8d30b5d765 | bba71f645680a33d0d21fef49aa916399c0bc9b9 | [
"> mock(DM.class, withSettings().useDefaultMethods())\n\nI like that. 'spyDefaultMethods'?\n\nBTW. What's better/more intuitive default for default methods? real method invocation or empty/unstubbed value?\n",
"I think that depends on the mocked type. I'd say :\n- interface => use default methods by default\n- concrete => I'm not sure I'd rather not make those default\n\n`spyDefaultMethod` is wrong because the primary objective is not to spy them.\n",
"So potentially this is Mockito 3 backwards incompatible change (when changing defaults). Thanks for bringing this up!\n",
"For this thing only this could be potntially backward incompatible. Yet for this thing only I'm not yet sure we should change the default between 2.x and 3.x whatever the introduction or not of `useDefaultMethods` in `2.x`. \n\nI'm a bit undecided at that moment. I may have a better opinion when the code is actually done. \n\nRight now the code base of mockito 2.x runs Java6 so we don't have Java 8 tests, Mockito 3 (master) is Java 8 and we'll introduce Java 8 specific tests.\n",
"Makes perfect sense.\n\nWe already have code in 2.x that detects java 8. Up to you how to push that further ;)\n",
"If starting from scratch, I couldn't think of a use case that'd benefit from stubbing the default methods by default.\r\n\r\nBut maybe that use case does exist, or at least for backward compatibility it's too late to change?\r\n\r\nEither way, I propose we do not need to add a default Answer or anything to mock(). \r\n\r\nDefault methods in interfaces are much like concrete methods in abstract classes. `spy(AnAbstractClass.class)` today already _by default_ invokes concrete methods unless they are explicitly stubbed. It seems natural to me that we just relax the restriction on `spy(SomeInterface.class)` to accept interface as a parameter instead of throwing illegal usage exception as it does today.\r\n",
"@fluentfuture Can you elaborate on that : \r\n\r\n> It seems natural to me that we just relax the restriction on `spy(SomeInterface.class)` to accept interface as a parameter instead of throwing illegal usage exception as it does today.\r\n\r\nYes backward compatiblity is a primary concern. Yet if the change makes sense and doesn't impact users in a bad way it can be discussed.\r\nAlso maybe we could backport behavior and API from master to release/2x.",
"Sure.\r\n\r\nToday, if java.util.Consumer were an abstract class defined as:\r\n\r\n```java\r\npublic abstract class Consumer<T> {\r\n public Consumer<T> andThen(Consumer<? super T> that) {\r\n return v -> {accept(v); that.accept(v);};\r\n }\r\n\r\n public abstract void accept(T value);\r\n}\r\n```\r\n\r\nI can `@Spy` it to have `andThen()` called by default:\r\n```java\r\n@Spy private final Consumer<String> consumer1;\r\n@Spy private final Consumer<String> consumer2;\r\n\r\n@Test public void testCompose() {\r\n consumer1.andThen(consumer2).accept(\"hi\");\r\n verify(consumer1).accept(\"hi\");\r\n verify(consumer2).accept(\"hi\");\r\n}\r\n```\r\n\r\nIt doesn't work with Consumer being interface with `andThen()` being an equivalent default method:\r\n\r\n```java\r\npublic interface Consumer<T> {\r\n default Consumer<T> andThen(Consumer<? super T> that) {\r\n return v -> {accept(v); that.accept(v);};\r\n }\r\n\r\n void accept(T value);\r\n}\r\n```\r\n\r\nBut that is just because we are having a validation that rejects spy(Consumer.class). That validation can be removed because it doesn't hurt even if you spy(AnInterface.class) and even if that interface has no default method, because it will just work the same way as mock(AnInterface.class).\r\n\r\nHere's a [commit](https://github.com/fluentfuture/mockito/commit/afdd5ebc32de38d098c517bda32c83e194371574) in my fork that removes the validation and the above test passes.\r\n\r\n\r\nBy the way, I retract my suggestion to make `mock(AnInterface.class)` to call default methods, because then it would break the symmetry with `mock(AnEquivalentAbstractClass.class)`, which can be surprising.",
"Ah I see.\r\n\r\nImho spying an interface `spy(Interface.class)` is wrong, even when there's default methods, it doesn't feel like a a spy. As spy have more meaning to spy concrete code.\r\n\r\nInstead mocking an interface `mock(Interface.class)` to call default methods only seems ok. And maybe backward compatible. Although I would like opt-in/out mechanism.\r\nBut mocking an abstract class `mock(AnEquivalentAbstractClass.class)` should never call concrete code.",
"I agree that the spy() name is kinda misleading for the behavior of \"mock only abstract methods\".\r\n\r\nI originally proposed fake() or other names but spy() was chosen none-the-less.\r\n\r\nI don't defend the spy() name but it's what we have, so there may be some value to consistency.\r\n\r\n",
"`spy` is a specialized mock that seems to _speak_ for everyone, maybe `fake` can be another compelling specilization.\r\n\r\nAt this moment not sure if we will, but maybe in the future.",
"Here's how I found peace with the spy() name:\r\n\r\nYes it calls the non-abstract methods, which isn't spying (more like fake). But it also allows you to explicitly stub them with `when()` or to `verify()` them, so in that sense, it can still be called a spy.",
"Regarding \"interface\" vs. \"abstract class\", I personally think we should try not to be picky about the difference.\r\n\r\nSome project scoped or company scoped APIs out there aren't designed to be implemented/subclassed directly by users. For these APIs, going from an abstract class to interface or vice versa is reserved as an implementation detail change.\r\n\r\nThe worst that should happen with changing abstract class to interface is that a handful of direct subclasses break compilation and need to be fixed to use the \"implements\" keyword.\r\n\r\nIt'd be a much bigger burden if all the sudden a lot of tests that used to spy() on the abstract class fail just because of the abstract -> interface change.\r\n\r\nSpecifically, now with Java 8, I'd expect some abstract classes to become interfaces with default methods because the only reason they were abstract classes in the first place was to be able to have some default methods (for fluent chaining and stuff).",
"Interesting feedback. I still have mixed feeling about relaxing spy to allow an interface.\r\nI'll sleep on it, and think about it as your migration use case is legitimate.\r\n\r\nAnd anyway this address only a part of the original issue.",
"@bric3 Can you explain which part isn't addressed in the original issue, assuming we put aside the mock() vs. spy() naming difference?",
"@fluentfuture I meant regarding configurability of stubbing default method for a mock, not a spy.\r\n\r\nYet the use cases discussed above are defintely additional scenario to account for when we will implement the stuff.",
"@bric3 Are you okay with allowing @Spy on interfaces? If so, I'll send a PR.",
"@fluentfuture yes. I have worked on it in #906. But I won't have a computer near me for a week still.",
"Great discussion. \r\n\r\n+1 to allow spying on interfaces\r\n-1 to adding new public API method like 'fake' - it would make the api more complicated just for the sake of a single use case\r\n+ 0.5 to changing the default behavior of Mockito 3 to 'spy' interface defender methods by default. This way it is the most intuitive behavior users expect. See https://github.com/mockito/mockito/issues/940",
"I attempted to update the ticket description to reflect the outcome of the discussion. Feel free to change if needed.",
"If I were going to add another method I would call it `stub` based on [Martin Fowler's article describing the 3]( https://martinfowler.com/articles/mocksArentStubs.html).\r\n\r\nSeems like `@Incubating Mockito.spy( Class<?> clazz )` more or less does what I expect. Ultimately finding that behavior though required quite a bit of research.\r\n\r\nWhether or not adding `Mockito.stub( Class<?> clazz )` method would be worth it I can't say because I don't feel like I'm familiar enough with the underlying implementation/behavior to know how different `mock` and `spy` are. If those are just configuration differences then it's probably worth it, if there's more to it, maybe not. If `stub` could `CALL_REAL_METHODS`, but only work for `abstract` and `interface` and not be able to do `verify` that would make it different from a `spy`, imo.\r\n\r\nEither way, more docs seem necessary. I might try to put those together for #940 ",
"I somehow missed this ticket. \r\n\r\nMockito should imho follow the idea of defender methods and allow API-evolution without breaking client code/test. I other words if a class under test evolves and calls defender methods on a mocked interface the tests should not fail or should not be rewritten by replacing `@Mock` with `@Spy` or setting up special mocking settings like `withSettings().useDefaultMethods()`.\r\n\r\nI think it is possibe to rewrite the `mock(..)` implementation to generate stubbed calls to default methods without special mock settings. \r\n\r\n```java\r\npublic <T> T mock(Class<T> type){\r\n T mock=MOCKITO_CORE.mock(type);\r\n if (!typeToMock.isInterface())\r\n return mock;\r\n\r\n for (Method method : typeToMock.getDeclaredMethods()) {\r\n if (method.isDefault()) {\r\n doCallRealMethod().when(mock);\r\n callWithAnyMatchers(mock, method);\r\n }\r\n }\r\n return mock;\r\n}\r\n\r\nprivate static void callWithAnyMatchers(Object mock, Method method) {\r\n Class<?>[] parameterTypes = method.getParameterTypes();\r\n List<Object> defaultValues = new ArrayList<Object>();\r\n for (Class<?> type : parameterTypes) {\r\n defaultValues.add(Mockito.any(type));\r\n }\r\n \r\n try {\r\n method.invoke(mock, defaultValues.toArray());\r\n } catch (Exception e) {\r\n throw new MockitoException(e.getMessage(), e);\r\n }\r\n}\r\n\r\n\r\n```\r\nThis way clients can redefine the defender stubbings like overriding it in an implementation. \r\n\r\n@bric3 \r\n@szczepiq \r\n@fluentfuture \r\nWhat do you think?\r\n\r\n\r\n",
"Is it any different from API-evolution of abstract classes?\r\n\r\nIn template-method pattern, if the SUT calls an abstract method, and then later evolves to call a default method that indirectly calls the abstract method, the exact same problem can happen, no?\r\n\r\nThis kind of evolution has always been possible. And it's not clear to me that the user always means to only stub/verify the abstract method. Sometimes the user may just want to stub/verify the method directly called, abstract or not.\r\n\r\nIt seems to me not the mocking framework's responsibility to guess the user's intention. Instead, if the user wants to stub/verify the direct method invocation, use `@Mock;` while if the user wants to stub/verify abstract methods, use `@Spy`.\r\n\r\n",
"> Is it any different from API-evolution of abstract classes?\r\n>\r\n>In template-method pattern, if the SUT calls an abstract method, and then later evolves to call a default method that indirectly calls the abstract method, the exact same problem can happen, no?\r\n\r\nI agree if you see it like that they are pretty equal.\r\n\r\nI want to avoid that `@Spy` is misused to stub in the first place. The word \"spying\" implies that there is something to spy on (the SUT), but for interfaces the \"spying\" make no sense we would spy on a mocked interface. \r\n\r\n>It seems to me not the mocking framework's responsibility to guess the user's intention. \r\n\r\nI agree here too! What about a littel helper that create stubbings that call the real default method: `Mockito.delegateDefaultMethodsToReal(mockedInterface)`\r\n",
"I still suggest `stub` as the method name for that per previous reasons cited",
"Did a bit of archeology. #106 has a discussion both about the API and the naming.\r\n\r\nIn that thread I argued against `spy`: \"All the use cases I know of for partial mocking don't need spying\". \r\n\r\nAt the time \"stub\" wasn't suggested but now I think about it, it seems to make sense.\r\n\r\nAlthough, changing it may mean to introduce a new `@Stub` annotation, and deprecate `@Spy AbstractClass`, if we are willing to consider the ship not sailed yet.",
"Interesting discussion! Thank you for all suggestions.\r\n\r\n>the tests should not fail or should not be rewritten by replacing @Mock with @Spy or setting up special mocking settings like withSettings().useDefaultMethods().\r\n\r\nYou are right. Ideally the tests only fail when a bug is introduced.\r\n\r\nI have a feeling the discussion is getting broader and I am not sure if still discusses the issue reported :) My immediate reaction to new `@Stub` interface and potential deprecation of `@Spy` is -1 because I don't see clear value. However, please formulate a separate ticket with the use case, code samples, and the team will for sure review it!\r\n\r\nComing back to the original issue: relaxing spy annotation for interfaces is useful for spying on interfaces with default methods. The use case is reasonable and team is +1 to the change. Do we have new data / use cases that indicate that this change inappropriate?"
] | [
"Nice! Thank you for updating the test!",
"Nice and clean! Thank you!"
] | "2017-02-12T21:29:48Z" | [
"new feature",
"java-8",
"noteworthy",
"please contribute"
] | Allow spying on interfaces so that it is convenient to work with Java 8 default methods | ## Problem
While Mockito supports and stubs by default the _default methods_ in interfaces, the stubbing code can be a bit non intuitive, e.g.
``` java
interface DM {
int contract();
default int default_contract() { return contract() + 1; }
}
DM dm = mock(DM.class);
given(dm.contract()).willReturn(2);
// necessary otherwise default method is stubbed
given(dm.default_contract()).willCallRealMethod();
assertThat(dm.default_contract()).isEqualTo(3);
```
This behavior is unintuitive to users who expect the default methods to trigger real implementation (callRealMethod() by default). See also user report at #940.
## Suggested plan
:1st_place_medal: Contributions are welcome!
- [x] relax validation and allow interfaces to be spied. This way users can invoke spy(SomeInterface) or use @Spy with interfaces. This way, we don't need to mark default methods with "callRealMethod".
- [x] ensure test coverage for mocking
- interfaces with and without default methods
- concrete classes that extend interface with default methods (perhaps already covered)
- [x] document this use case. On main Mockito javadoc the use can search for "default" and find information about default methods behavior. Suggested by user at #940.
- [ ] create a separate ticket for Mockito 3 ("2.* incompatible" label) to discuss whether we should change the default behavior for defender/default methods. Perhaps they should automatically call real method regardless if someone uses spy() or mock() with the interface. Also we should consider mocking/spying on concrete classes that extend from interface with default methods.
## Discontinued ~~original plan~~
Below idea was discontinued:
Replace `DM` by `Map`, `default_contract()` by `getOrDefault()`, `contract()` by `get()` or `containsKey()` and you have a problem with designs that are used in the JDK itself.
I think mockito can improve on this by configuring the mock to invoke concrete default methods rather than stubbing them. This could be done the following way (_api naming in progress_) :
- `mock(DM.class, USE_DEFAULT_METHODS)`
The issue with that approach is that a default answer is mutually exclusive with other answers. e.g. if one wants to use `RETURNS_SMART_NULLS` and default methods this cannot work with the current design.
- `mock(DM.class, withSettings().useDefaultMethods())`
This approach is interesting as it allows to configure the behaviour with possibly any answer. However this may require some changes with our internal answers, not a deal breaker though.
| [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java"
] | [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java"
] | [
"src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java",
"src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java",
"src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java"
] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 8582cce078..35697eafd3 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -64,7 +64,7 @@
* <a href="#27">27. Delegate calls to real instance (Since 1.9.5)</a><br/>
* <a href="#28">28. <code>MockMaker</code> API (Since 1.9.5)</a><br/>
* <a href="#29">29. BDD style verification (Since 1.10.0)</a><br/>
- * <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12)</a><br/>
+ * <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12) and Java 8 default methods (Since release 2.x)</a><br/>
* <a href="#31">31. Mockito mocks can be <em>serialized</em> / <em>deserialized</em> across classloaders (Since 1.10.0)</a></h3><br/>
* <a href="#32">32. Better generic support with deep stubs (Since 1.10.0)</a></h3><br/>
* <a href="#32">33. Mockito JUnit rule (Since 1.10.17)</a><br/>
@@ -1008,7 +1008,7 @@
*
*
*
- * <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12)</a></h3>
+ * <h3 id="30">30. <a class="meaningful_link" href="#spying_abstract_classes" name="spying_abstract_classes">Spying or mocking abstract classes (Since 1.10.12) and Java 8 default methods (Since release 2.x)</a></h3>
*
* It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}).
* <p>
@@ -1021,6 +1021,9 @@
* //convenience API, new overloaded spy() method:
* SomeAbstract spy = spy(SomeAbstract.class);
*
+ * // Mocking abstract methods, spying default methods of an interface
+ * Function<Foo, Bar> function = spy(Function.class);
+ *
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
diff --git a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java
index b27307662c..6723be77f2 100644
--- a/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java
+++ b/src/main/java/org/mockito/internal/configuration/SpyAnnotationEngine.java
@@ -55,7 +55,6 @@ public void process(Class<?> context, Object testInstance) {
Object instance;
try {
instance = field.get(testInstance);
- assertNotInterface(instance, field.getType());
if (MockUtil.isMock(instance)) {
// instance has been spied earlier
// for example happens when MockitoAnnotations.initMocks is called two times.
@@ -72,14 +71,7 @@ public void process(Class<?> context, Object testInstance) {
}
}
- private static void assertNotInterface(Object testInstance, Class<?> type) {
- type = testInstance != null ? testInstance.getClass() : type;
- if (type.isInterface()) {
- throw new MockitoException("Type '" + type.getSimpleName() + "' is an interface and it cannot be spied on.");
- }
- }
-
- private Object spyInstance(Field field, Object instance) {
+ private static Object spyInstance(Field field, Object instance) {
return Mockito.mock(instance.getClass(),
withSettings().spiedInstance(instance)
.defaultAnswer(CALLS_REAL_METHODS)
@@ -142,9 +134,9 @@ private static boolean typeIsPrivateAbstractInnerClass(Class<?> type, int modifi
}
//TODO duplicated elsewhere
- private void assertNoIncompatibleAnnotations(Class<? extends Annotation> annotation,
- Field field,
- Class<? extends Annotation>... undesiredAnnotations) {
+ private static void assertNoIncompatibleAnnotations(Class<? extends Annotation> annotation,
+ Field field,
+ Class<? extends Annotation>... undesiredAnnotations) {
for (Class<? extends Annotation> u : undesiredAnnotations) {
if (field.isAnnotationPresent(u)) {
throw unsupportedCombinationOfAnnotations(annotation.getSimpleName(),
| diff --git a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java
index 157e08a65c..82c530b1f3 100644
--- a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java
+++ b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java
@@ -28,7 +28,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-@SuppressWarnings({"unchecked", "unused"})
+@SuppressWarnings("unused")
public class SpyAnnotationTest extends TestBase {
@Spy
@@ -59,19 +59,16 @@ public void should_init_spy_and_automatically_create_instance() throws Exception
}
@Test
- public void should_prevent_spying_on_interfaces() throws Exception {
+ public void should_allow_spying_on_interfaces() throws Exception {
class WithSpy {
@Spy
List<String> list;
}
WithSpy withSpy = new WithSpy();
- try {
- MockitoAnnotations.initMocks(withSpy);
- fail();
- } catch (MockitoException e) {
- assertThat(e.getMessage()).contains("is an interface and it cannot be spied on");
- }
+ MockitoAnnotations.initMocks(withSpy);
+ when(withSpy.list.size()).thenReturn(3);
+ assertEquals(3, withSpy.list.size());
}
@Test
diff --git a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
index 5f8595dbf7..ef0a646ec3 100644
--- a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
+++ b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
@@ -14,7 +14,6 @@
import static junit.framework.TestCase.fail;
-@SuppressWarnings({"unchecked", "unused"})
public class WrongSetOfAnnotationsTest extends TestBase {
@Test(expected=MockitoException.class)
@@ -25,19 +24,13 @@ public void should_not_allow_Mock_and_Spy() throws Exception {
}
@Test
- public void should_not_allow_Spy_and_or_InjectMocks_on_interfaces() throws Exception {
+ public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exception {
try {
MockitoAnnotations.initMocks(new Object() { @InjectMocks @Spy List<?> mock; });
fail();
} catch (MockitoException me) {
Assertions.assertThat(me.getMessage()).contains("'List' is an interface");
}
- try {
- MockitoAnnotations.initMocks(new Object() { @Spy List<?> mock; });
- fail();
- } catch (MockitoException me) {
- Assertions.assertThat(me.getMessage()).contains("'List' is an interface");
- }
}
@Test
diff --git a/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java b/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java
index 064cf7d2be..2295593e3f 100644
--- a/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java
+++ b/src/test/java/org/mockitousage/constructor/CreatingMocksWithConstructorTest.java
@@ -127,6 +127,13 @@ public void abstract_method_stubbed() {
assertEquals("abstract me", thing.fullName());
}
+ @Test
+ public void interface_method_stubbed() {
+ List<?> list = spy(List.class);
+ when(list.size()).thenReturn(12);
+ assertEquals(12, list.size());
+ }
+
@Test
public void calls_real_interface_method() {
List list = mock(List.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
| train | train | 2017-02-08T11:10:42 | "2016-10-07T09:29:53Z" | bric3 | train |
mockito/mockito/960_966 | mockito/mockito | mockito/mockito/960 | mockito/mockito/966 | [
"timestamp(timedelta=0.0, similarity=0.9276498021435603)",
"keyword_pr_to_issue"
] | a59cc571674ba23acedc47003a09d129603a98c6 | b413bbeee9f6dc4b61bee8fb394c0c376dc48075 | [] | [
"I'll also add : \r\n\r\n```\r\ncharset=utf-8\r\n```\r\n\r\n",
"I've met in some placed that option disabled for markdown files:\r\n\r\n```\r\n[*.md]\r\ntrim_trailing_whitespace = false\r\n```\r\n\r\nHowever, I'm not sure if it was a copy-paste from one source or there is a valid use case where new whitespace in a markdown files is required.",
"yup, for Eclipse guys on Windows.",
"We can always improve this file.\r\n\r\nRegarding the specific change for md files, I don't think trailing spaces should be an issue."
] | "2017-02-25T15:34:04Z" | [] | Add editor configuration to ease the process of adhering to Checkstyle | We recently added the enforcement of Checkstyle. @ChristianSchwarz requested in https://github.com/mockito/mockito/pull/908#issuecomment-281468837 to also include a default template or at least provide steps for developers to automatically adhere to the style guide. E.g. no manual labor required, the IDE fixes it for the contributor.
We can probably adopt [EditorConfig](http://editorconfig.org/) which is automatically supported by IntelliJ and there is a plugin available for Eclipse users. There is even [support by GitHub themselves](https://github.com/editorconfig/editorconfig.github.com/pull/48). | [
".github/CONTRIBUTING.md"
] | [
".editorconfig",
".github/CONTRIBUTING.md"
] | [] | diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000000..88fd9c2e0b
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,8 @@
+root = true
+
+[*]
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+indent_style = space
+indent_size = 4
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 13884c3a1e..f08d2c21b2 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -78,6 +78,10 @@ But first of all, make sure that :
* Line ending character is unix-style **`LF`**
* New line is added at end of file: `IntelliJ setting > Editor > General > Ensure line feed at file end on save`
+For most editors, this should be automatically enforced by [EditorConfig](http://editorconfig.org/).
+Check if your editor has a built-in plugin or if you need to download one.
+IntelliJ has a built-in plugin, for Eclipse you need to download [this plugin](https://github.com/ncjones/editorconfig-eclipse#readme).
+
### Imports
Imports must be sorted in the following order
| null | val | train | 2017-02-21T21:43:08 | "2017-02-21T20:27:00Z" | TimvdLippe | train |
mockito/mockito/982_983 | mockito/mockito | mockito/mockito/982 | mockito/mockito/983 | [
"timestamp(timedelta=0.0, similarity=0.9999999999999998)"
] | 64a1180ec625f9ef50fc35a8a6c1e80b6f665b04 | 723d341ed8fc5decb7c358e557c76852ff219441 | [
"That seems like a reasonable issue. Looking forward to your pull request @paulduffin !",
"Should I make the change in release/2.x?\n\nOn 8 March 2017 at 12:57, Tim van der Lippe <notifications@github.com>\nwrote:\n\n> That seems like a reasonable issue. Looking forward to your pull request\n> @paulduffin <https://github.com/paulduffin> !\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/mockito/mockito/issues/982#issuecomment-285033757>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AEtcQ-KnL90mWa9jxuLBhEsA8QmxpSJzks5rjqXXgaJpZM4MWrIj>\n> .\n>\n",
"Yes please :)",
"Done."
] | [] | "2017-03-08T16:38:10Z" | [
"bug",
"1.* incompatible"
] | Break cyclical compile time dependency on hideRecursiveCall | I am working on upgrading the version of mockito in AOSP to 2.7.13 using byte buddy and byte buddy android rather than dexmaker.
As part of that I need to exclude a number of classes which will not compile on Android because it does not support Java agents/instrumentation. The mockito code has always been very well organized and made that very simple to do but in the latest version I found a minor issue.
The files I need to exclude are:
- src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
- src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
- src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
Unfortunately, when I do that I get a compile error because MockMethodAdvice is trying to use hideRecursiveCall from InlineByteBuddyMockMaker. I looked at the code and it seems as though InlineByteBuddyMockMaker depends on InlineBytecodeGenerator which depends on MockMethodAdvice which depends on hideRecursiveCall from InlineByteBuddyMockMaker.
The only places that actually use hideRecursiveCall are MockMethodAdvice and InlineByteBuddyMockMakerTest. That depends on InlineByteBuddyMockMaker which depends on InlineBytecodeGenerator which depends on MockMethodAdvice which depends on hideRecursiveCall from InlineByteBuddyMockMaker.
So, moving hideRecursiveCall from InlineByteBuddyMockMaker to MockMethodAdvice breaks a dependency cycle and allows the InlineByteBuddyMockMaker.java file to be excluded without problem. Also, MockMethodAdvice seems to be a better place for it.
If you are happy with this proposal or can suggest a better place for hideRecursiveCall then I am happy to submit a fix for this. | [
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java",
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java"
] | [
"src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
index a98629564c..0258b67985 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMaker.java
@@ -311,23 +311,4 @@ public String nonMockableReason() {
};
}
- static Throwable hideRecursiveCall(Throwable throwable, int current, Class<?> targetType) {
- try {
- StackTraceElement[] stack = throwable.getStackTrace();
- int skip = 0;
- StackTraceElement next;
- do {
- next = stack[stack.length - current - ++skip];
- } while (!next.getClassName().equals(targetType.getName()));
- int top = stack.length - current - skip;
- StackTraceElement[] cleared = new StackTraceElement[stack.length - skip];
- System.arraycopy(stack, 0, cleared, 0, top);
- System.arraycopy(stack, top + skip, cleared, top, current);
- throwable.setStackTrace(cleared);
- return throwable;
- } catch (RuntimeException ignored) {
- // This should not happen unless someone instrumented or manipulated exception stack traces.
- return throwable;
- }
- }
}
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 394bd2d2eb..cef75c8830 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
@@ -23,8 +23,6 @@
import java.lang.reflect.Modifier;
import java.util.concurrent.Callable;
-import static org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.hideRecursiveCall;
-
public class MockMethodAdvice extends MockMethodDispatcher {
final WeakConcurrentMap<Object, MockMethodInterceptor> interceptors;
@@ -61,6 +59,26 @@ private static void exit(@Advice.Return(readOnly = false, typing = Assigner.Typi
}
}
+ static Throwable hideRecursiveCall(Throwable throwable, int current, Class<?> targetType) {
+ try {
+ StackTraceElement[] stack = throwable.getStackTrace();
+ int skip = 0;
+ StackTraceElement next;
+ do {
+ next = stack[stack.length - current - ++skip];
+ } while (!next.getClassName().equals(targetType.getName()));
+ int top = stack.length - current - skip;
+ StackTraceElement[] cleared = new StackTraceElement[stack.length - skip];
+ System.arraycopy(stack, 0, cleared, 0, top);
+ System.arraycopy(stack, top + skip, cleared, top, current);
+ throwable.setStackTrace(cleared);
+ return throwable;
+ } catch (RuntimeException ignored) {
+ // This should not happen unless someone instrumented or manipulated exception stack traces.
+ return throwable;
+ }
+ }
+
@Override
public Callable<?> handle(Object instance, Method origin, Object[] arguments) throws Throwable {
MockMethodInterceptor interceptor = interceptors.get(instance);
| 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 ee36f6de77..445c6f8905 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
@@ -158,7 +158,7 @@ public void should_remove_recursive_self_call_from_stack_trace() throws Exceptio
Throwable throwable = new Throwable();
throwable.setStackTrace(stack);
- throwable = InlineByteBuddyMockMaker.hideRecursiveCall(throwable, 2, SampleInterface.class);
+ throwable = MockMethodAdvice.hideRecursiveCall(throwable, 2, SampleInterface.class);
assertThat(throwable.getStackTrace()).isEqualTo(new StackTraceElement[]{
new StackTraceElement("foo", "", "", -1),
@@ -171,7 +171,7 @@ public void should_remove_recursive_self_call_from_stack_trace() throws Exceptio
public void should_handle_missing_or_inconsistent_stack_trace() throws Exception {
Throwable throwable = new Throwable();
throwable.setStackTrace(new StackTraceElement[0]);
- assertThat(InlineByteBuddyMockMaker.hideRecursiveCall(throwable, 0, SampleInterface.class)).isSameAs(throwable);
+ assertThat(MockMethodAdvice.hideRecursiveCall(throwable, 0, SampleInterface.class)).isSameAs(throwable);
}
@Test
| train | train | 2017-03-06T00:25:41 | "2017-03-08T11:30:26Z" | paulduffin | train |
mockito/mockito/981_985 | mockito/mockito | mockito/mockito/981 | mockito/mockito/985 | [
"timestamp(timedelta=0.0, similarity=0.931699655929002)"
] | 1599dfe84f953d5ef85c17471296fabbdd1b9a2b | d9a1e515f7d7ec1fd291292b3203995eafcf01a5 | [] | [] | "2017-03-10T09:54:11Z" | [
"please contribute"
] | Update documentation about mockito-inline artifact | Mockito documentation currently does not explain "mockito-inline" artifact that is used for inline mocking (mocking finals). The main Mockito class still contains information on how to configure the inline mocking using a classpath resource. | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 5e74aa7790..f886627f56 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -36,6 +36,7 @@
* <b>
* <a href="#0">0. Migrating to Mockito 2</a><br/>
* <a href="#0.1">0.1 Mockito Android support</a></br/>
+ * <a href="#0.2">0.2 Configuration-free inline mock making</a></br/>
* <a href="#1">1. Let's verify some behaviour! </a><br/>
* <a href="#2">2. How about some stubbing? </a><br/>
* <a href="#3">3. Argument matchers </a><br/>
@@ -110,6 +111,25 @@
* <a href="https://github.com/mockito/mockito/issues/new">on the official issue tracker</a>.
* Do provide the version of Android you are working on and dependencies of your project.
*
+ * <h3 id="0.2">0.2. <a class="meaningful_link" href="#mockito-inline" name="mockito-inline">Configuration-free inline mock making</a></h3>
+ *
+ * Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables <a href="#39">inline mock making</a> without configuring
+ * the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows:
+ *
+ * <pre class="code"><code>
+ * repositories {
+ * jcenter()
+ * }
+ * dependencies {
+ * testCompile "org.mockito:mockito-inline:+"
+ * }
+ * </code></pre>
+ *
+ * Be aware that this artifact may be abolished when the inline mock making feature is integrated into the default mock maker.
+ *
+ * <p>
+ * For more information about inline mock making, see <a href="#39">section 39</a>.
+ *
* <h3 id="1">1. <a class="meaningful_link" href="#verification" name="verification">Let's verify some behaviour!</a></h3>
*
* The following examples mock a List, because most people are familiar with the interface (such as the
| null | train | train | 2017-03-09T13:05:05 | "2017-03-07T13:46:15Z" | mockitoguy | train |
mockito/mockito/989_995 | mockito/mockito | mockito/mockito/989 | mockito/mockito/995 | [
"keyword_pr_to_issue"
] | 62a1d8828e7afb0f06dc6f4d135b54824d5eccf8 | 17db34508543150a70573fba3ca04bc4ba37a821 | [
"This was fixed in #989"
] | [
"Let's add a `@deprecated since 3.0.0` here, so we don't accidently remove it in the wrong version (which we did previously)",
"Since we deprecate the method anyways, is this test really required?",
"This still needs a `@since`",
"I would rather not name it with `2`. Probably better as `should_remove_all_interactions_verify_no_interactions()`",
"Same here",
"Same here",
"Same here",
"Same here",
"Same here",
"Same here",
"@ffissore We should avoid this catch block by calling `MockUtil.isMock(..)`"
] | "2017-03-21T08:43:15Z" | [
"2.* incompatible",
"feedback-needed"
] | Misleading behavior of Mockito.verifyZeroInteractions() | ## Problem
Mockito.verifyZeroInteractions() actually does not do what it advertises. The purpose of this ticket is to discuss whether to change the behavior of this method in Mockito 3.
## Details
Based on user feedback at #977, from @ffissore, "verifyZeroInteractions" API can be misleading. When you read that method in test code, you expect zero interactions with specified mocks. However, "verifyZeroInteractions" is only an alias to "verifyNoMoreInteractions" and in fact, it **does not** guarantee that there were zero interactions. Let's use examples to illustrate the problem
## Feedback needed
Please comment / vote / state your opinion about changing the behavior of "verifyZeroInteractions" so that it actually ensures that there were **zero** interactions with the mock (regardless if previously verified or not).
## Examples
Below examples illustrate current behavior of Mockito 2.x, in case you are puzzled what this ticket is about.
Example 1 - verifyNoMoreInteractions
```java
mock.foo();
verify(mock).foo();
verifyNoMoreInteractions(mock); //pretty clear I think
```
Example 2 - verifyZeroInteractions
```java
mock.foo();
verify(mock).foo();
verifyZeroInteractions(mock);
//above passes because verifyZeroInteractions == verifyNoMoreInteractions
//and we already have verified the only method invoked on the mock
```
Example 3 - verifyZeroInteractions with regular stubbing
```java
given(mock.foo()).willReturn("x");
assertEquals("x", mock.foo());
verify(mock).foo();
verifyZeroInteractions(mock);
//above passes because verifyZeroInteractions == verifyNoMoreInteractions
```
Example 4 - verifyZeroInteractions with new strict stubbing
```java
given(mock.foo()).willReturn("x");
assertEquals("x", mock.foo());
verifyZeroInteractions(mock);
//above passes because with strict stubbing
//stubbed method are implicitly verified when they are "used"
//this is one of key features of strict stubbing (DRY, don't repeat yourself)
``` | [
"src/main/java/org/mockito/BDDMockito.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/MockitoCore.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/verification/VerificationModeFactory.java"
] | [
"src/main/java/org/mockito/BDDMockito.java",
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/MockitoCore.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/verification/NoInteractions.java",
"src/main/java/org/mockito/internal/verification/VerificationModeFactory.java"
] | [
"src/test/java/org/mockito/MockitoTest.java",
"src/test/java/org/mockito/internal/InvalidStateDetectionTest.java",
"src/test/java/org/mockito/internal/verification/NoInteractionsTest.java",
"src/test/java/org/mockitousage/basicapi/ResetTest.java",
"src/test/java/org/mockitousage/customization/BDDMockitoTest.java",
"src/test/java/org/mockitousage/misuse/InvalidUsageTest.java",
"src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java",
"src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java",
"src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java",
"src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java",
"src/test/java/org/mockitousage/verification/VerificationOnMultipleMocksUsingMatchersTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java"
] | diff --git a/src/main/java/org/mockito/BDDMockito.java b/src/main/java/org/mockito/BDDMockito.java
index 9090fa891d..ef478a1082 100644
--- a/src/main/java/org/mockito/BDDMockito.java
+++ b/src/main/java/org/mockito/BDDMockito.java
@@ -259,6 +259,12 @@ public interface Then<T> {
* @since 2.1.0
*/
void shouldHaveNoMoreInteractions();
+
+ /**
+ * @see #verifyNoInteractions(Object...)
+ * @since 3.0.0
+ */
+ void shouldHaveNoInteractions();
}
private static class ThenImpl<T> implements Then<T> {
@@ -304,11 +310,21 @@ public T should(InOrder inOrder, VerificationMode mode) {
/**
* @see #verifyZeroInteractions(Object...)
* @since 2.1.0
+ * @deprecated Since 3.0.0. Please migrate your code to {@link #shouldHaveNoInteractions()}
*/
+ @Deprecated
public void shouldHaveZeroInteractions() {
verifyZeroInteractions(mock);
}
+ /**
+ * @see #verifyNoInteractions(Object...)
+ * @since 3.0.0
+ */
+ public void shouldHaveNoInteractions() {
+ verifyNoInteractions(mock);
+ }
+
/**
* @see #verifyNoMoreInteractions(Object...)
* @since 2.1.0
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 73ff1f2583..c469ac0f1f 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -2010,11 +2010,33 @@ public static void verifyNoMoreInteractions(Object... mocks) {
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
+ * @deprecated Since 3.0.0. Please migrate your code to {@link #verifyNoInteractions(Object...)}
*/
+ @Deprecated
public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
+ /**
+ * Verifies that no interactions happened on given mocks.
+ * <pre class="code"><code class="java">
+ * verifyNoInteractions(mockOne, mockTwo);
+ * </code></pre>
+ * This method will also detect invocations
+ * that occurred before the test method, for example: in <code>setUp()</code>, <code>@Before</code> method or in constructor.
+ * Consider writing nice code that makes interactions only in test methods.
+ * <p>
+ * See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @since 3.0.0
+ * @param mocks to be verified
+ */
+ public static void verifyNoInteractions(Object... mocks) {
+ MOCKITO_CORE.verifyNoInteractions(mocks);
+ }
+
/**
* Use <code>doThrow()</code> when you want to stub the void method with an exception.
* <p>
diff --git a/src/main/java/org/mockito/internal/MockitoCore.java b/src/main/java/org/mockito/internal/MockitoCore.java
index 791e0d1d64..ba93131f46 100644
--- a/src/main/java/org/mockito/internal/MockitoCore.java
+++ b/src/main/java/org/mockito/internal/MockitoCore.java
@@ -19,6 +19,7 @@
import static org.mockito.internal.util.MockUtil.isMock;
import static org.mockito.internal.util.MockUtil.resetMock;
import static org.mockito.internal.util.MockUtil.typeMockabilityOf;
+import static org.mockito.internal.verification.VerificationModeFactory.noInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions;
import java.util.Arrays;
@@ -137,6 +138,28 @@ public void verifyNoMoreInteractionsInOrder(List<Object> mocks, InOrderContext i
VerificationModeFactory.noMoreInteractions().verifyInOrder(data);
}
+ /**
+ * Verifies that given mocks have been invoked zero times, failing otherwise
+ *
+ * @since 3.0.0
+ * @param mocks the mocks to verify
+ */
+ public void verifyNoInteractions(Object... mocks) {
+ assertMocksNotEmpty(mocks);
+ mockingProgress().validateState();
+ for (Object mock : mocks) {
+ if (mock == null) {
+ throw nullPassedToVerifyNoMoreInteractions();
+ }
+ if (!isMock(mock)) {
+ throw notAMockPassedToVerifyNoMoreInteractions();
+ }
+ InvocationContainer invocations = getMockHandler(mock).getInvocationContainer();
+ VerificationDataImpl data = new VerificationDataImpl(invocations, null);
+ noInteractions().verify(data);
+ }
+ }
+
private void assertMocksNotEmpty(Object[] mocks) {
if (mocks == null || mocks.length == 0) {
throw mocksHaveToBePassedToVerifyNoMoreInteractions();
diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 7544557047..05db983691 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -185,7 +185,7 @@ public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() {
"Method requires argument(s)!",
"Pass mocks that should be verified, e.g:",
" verifyNoMoreInteractions(mockOne, mockTwo);",
- " verifyZeroInteractions(mockOne, mockTwo);",
+ " verifyNoInteractions(mockOne, mockTwo);",
""
));
}
@@ -195,7 +195,7 @@ public static MockitoException notAMockPassedToVerifyNoMoreInteractions() {
"Argument(s) passed is not a mock!",
"Examples of correct verifications:",
" verifyNoMoreInteractions(mockOne, mockTwo);",
- " verifyZeroInteractions(mockOne, mockTwo);",
+ " verifyNoInteractions(mockOne, mockTwo);",
""
));
}
@@ -205,7 +205,7 @@ public static MockitoException nullPassedToVerifyNoMoreInteractions() {
"Argument(s) passed is null!",
"Examples of correct verifications:",
" verifyNoMoreInteractions(mockOne, mockTwo);",
- " verifyZeroInteractions(mockOne, mockTwo);"
+ " verifyNoInteractions(mockOne, mockTwo);"
));
}
@@ -443,6 +443,23 @@ public static MockitoAssertionError noMoreInteractionsWanted(Invocation undesire
));
}
+ public static MockitoAssertionError noInteractionsWanted(Object mock, List<VerificationAwareInvocation> invocations) {
+ ScenarioPrinter scenarioPrinter = new ScenarioPrinter();
+ String scenario = scenarioPrinter.print(invocations);
+
+ List<Location> locations = new ArrayList<Location>();
+ for (VerificationAwareInvocation invocation : invocations) {
+ locations.add(invocation.getLocation());
+ }
+ return new NoInteractionsWanted(join(
+ "No interactions wanted here:",
+ new LocationImpl(),
+ "But found these interactions on mock '" + safelyGetMockName(mock) + "':",
+ join("", locations),
+ scenario
+ ));
+ }
+
public static MockitoAssertionError noMoreInteractionsWantedInOrder(Invocation undesired) {
return new VerificationInOrderFailure(join(
"No interactions wanted here:",
diff --git a/src/main/java/org/mockito/internal/verification/NoInteractions.java b/src/main/java/org/mockito/internal/verification/NoInteractions.java
new file mode 100644
index 0000000000..854a77c46d
--- /dev/null
+++ b/src/main/java/org/mockito/internal/verification/NoInteractions.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import java.util.List;
+
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.invocation.Invocation;
+import org.mockito.verification.VerificationMode;
+
+import static org.mockito.internal.exceptions.Reporter.noInteractionsWanted;
+
+public class NoInteractions implements VerificationMode {
+
+ @SuppressWarnings("unchecked")
+ public void verify(VerificationData data) {
+ List<Invocation> invocations = data.getAllInvocations();
+ if (!invocations.isEmpty()) {
+ throw noInteractionsWanted(invocations.get(0).getMock(), (List) invocations);
+ }
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
diff --git a/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java b/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java
index 1f8e8b6c25..9ba2499fbf 100644
--- a/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java
@@ -33,6 +33,10 @@ public static NoMoreInteractions noMoreInteractions() {
return new NoMoreInteractions();
}
+ public static NoInteractions noInteractions() {
+ return new NoInteractions();
+ }
+
public static VerificationMode atMost(int maxNumberOfInvocations) {
return new AtMost(maxNumberOfInvocations);
}
| diff --git a/src/test/java/org/mockito/MockitoTest.java b/src/test/java/org/mockito/MockitoTest.java
index 3b96aff3b0..c25be8d28f 100644
--- a/src/test/java/org/mockito/MockitoTest.java
+++ b/src/test/java/org/mockito/MockitoTest.java
@@ -12,6 +12,7 @@
import java.util.List;
import org.junit.Test;
import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockito.exceptions.misusing.NullInsteadOfMockException;
import org.mockito.internal.creation.MockSettingsImpl;
@SuppressWarnings("unchecked")
@@ -45,6 +46,16 @@ public void shouldValidateMockWhenVerifyingZeroInteractions() {
Mockito.verifyZeroInteractions("notMock");
}
+ @Test(expected=NotAMockException.class)
+ public void shouldValidateMockWhenVerifyingNoInteractions() {
+ Mockito.verifyNoInteractions("notMock");
+ }
+
+ @Test(expected=NullInsteadOfMockException.class)
+ public void shouldValidateNullMockWhenVerifyingNoInteractions() {
+ Mockito.verifyNoInteractions(new Object[] { null });
+ }
+
@Test(expected=NotAMockException.class)
public void shouldValidateMockWhenCreatingInOrderObject() {
Mockito.inOrder("notMock");
diff --git a/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java b/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java
index 850b9490d6..d326409b3f 100644
--- a/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java
+++ b/src/test/java/org/mockito/internal/InvalidStateDetectionTest.java
@@ -63,6 +63,9 @@ public void shouldDetectUnfinishedStubbing() {
when(mock.simpleMethod());
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedStubbingException.class);
+ when(mock.simpleMethod());
+ detectsAndCleansUp(new OnVerifyNoInteractions(), UnfinishedStubbingException.class);
+
when(mock.simpleMethod());
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedStubbingException.class);
@@ -87,6 +90,9 @@ public void shouldDetectUnfinishedDoAnswerStubbing() {
doAnswer(null);
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedStubbingException.class);
+ doAnswer(null);
+ detectsAndCleansUp(new OnVerifyNoInteractions(), UnfinishedStubbingException.class);
+
doAnswer(null);
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedStubbingException.class);
@@ -108,6 +114,9 @@ public void shouldDetectUnfinishedVerification() {
verify(mock);
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedVerificationException.class);
+ verify(mock);
+ detectsAndCleansUp(new OnVerifyNoInteractions(), UnfinishedVerificationException.class);
+
verify(mock);
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedVerificationException.class);
@@ -126,6 +135,9 @@ public void shouldDetectMisplacedArgumentMatcher() {
anyObject();
detectsAndCleansUp(new OnVerifyZeroInteractions(), InvalidUseOfMatchersException.class);
+ anyObject();
+ detectsAndCleansUp(new OnVerifyNoInteractions(), InvalidUseOfMatchersException.class);
+
anyObject();
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), InvalidUseOfMatchersException.class);
@@ -184,6 +196,12 @@ public void detect(IMethods mock) {
}
}
+ private static class OnVerifyNoInteractions implements DetectsInvalidState {
+ public void detect(IMethods mock) {
+ verifyNoInteractions(mock);
+ }
+ }
+
private static class OnVerifyNoMoreInteractions implements DetectsInvalidState {
public void detect(IMethods mock) {
verifyNoMoreInteractions(mock);
diff --git a/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java b/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java
new file mode 100644
index 0000000000..9d268d7156
--- /dev/null
+++ b/src/test/java/org/mockito/internal/verification/NoInteractionsTest.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import org.assertj.core.api.Assertions;
+import org.junit.Test;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
+import org.mockito.internal.creation.MockSettingsImpl;
+import org.mockito.internal.invocation.InvocationBuilder;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.stubbing.InvocationContainerImpl;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+import static junit.framework.TestCase.*;
+import static org.mockito.Mockito.mock;
+
+public class NoInteractionsTest extends TestBase {
+
+ @Test
+ public void noInteractionsExceptionMessageShouldDescribeMock() {
+ //given
+ NoInteractions n = new NoInteractions();
+ IMethods mock = mock(IMethods.class, "a mock");
+ InvocationMatcher i = new InvocationBuilder().mock(mock).toInvocationMatcher();
+
+ InvocationContainerImpl invocations =
+ new InvocationContainerImpl( new MockSettingsImpl());
+ invocations.setInvocationForPotentialStubbing(i);
+
+ try {
+ //when
+ n.verify(new VerificationDataImpl(invocations, null));
+ //then
+ fail();
+ } catch (NoInteractionsWanted e) {
+ Assertions.assertThat(e.toString()).contains(mock.toString());
+ }
+ }
+
+}
diff --git a/src/test/java/org/mockitousage/basicapi/ResetTest.java b/src/test/java/org/mockitousage/basicapi/ResetTest.java
index 5ec69cc64f..09f893e9ec 100644
--- a/src/test/java/org/mockitousage/basicapi/ResetTest.java
+++ b/src/test/java/org/mockitousage/basicapi/ResetTest.java
@@ -62,6 +62,13 @@ public void shouldRemoveAllInteractions() throws Exception {
verifyZeroInteractions(mock);
}
+ @Test
+ public void shouldRemoveAllInteractionsVerifyNoInteractions() throws Exception {
+ mock.simpleMethod(1);
+ reset(mock);
+ verifyNoInteractions(mock);
+ }
+
@Test
public void shouldRemoveStubbingToString() throws Exception {
IMethods mockTwo = mock(IMethods.class);
@@ -78,6 +85,14 @@ public void shouldStubbingNotBeTreatedAsInteraction() {
verifyZeroInteractions(mock);
}
+ @Test
+ public void shouldStubbingNotBeTreatedAsInteractionVerifyNoInteractions() {
+ when(mock.simpleMethod("one")).thenThrow(new RuntimeException());
+ doThrow(new RuntimeException()).when(mock).simpleMethod("two");
+ reset(mock);
+ verifyNoInteractions(mock);
+ }
+
@Test
public void shouldNotAffectMockName() {
IMethods mock = mock(IMethods.class, "mockie");
diff --git a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
index 6830765b23..bc3bfb6cbb 100644
--- a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
+++ b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java
@@ -268,6 +268,11 @@ public void should_validate_that_mock_did_not_have_any_interactions() {
then(mock).shouldHaveZeroInteractions();
}
+ @Test
+ public void should_validate_that_mock_had_no_interactions() {
+ then(mock).shouldHaveNoInteractions();
+ }
+
@Test
public void should_fail_when_mock_had_unwanted_interactions() {
mock.booleanObjectReturningMethod();
diff --git a/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java b/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java
index 1ba6e99e1f..c2342d7a3c 100644
--- a/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java
+++ b/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java
@@ -37,6 +37,11 @@ public void shouldRequireArgumentsWhenVerifyingZeroInteractions() {
verifyZeroInteractions();
}
+ @Test(expected=MockitoException.class)
+ public void shouldRequireArgumentsWhenVerifyingNoInteractions() {
+ verifyNoInteractions();
+ }
+
@Test(expected=MockitoException.class)
public void shouldNotCreateInOrderObjectWithoutMocks() {
inOrder();
@@ -104,6 +109,18 @@ public void shouldNotMockObjectMethodsOnInterface() throws Exception {
verifyZeroInteractions(inter);
}
+ @Test
+ public void shouldNotMockObjectMethodsOnInterfaceVerifyNoInteractions() throws Exception {
+ ObjectLikeInterface inter = mock(ObjectLikeInterface.class);
+
+ inter.equals(null);
+ inter.toString();
+ inter.hashCode();
+
+ verifyNoInteractions(inter);
+ }
+
+ @Test
public void shouldNotMockObjectMethodsOnClass() throws Exception {
Object clazz = mock(ObjectLikeInterface.class);
@@ -113,4 +130,15 @@ public void shouldNotMockObjectMethodsOnClass() throws Exception {
verifyZeroInteractions(clazz);
}
+
+ @Test
+ public void shouldNotMockObjectMethodsOnClassVerifyNoInteractions() throws Exception {
+ Object clazz = mock(ObjectLikeInterface.class);
+
+ clazz.equals(null);
+ clazz.toString();
+ clazz.hashCode();
+
+ verifyNoInteractions(clazz);
+ }
}
diff --git a/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java b/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java
index 8ad5ae0ead..2da4492d2b 100644
--- a/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/StackTraceFilteringTest.java
@@ -19,11 +19,7 @@
import org.mockitoutil.TestBase;
import static junit.framework.TestCase.fail;
-import static org.mockito.Mockito.inOrder;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.*;
import static org.mockitoutil.Conditions.firstMethodInStackTrace;
public class StackTraceFilteringTest extends TestBase {
@@ -72,6 +68,17 @@ public void shouldFilterStackTraceOnVerifyZeroInteractions() {
}
}
+ @Test
+ public void shouldFilterStackTraceOnVerifyNoInteractions() {
+ mock.oneArg(true);
+ try {
+ verifyNoInteractions(mock);
+ fail();
+ } catch (NoInteractionsWanted e) {
+ Assertions.assertThat(e).has(firstMethodInStackTrace("shouldFilterStackTraceOnVerifyNoInteractions"));
+ }
+ }
+
@Test
public void shouldFilterStacktraceOnMockitoException() {
verify(mock);
diff --git a/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java b/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java
index faf250d76f..688b12a4a8 100644
--- a/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/BasicStubbingTest.java
@@ -66,6 +66,14 @@ public void should_stubbing_not_be_treated_as_interaction() {
verifyZeroInteractions(mock);
}
+ @Test
+ public void should_stubbing_not_be_treated_as_interaction_verify_no_interactions() {
+ when(mock.simpleMethod("one")).thenThrow(new RuntimeException());
+ doThrow(new RuntimeException()).when(mock).simpleMethod("two");
+
+ verifyNoInteractions(mock);
+ }
+
@Test
public void unfinished_stubbing_cleans_up_the_state() {
reset(mock);
@@ -78,6 +86,18 @@ public void unfinished_stubbing_cleans_up_the_state() {
verifyZeroInteractions(mock);
}
+ @Test
+ public void unfinished_stubbing_cleans_up_the_state_verify_no_interactions() {
+ reset(mock);
+ try {
+ when("").thenReturn("");
+ fail();
+ } catch (MissingMethodInvocationException e) {}
+
+ //anything that can cause state validation
+ verifyNoInteractions(mock);
+ }
+
@Test
public void should_to_string_mock_name() {
IMethods mock = mock(IMethods.class, "mockie");
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
index 0ccf14f268..b6516048e4 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
@@ -212,7 +212,7 @@ public void shouldStubbingWithThrowableFailVerification() {
when(mock.size()).thenThrow(new RuntimeException());
doThrow(new RuntimeException()).when(mock).clone();
- verifyZeroInteractions(mock);
+ verifyNoInteractions(mock);
mock.add("test");
diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
index 4268b591ce..d94794e1e8 100644
--- a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
+++ b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
@@ -264,6 +264,11 @@ public void shouldFailOnVerifyZeroInteractions() {
verifyZeroInteractions(mockOne);
}
+ @Test(expected = NoInteractionsWanted.class)
+ public void shouldFailOnVerifyNoInteractions() {
+ verifyNoInteractions(mockOne);
+ }
+
@SuppressWarnings("all")
@Test(expected = MockitoException.class)
public void shouldScreamWhenNullPassed() {
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 72cd98d778..c81f97a66c 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -210,6 +210,33 @@ public void should_print_first_unexpected_invocation_when_verifying_zero_interac
}
}
+ @Test
+ public void should_print_first_unexpected_invocation_when_verifying_no_interactions() {
+ mock.twoArgumentMethod(1, 2);
+ mock.threeArgumentMethod(1, "2", "3");
+
+ try {
+ verifyNoInteractions(mock);
+ fail();
+ } catch (NoInteractionsWanted e) {
+ String expected =
+ "\n" +
+ "No interactions wanted here:" +
+ "\n" +
+ "-> at";
+
+ assertThat(e).hasMessageContaining(expected);
+
+ String expectedCause =
+ "\n" +
+ "But found these interactions on mock '" + mock + "':" +
+ "\n" +
+ "-> at";
+
+ assertThat(e).hasMessageContaining(expectedCause);
+ }
+ }
+
@Test
public void should_print_method_name_when_verifying_at_least_once() throws Exception {
try {
diff --git a/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java b/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java
index 6382df3a6c..04aef9a408 100644
--- a/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java
+++ b/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java
@@ -58,6 +58,9 @@ public void shouldVerifyNoInteractionsAsManyTimesAsYouWant() throws Exception {
verifyZeroInteractions(mock);
verifyZeroInteractions(mock);
+
+ verifyNoInteractions(mock);
+ verifyNoInteractions(mock);
}
@Test
@@ -70,6 +73,16 @@ public void shouldFailZeroInteractionsVerification() throws Exception {
} catch (NoInteractionsWanted e) {}
}
+ @Test
+ public void shouldFailNoInteractionsVerification() throws Exception {
+ mock.clear();
+
+ try {
+ verifyNoInteractions(mock);
+ fail();
+ } catch (NoInteractionsWanted e) {}
+ }
+
@Test
public void shouldFailNoMoreInteractionsVerification() throws Exception {
mock.clear();
@@ -126,6 +139,25 @@ public void shouldVerifyOneMockButFailOnOther() throws Exception {
} catch (NoInteractionsWanted e) {}
}
+ @Test
+ public void shouldVerifyOneMockButFailOnOtherVerifyNoInteractions() throws Exception {
+ List<String> list = mock(List.class);
+ Map<String, Integer> map = mock(Map.class);
+
+ list.add("one");
+ list.add("one");
+
+ map.put("one", 1);
+
+ verify(list, times(2)).add("one");
+
+ verifyNoMoreInteractions(list);
+ try {
+ verifyNoInteractions(map);
+ fail();
+ } catch (NoInteractionsWanted e) {}
+ }
+
@SuppressWarnings("all")
@Test(expected=MockitoException.class)
public void verifyNoMoreInteractionsShouldScreamWhenNullPassed() throws Exception {
diff --git a/src/test/java/org/mockitousage/verification/VerificationOnMultipleMocksUsingMatchersTest.java b/src/test/java/org/mockitousage/verification/VerificationOnMultipleMocksUsingMatchersTest.java
index 45bf19d4ff..5a6610aae9 100644
--- a/src/test/java/org/mockitousage/verification/VerificationOnMultipleMocksUsingMatchersTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationOnMultipleMocksUsingMatchersTest.java
@@ -60,5 +60,6 @@ public void shouldVerifyMultipleMocks() throws Exception {
verifyNoMoreInteractions(list, map);
verifyZeroInteractions(set);
+ verifyNoInteractions(set);
}
}
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java
index e9dd50a83a..55fef7adbf 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java
@@ -2,6 +2,7 @@
import org.testng.annotations.Test;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
public class ResetMocksInParentTestClassTooTest extends ParentTest {
@@ -15,4 +16,9 @@ public void interact_with_parent_mock() throws Exception {
public void verify__zero_interaction_with_parent_mock() throws Exception {
verifyZeroInteractions(parentMockField);
}
+
+ @Test
+ public void verify__no_interaction_with_parent_mock() throws Exception {
+ verifyNoInteractions(parentMockField);
+ }
}
| val | train | 2017-03-26T19:46:52 | "2017-03-16T04:44:21Z" | mockitoguy | train |
mockito/mockito/1059_1062 | mockito/mockito | mockito/mockito/1059 | mockito/mockito/1062 | [
"keyword_pr_to_issue"
] | 802a43e78a9e9aff45bdd7362d3fdc0c22616dd6 | e34fe9279057dbc11f05fa70a3422475e12c8914 | [
"Waiting for review / merge: https://github.com/mockito/mockito-release-tools/pull/103",
"Fix seems fine to me. Have not executed it locally though.",
"I don't know if this is related, but the release process currently [fails](https://travis-ci.org/mockito/mockito/jobs/230865593#L796) with:\r\n> remote: Invalid username or password.\r\n\r\non a git push.",
"It is sadly unrelated. It seems that @szczepiq password was reset for some reason :sob: ",
"There is something weird going on with GitHub auth tokens. They seem to be expiring or something. I've tested locally a new token, updated Travis configuration and restarted Travis Job. We'll see if it helps.",
"It was fixed!"
] | [] | "2017-05-01T01:17:25Z" | [
"continuous integration"
] | Release automation endless loop issue | Recently I introduced a problem (PR: https://github.com/mockito/mockito/pull/1057) that created endless loop with our releases. Fallout / clean up needed:
- [x] - stop the endless loop by reverting the commit. Thank you @TimvdLippe spotting the issue and reverting the change!
- [x] - remove unnecessary tags
- [x] - discard versions/artifacts that were pushed to Bintray (not "published" yet, safe to delete)
- [x] - delete unnecessary content from [release notes file](https://github.com/mockito/mockito/blob/release/2.x/doc/release-notes/official.md)
- [x] - fix the bug in release automation code, pr submitted, waiting for review & merge: https://github.com/mockito/mockito-release-tools/pull/103
- [x] - test & reapply PR #1057 | [
"gradle.properties"
] | [
"gradle.properties"
] | [] | diff --git a/gradle.properties b/gradle.properties
index efadf69c1a..6d27b51dde 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -2,4 +2,4 @@ org.gradle.daemon=true
org.gradle.parallel=true
#Declared the dependency here to avoid duplication across build.gradle files
-dependencies.mockito-release-tools=gradle.plugin.org.mockito:mockito-release-tools:0.8.0
+dependencies.mockito-release-tools=gradle.plugin.org.mockito:mockito-release-tools:0.8.1
| null | train | train | 2017-05-01T03:30:23 | "2017-04-30T17:50:35Z" | mockitoguy | train |
mockito/mockito/1071_1076 | mockito/mockito | mockito/mockito/1071 | mockito/mockito/1076 | [
"keyword_pr_to_issue"
] | a8d1f37ec282294dd7ec18028f679b958c2f78ea | 761de40d05b4eddae8328ab1d7e5bdacd882a3be | [
"@troig Mockito checks if the argument type is compatible with the return type to make a misuse ot the API as soon as posible visible. In this case the argument-type Object is inferred from the generic type T, due to type erasure. Since Object is not a subtype of String Mockito throws the exception you see.\r\n\r\nSolution: The issue can by fixed by inferring the argument-type of the actual argument-instance.\r\n In case the argument-type is a primitive or the arg is null Mockito must fallback and use the type provided by method signature. \r\n\r\nI have a solution ~~that currently doesn't work due to regressions introduced with #1032 (vararg-expansion is broken)~~.\r\n",
"Thanks @ChristianSchwarz for you quick answer!"
] | [] | "2017-05-10T11:47:32Z" | [] | Mockito AdditionalAnswers.returnsFirstArg() doesn't work with generic first arg | _Issue concerning [this stackoverflow question](http://stackoverflow.com/questions/30670275/mockito-returnsfirstarg-doesnt-work-with-generic-first-arg).
I've checked it's not working both Mockito 1.x and 2.x._
-------------------
I'm trying to mock the typed method `getNameElement` of Interface `RoomGeneralService` to return the first arg, using Mockito `AdditionalAnswers.returnsFirstArg` functionality:
**Interface to mock**:
interface PrimaryKeyElement<T> {
public String getNameElement(T primaryKey);
}
interface RoomGeneralService extends PrimaryKeyElement<String> {
// ...
}
**My test** (note the imports)
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class SampleTest {
@Mock
RoomGeneralService roomGeneralService;
@Test
public void testFoo() throws Exception {
when(roomGeneralService.getNameElement(anyString())).thenAnswer(returnsFirstArg());
//...
}
}
Also I've tried with other combinations, but without success so far:
when(roomGeneralService.getNameElement(Matchers.<String>any())).thenAnswer(returnsFirstArg());
doAnswer(returnsFirstArg()).when(roomGeneralService.getNameElement(anyString()));
doReturn(returnsFirstArg()).when(roomGeneralService.getNameElement(anyString()));
**Error received**:
> The reason for this error can be :
> 1. The wanted argument position is incorrect.
> 2. The answer is used on the wrong interaction.
>
> Position of the wanted argument is 0 and the possible argument indexes
> for this method are :
> [0] Object
**Workaround**:
I know I can create my own answer, and in fact it's working fine if instead of use `returnFirstArg()` I do something like this:
when(roomGeneralService.getNameElement(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return (String) invocation.getArguments()[0];
}
});
But I would use `returnFirstArg()` as in the rest of my tests (tests look cleaner), as well as mocking is working fine if the method `getNameElement` would receive an `String` instead a `T` arg.
Thanks for the help. | [
"src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java"
] | [
"src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java"
] | [
"src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java",
"src/test/java/org/mockitousage/IMethods.java",
"src/test/java/org/mockitousage/MethodsImpl.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
index 7c0a144b71..5419819647 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
@@ -4,9 +4,12 @@
*/
package org.mockito.internal.stubbing.answers;
+import static org.mockito.internal.exceptions.Reporter.invalidArgumentPositionRangeAtInvocationTime;
+import static org.mockito.internal.exceptions.Reporter.invalidArgumentRangeAtIdentityAnswerCreationTime;
+import static org.mockito.internal.exceptions.Reporter.wrongTypeOfArgumentToReturn;
+
import java.io.Serializable;
import java.lang.reflect.Method;
-import org.mockito.internal.exceptions.Reporter;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -15,8 +18,12 @@
/**
* Returns the passed parameter identity at specified index.
* <p>
- * <p>The <code>argumentIndex</code> represents the index in the argument array of the invocation.</p>
- * <p>If this number equals -1 then the last argument is returned.</p>
+ * <p>
+ * The <code>argumentIndex</code> represents the index in the argument array of the invocation.
+ * </p>
+ * <p>
+ * If this number equals -1 then the last argument is returned.
+ * </p>
*
* @see org.mockito.AdditionalAnswers
* @since 1.9.5
@@ -32,12 +39,12 @@ public class ReturnsArgumentAt implements Answer<Object>, ValidableAnswer, Seria
/**
* Build the identity answer to return the argument at the given position in the argument array.
*
- * @param wantedArgumentPosition The position of the argument identity to return in the invocation.
- * Using <code>-1</code> indicates the last argument ({@link #LAST_ARGUMENT}).
+ * @param wantedArgumentPosition
+ * The position of the argument identity to return in the invocation. Using <code>-1</code> indicates the last argument ({@link #LAST_ARGUMENT}).
*/
public ReturnsArgumentAt(int wantedArgumentPosition) {
if (wantedArgumentPosition != LAST_ARGUMENT && wantedArgumentPosition < 0) {
- throw Reporter.invalidArgumentRangeAtIdentityAnswerCreationTime();
+ throw invalidArgumentRangeAtIdentityAnswerCreationTime();
}
this.wantedArgumentPosition = wantedArgumentPosition;
}
@@ -50,49 +57,53 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentPosition)) {
// answer raw vararg array argument
return ((Invocation) invocation).getRawArguments()[argumentPosition];
- } else {
- // answer expanded argument at wanted position
- return invocation.getArgument(argumentPosition);
}
+
+ // answer expanded argument at wanted position
+ return invocation.getArgument(argumentPosition);
+
}
@Override
public void validateFor(InvocationOnMock invocation) {
int argumentPosition = inferWantedArgumentPosition(invocation);
validateIndexWithinInvocationRange(invocation, argumentPosition);
- validateArgumentTypeCompatibility(invocation, argumentPosition);
+ validateArgumentTypeCompatibility((Invocation) invocation, argumentPosition);
}
private int inferWantedArgumentPosition(InvocationOnMock invocation) {
- return wantedArgumentPosition == LAST_ARGUMENT ?
- invocation.getArguments().length - 1 :
- wantedArgumentPosition;
+ if (wantedArgumentPosition == LAST_ARGUMENT)
+ return invocation.getArguments().length - 1;
+
+ return wantedArgumentPosition;
}
private void validateIndexWithinInvocationRange(InvocationOnMock invocation, int argumentPosition) {
if (!wantedArgumentPositionIsValidForInvocation(invocation, argumentPosition)) {
- throw Reporter.invalidArgumentPositionRangeAtInvocationTime(invocation,
- wantedArgumentPosition == LAST_ARGUMENT,
- wantedArgumentPosition);
+ throw invalidArgumentPositionRangeAtInvocationTime(invocation,
+ wantedArgumentPosition == LAST_ARGUMENT,
+ wantedArgumentPosition);
}
}
- private void validateArgumentTypeCompatibility(InvocationOnMock invocation, int argumentPosition) {
+ private void validateArgumentTypeCompatibility(Invocation invocation, int argumentPosition) {
InvocationInfo invocationInfo = new InvocationInfo(invocation);
- Class<?> inferredArgumentType = inferWantedArgumentType(invocation, argumentPosition);
- if (!invocationInfo.isValidReturnType(inferredArgumentType)) {
- throw Reporter.wrongTypeOfArgumentToReturn(invocation,
- invocationInfo.printMethodReturnType(),
- inferredArgumentType,
- wantedArgumentPosition);
+
+ Class<?> inferredArgumentType = inferArgumentType(invocation, argumentPosition);
+
+ if (!invocationInfo.isValidReturnType(inferredArgumentType)){
+ throw wrongTypeOfArgumentToReturn(invocation,
+ invocationInfo.printMethodReturnType(),
+ inferredArgumentType,
+ wantedArgumentPosition);
}
}
private boolean wantedArgIndexIsVarargAndSameTypeAsReturnType(Method method, int argumentPosition) {
Class<?>[] parameterTypes = method.getParameterTypes();
- return method.isVarArgs()
- && argumentPosition == /* vararg index */ parameterTypes.length - 1
- && method.getReturnType().isAssignableFrom(parameterTypes[argumentPosition]);
+ return method.isVarArgs() &&
+ argumentPosition == /* vararg index */ parameterTypes.length - 1 &&
+ method.getReturnType().isAssignableFrom(parameterTypes[argumentPosition]);
}
private boolean wantedArgumentPositionIsValidForInvocation(InvocationOnMock invocation, int argumentPosition) {
@@ -106,29 +117,37 @@ private boolean wantedArgumentPositionIsValidForInvocation(InvocationOnMock invo
return true;
}
- private Class<?> inferWantedArgumentType(InvocationOnMock invocation, int argumentPosition) {
+ private Class<?> inferArgumentType(Invocation invocation, int argumentIndex) {
Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
+
// Easy when the method is not a vararg
if (!invocation.getMethod().isVarArgs()) {
- return parameterTypes[argumentPosition];
+ Class<?> argumentType = parameterTypes[argumentIndex];
+ Object argumentValue = invocation.getArgument(argumentIndex);
+ // we don't want to return primitive wrapper types
+ if (argumentType.isPrimitive() || argumentValue == null) {
+ return argumentType;
+ }
+
+ return argumentValue.getClass();
}
// Now for varargs
int varargIndex = parameterTypes.length - 1; // vararg always last
- if (argumentPosition < varargIndex) {
+ if (argumentIndex < varargIndex) {
// Same for non vararg arguments
- return parameterTypes[argumentPosition];
- } else {
- // if wanted argument is vararg
- if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentPosition)) {
- // return the vararg array if return type is compatible
- // because the user probably want to return the array itself if the return type is compatible
- return parameterTypes[argumentPosition]; // move to MethodInfo ?
- } else {
- // return the type in this vararg array
- return parameterTypes[varargIndex].getComponentType();
- }
+ return parameterTypes[argumentIndex];
}
+ // if wanted argument is vararg
+ if (wantedArgIndexIsVarargAndSameTypeAsReturnType(invocation.getMethod(), argumentIndex)) {
+ // return the vararg array if return type is compatible
+ // because the user probably want to return the array itself if the return type is compatible
+ return parameterTypes[argumentIndex]; // move to MethodInfo ?
+ }
+ // return the type in this vararg array
+ return parameterTypes[varargIndex].getComponentType();
+
}
}
+
| diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
index 8bb0451e0c..3a817cb5a1 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsArgumentAtTest.java
@@ -185,6 +185,17 @@ public void should_fail_if_argument_type_of_signature_is_incompatible_with_retur
}
}
+ @Test
+ public void shouldNotFailWhenArgumentIsGenericAndCompatibleWithReturnType() throws Exception {
+ new ReturnsArgumentAt(0 ).validateFor(
+ new InvocationBuilder().method("genericToString")
+ .argTypes(Object.class)
+ .args("anyString")
+ .toInvocation()
+ );
+ }
+
+
private static InvocationOnMock invocationWith(Object... parameters) {
return new InvocationBuilder().method("varargsReturningString")
.argTypes(Object[].class)
diff --git a/src/test/java/org/mockitousage/IMethods.java b/src/test/java/org/mockitousage/IMethods.java
index 2d5663115c..7ec37500d9 100644
--- a/src/test/java/org/mockitousage/IMethods.java
+++ b/src/test/java/org/mockitousage/IMethods.java
@@ -233,4 +233,6 @@ public interface IMethods {
Integer toIntWrapper(int i);
String forObject(Object object);
+
+ <T> String genericToString(T arg);
}
diff --git a/src/test/java/org/mockitousage/MethodsImpl.java b/src/test/java/org/mockitousage/MethodsImpl.java
index b9830579e7..9417cbebe5 100644
--- a/src/test/java/org/mockitousage/MethodsImpl.java
+++ b/src/test/java/org/mockitousage/MethodsImpl.java
@@ -451,4 +451,9 @@ public String forObject(Object object) {
public Void voidReturningMethod() {
return null;
}
+
+ @Override
+ public <T> String genericToString(T arg) {
+ return null;
+ }
}
| val | train | 2017-05-06T14:48:08 | "2017-05-05T13:31:05Z" | troig | train |
mockito/mockito/1088_1091 | mockito/mockito | mockito/mockito/1088 | mockito/mockito/1091 | [
"keyword_pr_to_issue"
] | db7dbc3d5f7d97d0625683b4e41f282818f9b87c | bbceeb3d8d57c30ff47231e26310802ab7fb4a2c | [
"What would you consider to be the correct behaviour here? At a push I might propose a slight change in naming to \"TooFewActualInvocations\" but the core behaviour is the same.\r\n\r\nYour example is confusing because your \"atLeast(2)\" verification is on .add(\"five times\"), which suggests five invocations of add() with that String, but there are no invocations with that String.\r\n\r\nWhat do you expect to see here?",
"I think the expectation is that the code works when it is copy pasted to IDE and executed. Why don't we fix it by changing \"five times\" to \"three times\"? Do you want to contribute? Please do! :)",
"Oh wait, I see now. It's a problem with [the documentation](http://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/Mockito.html#4). Sure thing, I can update that no problem.",
"Thanks folks. "
] | [] | "2017-05-26T07:51:19Z" | [
"docs",
"please contribute"
] | Javadoc Example Throws Unexpected Exception | Verify(mockedList, atLeast(2)).add("five times"); - would throw
org.mockito.exceptions.verification.TooLittleActualInvocations
Correcting this would help to make sure new devs are not confused by the verify use case there.
<img width="678" alt="screen shot 2017-05-17 at 8 40 03 pm" src="https://cloud.githubusercontent.com/assets/10499046/26181818/2241904c-3b41-11e7-8f71-6974d46d5579.png">
| [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index cd4955a63d..8f389455cf 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -293,7 +293,7 @@
*
* //verification using atLeast()/atMost()
* verify(mockedList, atLeastOnce()).add("three times");
- * verify(mockedList, atLeast(2)).add("five times");
+ * verify(mockedList, atLeast(2)).add("three times");
* verify(mockedList, atMost(5)).add("three times");
*
* </code></pre>
| null | val | train | 2017-05-23T00:44:49 | "2017-05-18T00:46:16Z" | Abasifreke | train |
mockito/mockito/1107_1109 | mockito/mockito | mockito/mockito/1107 | mockito/mockito/1109 | [
"keyword_pr_to_issue"
] | dc554a084c55d5f6249d2e8069626268771d818d | f4a00def6ebd825454939e47602776725d0faa6a | [
"No, I haven't seen anything like that before. There were no changes in .travis.yml and I have no idea what one of the jobs is missing. Probably (I hope) it will be automatically fixed by the next commit. It may be good to report it to Travis.",
"Just merged another PR, will see how many child jobs Travis triggers this time :)",
"Another instance of this problem. I've contacted Travis CI support, put you guys on cc.",
"Commented on the ticket in Travis issue tracker (https://github.com/travis-ci/travis-ci/issues/4681#issuecomment-306102865). Here's the message from Travis CI support:\r\n\r\n```\r\nThanks for reaching out and I'm sorry for this change in behavior.\r\n\r\nThis is the result of a change we released 3 days ago and it's detailed here: https://github.com/travis-ci/travis-ci/issues/4681. In brief, if you have no matrix expansion on the top level, and there is at least one job defined in `matrix.include`, the top level job is no longer included in the build matrix.\r\n\r\nYou should be able to get your old build configuration back by adding the following under `matrix.include`:\r\n\r\n\r\nmatrix:\r\n include:\r\n - jdk: oraclejdk7\r\n - jdk: oraclejdk7\r\n env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline\r\n ⋮\r\n```\r\n\r\nI'm trying it now ;)"
] | [] | "2017-06-05T04:58:17Z" | [
"bug",
"continuous integration"
] | No release build for 2.8.39 - possible bug in Travis CI | For some reason, Travis CI did not trigger the main build for version 2.8.39. In the travis dashboard for that build I can see only [3 child jobs](https://travis-ci.org/mockito/mockito/builds/237813636) whereas normally there are [4 child jobs](https://travis-ci.org/mockito/mockito/builds/237433149).
@szpak, have you seen something like that before? I'm restarting the build, let's see what happens :) | [
".travis.yml"
] | [
".travis.yml"
] | [] | diff --git a/.travis.yml b/.travis.yml
index 7f4507d163..88d3f36acf 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -25,11 +25,9 @@ before_install:
- export TRAVIS_COMMIT_MESSAGE=$(git log --format=%B -n 1 $TRAVIS_COMMIT)
- echo "$TRAVIS_COMMIT_MESSAGE"
-jdk:
- - oraclejdk7
-
matrix:
include:
+ - jdk: oraclejdk7
- jdk: oraclejdk7
env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline
- jdk: oraclejdk8
| null | train | train | 2017-06-02T15:06:14 | "2017-06-01T17:03:21Z" | mockitoguy | train |
mockito/mockito/1117_1122 | mockito/mockito | mockito/mockito/1117 | mockito/mockito/1122 | [
"timestamp(timedelta=1.0, similarity=0.8727445117873299)"
] | 3cf29be1d7cbf701ed4fac7ccb4ccf914cad7d8a | 04961ae3cc8093916f563d7edc223224d757a4a1 | [
"If the implementation is clean and generic, I would be in favor of it",
"@szpak For what version is that feature planned (Or has it been already released)?"
] | [] | "2017-06-12T22:22:38Z" | [
"new feature",
"noteworthy"
] | Answer with delay in mock or spy to improve testing of asynchronous code | I'm currently using Mockito for component testing of microservices. All code should be run, up to the boundary at which another microservice is called. In the component test, the mocks return very quickly, but obviously in integration testing, the real calls return much more slowly. Some threading problems are revealed by the slow returns that would have been revealed in the component test if the returns could be forced to come back more slowly. Since integration tests are *painfully* slow to start, this would save me, the developer, considerable time in debugging this kind of issue once I discover it in the integration tests.
Because it's so easy to write, I've already solved it with a class called AnswerWithDelay. It takes another answer as a parameter, and inserts a little sleep before it returns.
If desired, I can turn this little helper into a PR for mockito. Or perhaps there's already something there that does this, that I've overlooked.
Best Regards,
Myrle
```
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
classes = {AbstractRhythmTest.TestConfiguration.class},
properties = {"rhythm.user=homer", "rhythm.beatCheckRate=500"}
)
public class AbstractRhythmTest {
//...
static class AnswerWithDelay<T> implements Answer<T> {
private final int sleepyTime;
private final Answer<T> answer;
AnswerWithDelay(final int sleepyTime, final Answer<T> answer) {
this.sleepyTime = sleepyTime;
this.answer = answer;
}
@Override
public T answer(final InvocationOnMock invocation) throws Throwable {
TimeUnit.MILLISECONDS.sleep(sleepyTime);
return answer.answer(invocation);
}
}
Beat createBeat(
final String applicationIdentifier,
final String beatIdentifier,
final int alignmentHour,
final LocalDateTime expectedBeatTimestamp) throws InterruptedException {
final String tenantIdentifier = tenantDataStoreContext.getTenantName();
final Beat beat = new Beat();
beat.setIdentifier(beatIdentifier);
beat.setAlignmentHour(alignmentHour);
Mockito.doAnswer(new AnswerWithDelay<>(2_000, new Returns(Optional.of(PermittableGroupIds.forApplication(applicationIdentifier))))).when(beatPublisherServiceSpy).requestPermissionForBeats(Matchers.eq(tenantIdentifier), Matchers.eq(applicationIdentifier));
Mockito.doAnswer(new AnswerWithDelay<>(2_000, new Returns(true))).when(beatPublisherServiceSpy).publishBeat(Matchers.eq(beatIdentifier), Matchers.eq(tenantIdentifier), Matchers.eq(applicationIdentifier),
AdditionalMatchers.or(Matchers.eq(expectedBeatTimestamp), Matchers.eq(getNextTimeStamp(expectedBeatTimestamp))));
this.testSubject.createBeat(applicationIdentifier, beat);
Assert.assertTrue(this.eventRecorder.wait(EventConstants.POST_BEAT, new BeatEvent(applicationIdentifier, beat.getIdentifier())));
Mockito.verify(beatPublisherServiceSpy, Mockito.timeout(2_500).times(1)).requestPermissionForBeats(tenantIdentifier, applicationIdentifier);
return beat;
}
//...
}
``` | [
"src/main/java/org/mockito/AdditionalAnswers.java"
] | [
"src/main/java/org/mockito/AdditionalAnswers.java",
"src/main/java/org/mockito/internal/stubbing/answers/AnswersWithDelay.java"
] | [
"src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java"
] | diff --git a/src/main/java/org/mockito/AdditionalAnswers.java b/src/main/java/org/mockito/AdditionalAnswers.java
index 287e4b1830..214eaa5c47 100644
--- a/src/main/java/org/mockito/AdditionalAnswers.java
+++ b/src/main/java/org/mockito/AdditionalAnswers.java
@@ -5,6 +5,8 @@
package org.mockito;
import java.util.Collection;
+
+import org.mockito.internal.stubbing.answers.AnswersWithDelay;
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
import org.mockito.internal.stubbing.answers.ReturnsElementsOf;
import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;
@@ -316,6 +318,21 @@ public static <T> Answer<T> returnsElementsOf(Collection<?> elements) {
return (Answer<T>) new ReturnsElementsOf(elements);
}
+ /**
+ * Returns an answer after a delay with a defined length.
+ *
+ * @param <T> return type
+ * @param sleepyTime the delay in milliseconds
+ * @param answer interface to the answer which provides the intended return value.
+ * @return the answer object to use
+ *
+ * @since 2.8.44
+ */
+ @Incubating
+ public static <T> Answer<T> answersWithDelay(long sleepyTime, Answer<T> answer) {
+ return (Answer<T>) new AnswersWithDelay(sleepyTime, (Answer<Object>) answer);
+ }
+
/**
* Creates an answer from a functional interface - allows for a strongly typed answer to be created
* ideally in Java 8
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/AnswersWithDelay.java b/src/main/java/org/mockito/internal/stubbing/answers/AnswersWithDelay.java
new file mode 100644
index 0000000000..083b082fcb
--- /dev/null
+++ b/src/main/java/org/mockito/internal/stubbing/answers/AnswersWithDelay.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.ValidableAnswer;
+
+import java.io.Serializable;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Returns as the provided answer would return, after delaying the specified amount.
+ *
+ * <p>The <code>sleepyTime</code> specifies how long, in milliseconds, to pause before
+ * returning the provided <code>answer</code>.</p>
+ *
+ * @since 2.8.44
+ * @see org.mockito.AdditionalAnswers
+ */
+public class AnswersWithDelay implements Answer<Object>, ValidableAnswer, Serializable {
+ private static final long serialVersionUID = 2177950597971260246L;
+
+ private final long sleepyTime;
+ private final Answer<Object> answer;
+
+ public AnswersWithDelay(final long sleepyTime, final Answer<Object> answer) {
+ this.sleepyTime = sleepyTime;
+ this.answer = answer;
+ }
+
+ @Override
+ public Object answer(final InvocationOnMock invocation) throws Throwable {
+ TimeUnit.MILLISECONDS.sleep(sleepyTime);
+ return answer.answer(invocation);
+ }
+
+ @Override
+ public void validateFor(final InvocationOnMock invocation) {
+ if (answer instanceof ValidableAnswer) {
+ ((ValidableAnswer) answer).validateFor(invocation);
+ }
+ }
+}
+
| diff --git a/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java b/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java
new file mode 100644
index 0000000000..35c526555b
--- /dev/null
+++ b/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import org.junit.Test;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.invocation.InvocationBuilder;
+
+import java.util.Date;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.within;
+
+public class AnswersWithDelayTest {
+ @Test
+ public void should_return_value() throws Throwable {
+ assertThat(new AnswersWithDelay(1, new Returns("value")).answer(new InvocationBuilder().method("oneArg").arg("A").toInvocation())).isEqualTo("value");
+ }
+
+ @Test(expected = MockitoException.class)
+ public void should_fail_when_contained_answer_should_fail() throws Throwable {
+ new AnswersWithDelay(1, new Returns("one")).validateFor(new InvocationBuilder().method("voidMethod").toInvocation());
+ }
+
+ @Test
+ public void should_succeed_when_contained_answer_should_succeed() throws Throwable {
+ new AnswersWithDelay(1, new Returns("one")).validateFor(new InvocationBuilder().simpleMethod().toInvocation());
+ }
+
+ @Test
+ public void should_delay() throws Throwable {
+ final long sleepyTime = 500L;
+
+ final AnswersWithDelay testSubject = new AnswersWithDelay(sleepyTime, new Returns("value"));
+
+ final Date before = new Date();
+ testSubject.answer(new InvocationBuilder().method("oneArg").arg("A").toInvocation());
+ final Date after = new Date();
+
+ final long timePassed = after.getTime() - before.getTime();
+ assertThat(timePassed).isCloseTo(sleepyTime, within(15L));
+ }
+}
+
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java
index e67f711b77..417d998cc5 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithAdditionalAnswersTest.java
@@ -5,17 +5,17 @@
package org.mockitousage.stubbing;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.within;
import static org.mockito.AdditionalAnswers.answer;
import static org.mockito.AdditionalAnswers.answerVoid;
import static org.mockito.AdditionalAnswers.returnsArgAt;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.AdditionalAnswers.returnsLastArg;
import static org.mockito.AdditionalAnswers.returnsSecondArg;
+import static org.mockito.AdditionalAnswers.answersWithDelay;
import static org.mockito.BDDMockito.any;
import static org.mockito.BDDMockito.anyInt;
-import static org.mockito.BDDMockito.anyObject;
import static org.mockito.BDDMockito.anyString;
-import static org.mockito.BDDMockito.anyVararg;
import static org.mockito.BDDMockito.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.mock;
@@ -37,6 +37,8 @@
import org.mockito.stubbing.VoidAnswer5;
import org.mockitousage.IMethods;
+import java.util.Date;
+
@RunWith(MockitoJUnitRunner.class)
public class StubbingWithAdditionalAnswersTest {
@@ -44,18 +46,32 @@ public class StubbingWithAdditionalAnswersTest {
@Test
public void can_return_arguments_of_invocation() throws Exception {
- given(iMethods.objectArgMethod(anyObject())).will(returnsFirstArg());
- given(iMethods.threeArgumentMethod(eq(0), anyObject(), anyString())).will(returnsSecondArg());
- given(iMethods.threeArgumentMethod(eq(1), anyObject(), anyString())).will(returnsLastArg());
+ given(iMethods.objectArgMethod(any())).will(returnsFirstArg());
+ given(iMethods.threeArgumentMethod(eq(0), any(), anyString())).will(returnsSecondArg());
+ given(iMethods.threeArgumentMethod(eq(1), any(), anyString())).will(returnsLastArg());
assertThat(iMethods.objectArgMethod("first")).isEqualTo("first");
assertThat(iMethods.threeArgumentMethod(0, "second", "whatever")).isEqualTo("second");
assertThat(iMethods.threeArgumentMethod(1, "whatever", "last")).isEqualTo("last");
}
+ @Test
+ public void can_return_after_delay() throws Exception {
+ final long sleepyTime = 500L;
+
+ given(iMethods.objectArgMethod(any())).will(answersWithDelay(sleepyTime, returnsFirstArg()));
+
+ final Date before = new Date();
+ assertThat(iMethods.objectArgMethod("first")).isEqualTo("first");
+ final Date after = new Date();
+
+ final long timePassed = after.getTime() - before.getTime();
+ assertThat(timePassed).isCloseTo(sleepyTime, within(15L));
+ }
+
@Test
public void can_return_expanded_arguments_of_invocation() throws Exception {
- given(iMethods.varargsObject(eq(1), anyVararg())).will(returnsArgAt(3));
+ given(iMethods.varargsObject(eq(1), any())).will(returnsArgAt(3));
assertThat(iMethods.varargsObject(1, "bob", "alexander", "alice", "carl")).isEqualTo("alice");
}
@@ -163,7 +179,7 @@ public void answer(Integer i, String s1, String s2) {
}
@Test
- public void can_return_based_on_strongly_typed_four_parameter_function() throws Exception {
+ public void can_return_based_on_strongly_typed_four_parameter_function() throws Exception {
final IMethods target = mock(IMethods.class);
given(iMethods.fourArgumentMethod(anyInt(), anyString(), anyString(), any(boolean[].class)))
.will(answer(new Answer4<String, Integer, String, String, boolean[]>() {
| test | train | 2017-06-10T20:41:06 | "2017-06-08T15:22:57Z" | myrle-krantz | train |
mockito/mockito/1127_1129 | mockito/mockito | mockito/mockito/1127 | mockito/mockito/1129 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8675876474461881)"
] | e8829b53996fb152c8a4271de768a783868a8ffe | c295a53539316b8549663caa86463a90fe984e27 | [
"I think we need to set a property on our project, looking at the line above in the Travis build you linked: \r\n```\r\nproject property 'maven-central-release' exists: false\r\n```",
"Looking! Thank you for reporting!",
"Great bug report guys! It was very easy to nail down the issue!",
"Please review / merge: https://github.com/mockito/mockito/pull/1129",
"Worked perfectly - https://repo1.maven.org/maven2/org/mockito/mockito-core/2.8.47/"
] | [
"👍 "
] | "2017-06-15T14:35:35Z" | [
"question",
"continuous integration"
] | Version not released to Maven Central | 2 days ago I requested a [build](https://github.com/mockito/mockito/commit/04961ae3cc8093916f563d7edc223224d757a4a1) with Maven Central sync (having notable changes merged). Looking into release configuration I used `[ci maven-central-release]` and it seems to be [enabled](https://travis-ci.org/mockito/mockito/jobs/242215132#L842) in Travis.
However, that release is not [available](https://maven-badges.herokuapp.com/maven-central/org.mockito/mockito-core) in Maven Central (2.8.9 is the newest as time of raising this issue instead of 2.8.44).
@szczepiq Is there anything else (with the current release mechanism) that is needed to do to build a "notable version"? | [
"gradle/shipkit.gradle"
] | [
"gradle/shipkit.gradle"
] | [] | diff --git a/gradle/shipkit.gradle b/gradle/shipkit.gradle
index 24ac169368..2c9efd7e35 100644
--- a/gradle/shipkit.gradle
+++ b/gradle/shipkit.gradle
@@ -84,4 +84,5 @@ static boolean shouldReleaseToCentral(project) {
project.afterEvaluate {
project.tasks.performRelease.doLast { logger.lifecycle(message) }
}
+ return centralRelease
}
| null | train | train | 2017-06-13T17:03:39 | "2017-06-14T09:56:30Z" | szpak | train |
mockito/mockito/1144_1145 | mockito/mockito | mockito/mockito/1144 | mockito/mockito/1145 | [
"timestamp(timedelta=131388.0, similarity=0.8609656881228989)",
"keyword_pr_to_issue"
] | 48856d8fc844d70b21c804d55f5be624d3687ac3 | 6d6361fc72c16c947ef5f2f587fd9269a9d47f23 | [
"This should be fixed now."
] | [] | "2017-07-06T18:21:49Z" | [
"bug",
"continuous integration"
] | Unnecessary release was triggered | It seems that Shipkit was not able to avoid unnecessary release (see the [release notes](https://github.com/mockito/mockito/blob/release/2.x/doc/release-notes/official.md)). I will look into that. Our goal is not avoid shipping new version if binaries don't change. | [
"gradle.properties"
] | [
"gradle.properties"
] | [] | diff --git a/gradle.properties b/gradle.properties
index d7832b247d..946ba4c5d3 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -2,4 +2,4 @@ org.gradle.daemon=true
org.gradle.parallel=true
#Declared the dependency here to avoid duplication across build.gradle files
-dependencies.shipkit=org.shipkit:shipkit:0.8.112
+dependencies.shipkit=org.shipkit:shipkit:0.8.114
| null | train | train | 2017-07-06T19:43:14 | "2017-07-06T17:56:32Z" | mockitoguy | train |
mockito/mockito/1155_1162 | mockito/mockito | mockito/mockito/1155 | mockito/mockito/1162 | [
"keyword_pr_to_issue"
] | 9e4de546d7ea2ec675e15d8b6960a3b8ffe324f7 | f1ceb5097298872aef63725e758a80293417c5c1 | [
"I am going to fix this. \r\n\r\nThrowsExceptionClass must simply implement ValidableAnswer...\r\n\r\n\r\n\r\n",
"Thank you for reporting. Indeed it is a bug."
] | [
"Missing the ewuals here",
"Missing equals here",
"Missing equals here",
"Can you give me some more infos? We expect the instance to be thrown that was passed to the stubbing, right?",
"Lets better use: `exception.expect(sameInstance(expected));`",
"Sorry, this one is correct. I misread"
] | "2017-08-12T11:57:33Z" | [] | thenThrow(Class) should only throw checked exceptions that match the signature of the stubbed method | Hi,
- mockito-core 2.8.47
```java
public class FooTest {
@Test(expected = MockitoException.class)
public void using_thenThrow_Throwable() {
C mock = mock(C.class);
// Set a checked exception that does not matche the method signature
when(mock.doIt()).thenThrow(new Exception());
}
@Test(expected = MockitoException.class)
public void using_thenThrow_Class() {
C mock = mock(C.class);
// Set a checked exception that does not matche the method signature
when(mock.doIt()).thenThrow(Exception.class);
}
static class C {
String doIt() {
return null;
}
}
}
```
`using_thenThrow_Throwable()` passes, but `using_thenThrow_Class()` fails.
```
java.lang.AssertionError: Expected exception: org.mockito.exceptions.base.MockitoException
```
The Javadoc of `OngoingStubbing#thenThrow(Class)` says, *If the throwable class is a checked exception then it has to match one of the checked exceptions of the stubbed method signature*.
However, the result of `using_thenThrow_Class()` shows that it is not so.
| [
"src/main/java/org/mockito/internal/stubbing/BaseStubbing.java",
"src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java",
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java",
"src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java"
] | [
"src/main/java/org/mockito/internal/stubbing/BaseStubbing.java",
"src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java",
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java"
] | [
"src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
index c55c82b99a..ddb9a8dcb9 100644
--- a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
+++ b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
@@ -4,26 +4,30 @@
*/
package org.mockito.internal.stubbing;
+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.internal.stubbing.answers.ThrowsExceptionClass;
import org.mockito.stubbing.OngoingStubbing;
public abstract class BaseStubbing<T> implements OngoingStubbing<T> {
+ @Override
public OngoingStubbing<T> thenReturn(T value) {
return thenAnswer(new Returns(value));
}
- @SuppressWarnings({"unchecked","vararg"})
+ @Override
public OngoingStubbing<T> thenReturn(T value, T... values) {
OngoingStubbing<T> stubbing = thenReturn(value);
if (values == null) {
- //TODO below does not seem right
+ // TODO below does not seem right
return stubbing.thenReturn(null);
}
- for (T v: values) {
+ for (T v : values) {
stubbing = stubbing.thenReturn(v);
}
return stubbing;
@@ -33,12 +37,13 @@ private OngoingStubbing<T> thenThrow(Throwable throwable) {
return thenAnswer(new ThrowsException(throwable));
}
+ @Override
public OngoingStubbing<T> thenThrow(Throwable... throwables) {
if (throwables == null) {
return thenThrow((Throwable) null);
}
OngoingStubbing<T> stubbing = null;
- for (Throwable t: throwables) {
+ for (Throwable t : throwables) {
if (stubbing == null) {
stubbing = thenThrow(t);
} else {
@@ -48,23 +53,31 @@ public OngoingStubbing<T> thenThrow(Throwable... throwables) {
return stubbing;
}
+ @Override
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType) {
- return thenAnswer(new ThrowsExceptionClass(throwableType));
+ if (throwableType == null) {
+ mockingProgress().reset();
+ throw notAnException();
+ }
+ return thenThrow(newInstance(throwableType));
}
- @SuppressWarnings ({"unchecked", "varargs"})
+ @Override
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
if (nextToBeThrown == null) {
- thenThrow((Throwable) null);
+ thenThrow((Class<Throwable>) null);
}
OngoingStubbing<T> stubbing = thenThrow(toBeThrown);
- for (Class<? extends Throwable> t: nextToBeThrown) {
+ for (Class<? extends Throwable> t : nextToBeThrown) {
stubbing = stubbing.thenThrow(t);
}
return stubbing;
}
+ @Override
public OngoingStubbing<T> thenCallRealMethod() {
return thenAnswer(new CallsRealMethods());
}
}
+
+
diff --git a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
index fd47434a75..78a10270a3 100644
--- a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
@@ -20,6 +20,7 @@ public OngoingStubbingImpl(InvocationContainerImpl invocationContainer) {
this.invocationContainer = invocationContainer;
}
+ @Override
public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
if(!invocationContainer.hasInvocationForPotentialStubbing()) {
throw incorrectUseOfApi();
@@ -29,6 +30,7 @@ public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
return new ConsecutiveStubbing<T>(invocationContainer);
}
+ @Override
public OngoingStubbing<T> then(Answer<?> answer) {
return thenAnswer(answer);
}
@@ -38,8 +40,11 @@ public List<Invocation> getRegisteredInvocations() {
return invocationContainer.getInvocations();
}
+ @Override
@SuppressWarnings("unchecked")
public <M> M getMock() {
return (M) invocationContainer.invokedMock();
}
}
+
+
diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
index 89255ab791..efe74880ca 100644
--- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
@@ -5,8 +5,12 @@
package org.mockito.internal.stubbing;
import static org.mockito.internal.exceptions.Reporter.notAMockPassedToWhenMethod;
+import static org.mockito.internal.exceptions.Reporter.notAnException;
import static org.mockito.internal.exceptions.Reporter.nullPassedToWhenMethod;
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
import static org.mockito.internal.stubbing.answers.DoesNothing.doesNothing;
+import static org.mockito.internal.util.MockUtil.isMock;
+import static org.objenesis.ObjenesisHelper.newInstance;
import java.util.LinkedList;
import java.util.List;
@@ -14,12 +18,10 @@
import org.mockito.internal.stubbing.answers.CallsRealMethods;
import org.mockito.internal.stubbing.answers.Returns;
import org.mockito.internal.stubbing.answers.ThrowsException;
-import org.mockito.internal.stubbing.answers.ThrowsExceptionClass;
import org.mockito.internal.util.MockUtil;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Stubber;
-@SuppressWarnings("unchecked")
public class StubberImpl implements Stubber {
private final List<Answer<?>> answers = new LinkedList<Answer<?>>();
@@ -30,11 +32,13 @@ public <T> T when(T mock) {
throw nullPassedToWhenMethod();
}
- if (!MockUtil.isMock(mock)) {
- throw notAMockPassedToWhenMethod();
- }
+ if (!isMock(mock)) {
+ throw notAMockPassedToWhenMethod();
+ }
+
+
+ MockUtil.getInvocationContainer(mock).setAnswersForStubbing(answers);
- MockUtil.getInvocationContainer(mock).setAnswersForStubbing(answers);
return mock;
}
@@ -49,7 +53,7 @@ public Stubber doReturn(Object toBeReturned, Object... nextToBeReturned) {
}
private StubberImpl doReturnValues(Object... toBeReturned) {
- if(toBeReturned == null) {
+ if (toBeReturned == null) {
answers.add(new Returns(null));
return this;
}
@@ -61,7 +65,7 @@ private StubberImpl doReturnValues(Object... toBeReturned) {
@Override
public Stubber doThrow(Throwable... toBeThrown) {
- if(toBeThrown == null) {
+ if (toBeThrown == null) {
answers.add(new ThrowsException(null));
return this;
}
@@ -73,19 +77,34 @@ public Stubber doThrow(Throwable... toBeThrown) {
@Override
public Stubber doThrow(Class<? extends Throwable> toBeThrown) {
- return doThrowClasses(toBeThrown);
+ if (toBeThrown == null) {
+ mockingProgress().reset();
+ throw notAnException();
+ }
+ Throwable e;
+ try {
+ e = newInstance(toBeThrown);
+ } catch (RuntimeException instanciationError) {
+ mockingProgress().reset();
+ throw instanciationError;
+ }
+ return doThrow(e);
}
@Override
public Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
- return doThrowClasses(toBeThrown).doThrowClasses(nextToBeThrown);
- }
+ Stubber stubber = doThrow(toBeThrown);
- private StubberImpl doThrowClasses(Class<? extends Throwable>... toBeThrown) {
- for (Class<? extends Throwable> throwable: toBeThrown) {
- answers.add(new ThrowsExceptionClass(throwable));
+ if (nextToBeThrown == null) {
+ mockingProgress().reset();
+ throw notAnException();
}
- return this;
+
+ for (Class<? extends Throwable> next : nextToBeThrown) {
+ stubber = stubber.doThrow(next);
+ }
+ return stubber;
+
}
@Override
@@ -106,3 +125,5 @@ public Stubber doCallRealMethod() {
return this;
}
}
+
+
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java
deleted file mode 100644
index ef7baad764..0000000000
--- a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-
-package org.mockito.internal.stubbing.answers;
-
-import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.objenesis.ObjenesisHelper;
-
-import static org.mockito.internal.exceptions.Reporter.notAnException;
-
-import java.io.Serializable;
-
-public class ThrowsExceptionClass implements Answer<Object>, Serializable {
-
- private final Class<? extends Throwable> throwableClass;
- private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
-
- public ThrowsExceptionClass(Class<? extends Throwable> throwableClass) {
- this.throwableClass = checkNonNullThrowable(throwableClass);
- }
-
- private Class<? extends Throwable> checkNonNullThrowable(Class<? extends Throwable> throwableClass) {
- if(throwableClass == null || !Throwable.class.isAssignableFrom(throwableClass)) {
- throw notAnException();
- }
- return throwableClass;
- }
-
- public Object answer(InvocationOnMock invocation) throws Throwable {
- //TODO centralize the use of Objenesis. Why do we use ObjenesisHelper?
- Throwable throwable = ObjenesisHelper.newInstance(throwableClass);
- throwable.fillInStackTrace();
- filter.filter(throwable);
- throw throwable;
- }
-
- public Class<? extends Throwable> getThrowableClass() {
- return throwableClass;
- }
-}
| diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
index 0ccf14f268..1931bd1de2 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
@@ -5,29 +5,43 @@
package org.mockitousage.stubbing;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.exceptions.base.MockitoException;
-import org.mockito.exceptions.verification.NoInteractionsWanted;
-import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockitoutil.TestBase;
+import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.assertNull;
+import static junit.framework.TestCase.assertTrue;
+import static junit.framework.TestCase.fail;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.exceptions.verification.NoInteractionsWanted;
+import org.mockito.exceptions.verification.WantedButNotInvoked;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
-import static junit.framework.TestCase.*;
-import static org.mockito.Mockito.*;
-
-@SuppressWarnings({"serial", "unchecked", "all", "deprecation"})
+@SuppressWarnings({ "serial", "unchecked", "rawtypes" })
public class StubbingWithThrowablesTest extends TestBase {
private LinkedList mock;
private Map mockTwo;
+ @Rule
+ public ExpectedException exception = ExpectedException.none();
+
@Before
public void setup() {
mock = mock(LinkedList.class);
@@ -39,12 +53,9 @@ public void shouldStubWithThrowable() throws Exception {
IllegalArgumentException expected = new IllegalArgumentException("thrown by mock");
when(mock.add("throw")).thenThrow(expected);
- try {
- mock.add("throw");
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals(expected, e);
- }
+ exception.expect(sameInstance(expected));
+ mock.add("throw");
+
}
@Test
@@ -52,12 +63,11 @@ public void shouldSetThrowableToVoidMethod() throws Exception {
IllegalArgumentException expected = new IllegalArgumentException("thrown by mock");
doThrow(expected).when(mock).clear();
- try {
- mock.clear();
- fail();
- } catch (Exception e) {
- assertEquals(expected, e);
- }
+
+ exception.expect(sameInstance(expected));
+
+ mock.clear();
+
}
@Test
@@ -65,22 +75,18 @@ public void shouldLastStubbingVoidBeImportant() throws Exception {
doThrow(new ExceptionOne()).when(mock).clear();
doThrow(new ExceptionTwo()).when(mock).clear();
- try {
- mock.clear();
- fail();
- } catch (ExceptionTwo e) {
- }
+ exception.expect(ExceptionTwo.class);
+
+ mock.clear();
}
@Test
public void shouldFailStubbingThrowableOnTheSameInvocationDueToAcceptableLimitation() throws Exception {
- when(mock.get(1)).thenThrow(new ExceptionOne());
+ when(mock.size()).thenThrow(new ExceptionOne());
- try {
- when(mock.get(1)).thenThrow(new ExceptionTwo());
- fail();
- } catch (ExceptionOne e) {
- }
+ exception.expect(ExceptionOne.class);
+
+ when(mock.size()).thenThrow(new ExceptionTwo());
}
@Test
@@ -90,12 +96,9 @@ public void shouldAllowSettingCheckedException() throws Exception {
when(reader.read()).thenThrow(ioException);
- try {
- reader.read();
- fail();
- } catch (Exception e) {
- assertEquals(ioException, e);
- }
+ exception.expect(sameInstance(ioException));
+
+ reader.read();
}
@Test
@@ -104,49 +107,147 @@ public void shouldAllowSettingError() throws Exception {
when(mock.add("quake")).thenThrow(error);
- try {
- mock.add("quake");
- fail();
- } catch (Error e) {
- assertEquals(error, e);
- }
+ exception.expect(Error.class);
+
+ mock.add("quake");
}
- @Test(expected = MockitoException.class)
+ @Test
public void shouldNotAllowNullExceptionType() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot stub with null throwable");
+
when(mock.add(null)).thenThrow((Exception) null);
}
-
- @Test(expected = NaughtyException.class)
+ @Test
public void shouldInstantiateExceptionClassOnInteraction() {
when(mock.add(null)).thenThrow(NaughtyException.class);
+ exception.expect(NaughtyException.class);
+
mock.add(null);
}
- @Test(expected = NaughtyException.class)
+ @Test
public void shouldInstantiateExceptionClassWithOngoingStubbingOnInteraction() {
doThrow(NaughtyException.class).when(mock).add(null);
+ exception.expect(NaughtyException.class);
+
mock.add(null);
}
- @Test(expected = MockitoException.class)
- public void shouldNotAllowSettingInvalidCheckedException() throws Exception {
+ @Test
+ public void shouldNotAllowSettingInvalidCheckedException() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Checked exception is invalid for this method");
+
when(mock.add("monkey island")).thenThrow(new Exception());
}
- @Test(expected = MockitoException.class)
- public void shouldNotAllowSettingNullThrowable() throws Exception {
+ @Test
+ public void shouldNotAllowSettingNullThrowable() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot stub with null throwable");
+
when(mock.add("monkey island")).thenThrow((Throwable) null);
}
- @Test(expected = MockitoException.class)
- public void shouldNotAllowSettingNullThrowableArray() throws Exception {
+ @Test
+ public void shouldNotAllowSettingNullThrowableArray() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Cannot stub with null throwable");
+
when(mock.add("monkey island")).thenThrow((Throwable[]) null);
}
+ @Test
+ public void shouldNotAllowSettingNullThrowableClass() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ when(mock.isEmpty()).thenThrow((Class) null);
+ }
+
+ @Test
+ public void shouldNotAllowSettingNullThrowableClasses() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class[]) null);
+ }
+
+ @Test
+ public void shouldNotAllowSettingNullVarArgThrowableClass() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class) null);
+ }
+
+ @Test
+ public void doThrowShouldNotAllowSettingNullThrowableClass() {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ doThrow((Class) null).when(mock).isEmpty();
+ }
+
+ @Test
+ public void doThrowShouldNotAllowSettingNullThrowableClasses() throws Exception {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ doThrow(RuntimeException.class, (Class) null).when(mock).isEmpty();
+ }
+
+ @Test
+ public void doThrowShouldNotAllowSettingNullVarArgThrowableClasses() throws Exception {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ doThrow(RuntimeException.class, (Class[]) null).when(mock).isEmpty();
+ }
+
+ @Test
+ public void shouldNotAllowSettingNullVarArgsThrowableClasses() throws Exception {
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Exception type cannot be null");
+
+ when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class<RuntimeException>[]) null);
+ }
+
+ @Test
+ public void shouldNotAllowDifferntCheckedException() throws Exception {
+ IMethods mock = mock(IMethods.class);
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Checked exception is invalid for this method");
+
+ when(mock.throwsIOException(0)).thenThrow(CheckedException.class);
+ }
+
+ @Test
+ public void shouldNotAllowCheckedExceptionWhenErrorIsDeclared() throws Exception {
+ IMethods mock = mock(IMethods.class);
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Checked exception is invalid for this method");
+
+ when(mock.throwsError(0)).thenThrow(CheckedException.class);
+ }
+
+ @Test
+ public void shouldNotAllowCheckedExceptionWhenNothingIsDeclared() throws Exception {
+ IMethods mock = mock(IMethods.class);
+
+ exception.expect(MockitoException.class);
+ exception.expectMessage("Checked exception is invalid for this method");
+
+ when(mock.throwsNothing(true)).thenThrow(CheckedException.class);
+ }
+
@Test
public void shouldMixThrowablesAndReturnsOnDifferentMocks() throws Exception {
when(mock.add("ExceptionOne")).thenThrow(new ExceptionOne());
@@ -236,31 +337,23 @@ public void shouldStubbingWithThrowableFailVerification() {
}
private class ExceptionOne extends RuntimeException {
-
}
private class ExceptionTwo extends RuntimeException {
-
}
private class ExceptionThree extends RuntimeException {
-
}
private class ExceptionFour extends RuntimeException {
+ }
+ private class CheckedException extends Exception {
}
public class NaughtyException extends RuntimeException {
-
public NaughtyException() {
throw new RuntimeException("boo!");
}
}
-
- @Test(expected = NaughtyException.class)
- public void shouldShowDecentMessageWhenExcepionIsNaughty() throws Exception {
- when(mock.add("")).thenThrow(NaughtyException.class);
- mock.add("");
- }
}
| test | train | 2017-09-08T18:08:12 | "2017-08-03T13:49:41Z" | tmurakami | train |
mockito/mockito/1182_1184 | mockito/mockito | mockito/mockito/1182 | mockito/mockito/1184 | [
"keyword_pr_to_issue"
] | 1c61f1a91a7d5d8367b3dbddb6270afdd96c8f6a | 500b5770523c93fcc7860821a798f08361779b9c | [
"This was fixed in #1184"
] | [] | "2017-09-04T21:39:42Z" | [
"continuous integration"
] | Travis CI ERROR: JAVA_HOME is set to an invalid directory | Travis CI builds started failing with "ERROR: JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-7-oracle". [Example failure](https://travis-ci.org/mockito/mockito/jobs/270842998).
```
$ ./gradlew build idea -s -PcheckJava6Compatibility && ./gradlew ciPerformRelease
ERROR: JAVA_HOME is set to an invalid directory: /usr/lib/jvm/java-7-oracle
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
```
It looks like there was some incompatible change rolled out in Travis CI. | [
".travis.yml"
] | [
".travis.yml"
] | [] | diff --git a/.travis.yml b/.travis.yml
index e626d42d1a..096880fcb6 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -15,11 +15,7 @@ language: java
matrix:
include:
- - jdk: oraclejdk7
- - jdk: oraclejdk7
- env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline
- jdk: oraclejdk8
- env: SKIP_RELEASE=true
- jdk: oraclejdk8
env: SKIP_RELEASE=true MOCK_MAKER=mock-maker-inline
| null | train | train | 2017-09-04T23:38:20 | "2017-09-01T16:00:09Z" | mockitoguy | train |
mockito/mockito/1189_1195 | mockito/mockito | mockito/mockito/1189 | mockito/mockito/1195 | [
"timestamp(timedelta=2.0, similarity=0.8418935844654968)"
] | bf98a225a43e0a910ce84faed907fb08ef8b7799 | 5a5c409f561c853c04974c1542fe2f65c999c263 | [
"If we can make this work on JDK6-8, I am all for it. If you can, please submit a PR that we can review :)",
"This change is compatible with JDK6-8, because you only add an entry to `MANIFEST.mf` file. Older Java versions simply ignore it, and JDK9 uses it as a stable automatic module name (instead of generating it from JAR archive name).\r\n\r\nIf you drop the support for older JDKs somewhere in the future, you can create a true module with the same name and the change will be invisible to JDK9 modular applications:\r\n\r\n```java\r\nmodule org.mockito {\r\n requires ...;\r\n}\r\n```\r\n\r\nPR -> I'd love to, but I'm tracking the Jigsaw support in more projects and I'm afraid I don't have enough time to update them all. So I will see."
] | [] | "2017-10-04T16:23:03Z" | [
"java-9",
"please contribute"
] | JDK9: set a stable module name with `Automatic-Module-Name` entry in MANIFEST | JDK9 is out and introduces a module system.
Mockito does not currently use modules. When we use it in a JDK9 modular application, Java turns the JAR into a so-called automatic module, whose name is derived from the JAR archive name (*mockito*, in this case). However, the default name does not follow the recommended module naming conventions (reverse-dns style, module name derived from the main exported package).
It is possible to specify a stable automatic module name through a `Automatic-Module-Name` manifest entry, while still targeting JDK8:
```
Automatic-Module-Name: org.mockito
```
Selecting a stable module name is very important, because Java does not allow two modules to own the same package, and you may end up with a module hell. The naming issues are well-explained on Stephen Colebourne's blog:
* http://blog.joda.org/2017/04/java-se-9-jpms-module-naming.html
* http://blog.joda.org/2017/05/java-se-9-jpms-automatic-modules.html <- the explanation of module hell problem
And the comment of Mike Reinhold, chief Java architect:
> Strongly recommend that all modules be named according to the reverse Internet domain-name convention. A module's name should correspond to the name of its principal exported API package, which should also follow that convention. If a module does not have such a package, or if for legacy reasons it must have a name that does not correspond to one of its exported packages, then its name should at least start with the reversed form of an Internet domain with which the author is associated. | [
"gradle/mockito-core/osgi.gradle"
] | [
"gradle/mockito-core/osgi.gradle"
] | [] | diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle
index 2b0eb65fee..90a32eb6f8 100644
--- a/gradle/mockito-core/osgi.gradle
+++ b/gradle/mockito-core/osgi.gradle
@@ -27,6 +27,8 @@ afterEvaluate {
'org.mockito.*'
instruction '-removeheaders', 'Private-Package'
+
+ attributes 'Automatic-Module-Name': 'org.mockito'
}
}
}
| null | train | train | 2017-10-04T14:02:50 | "2017-09-24T15:16:58Z" | zyxist | train |
mockito/mockito/1212_1226 | mockito/mockito | mockito/mockito/1212 | mockito/mockito/1226 | [
"timestamp(timedelta=165622.0, similarity=0.8636678635689894)"
] | e10c5409e460c3ecd6b2ef9513a0b3802351d85f | fb3f09de77e6992973499a2d779113c44e8fe3e8 | [
"What's more even using the old Silent `@RunWith(org.mockito.runners.MockitoJUnitRunner.Silent.class)` still causes `UnnecessaryStubbingException`. The new one (`@RunWith(org.mockito.junit.MockitoJUnitRunner.Silent.class)`) has to be used to keep test passing.",
"https://github.com/mockito/mockito/blob/e10c5409e460c3ecd6b2ef9513a0b3802351d85f/src/main/java/org/mockito/runners/MockitoJUnitRunner.java#L29-L31\r\n\r\nIt seems we have to change the call to this instead: https://github.com/mockito/mockito/blob/e10c5409e460c3ecd6b2ef9513a0b3802351d85f/src/main/java/org/mockito/junit/MockitoJUnitRunner.java#L107\r\n\r\nI submitted #1226 to discuss this change in behavior. I think it is an oversight when we deprecated the runner in the old package.",
"It's a bug. Thank you for reporting!\r\n\r\nThe previous runner: ```org.mockito.runners.MockitoJUnitRunner``` should behave exactly the same as the new runner: ```org.mockito.junit.MockitoJUnitRunner```",
"I started reviewing @TimvdLippe PR and I came to conclusion that it the current behavior works as designed.\r\n\r\n - the change of strictness of the runner was an intentional incompatible change in 2.0 release\r\n - the deprecation of the runner was a compatible change done after 2.0. Deprecated runner does not intend to help migration.\r\n - the current behavior of the code (unless I'm mistaken) is that deprecated runner behaves as the new runner which is what we want.\r\n\r\nI hope above clarifies the situation :) Please reopen if needed!"
] | [
"Curious why changing the public modifier?\r\n\r\nI suspect that this change may not be binary compatible in case somebody extends the runner.",
"The code works as designed (https://github.com/mockito/mockito/issues/1212#issuecomment-340266646).\r\n\r\nIf you want to keep the PR I suggest that we add a unit test that uses deprecated runner so that we preserve and document this behavior."
] | "2017-10-27T13:12:40Z" | [
"question",
"wontfix",
"strictness"
] | MockitoJUnitRunner too strict by default? | In one of the projects being migrated to Mockito 2 I've observed that deprecated `org.mockito.runners.MockitoJUnitRunner` (tested with 2.11.0) works in a strict mode by default (fails a test on unnecessary stubbing). I wonder if it is an expected behavior?
Even Mockito rule works in a "warn" mode by default. It makes it a little bit harder to migrate from Mockito 1.10.x to 2.x. | [
"src/main/java/org/mockito/junit/MockitoJUnitRunner.java",
"src/main/java/org/mockito/runners/MockitoJUnitRunner.java"
] | [
"src/main/java/org/mockito/junit/MockitoJUnitRunner.java",
"src/main/java/org/mockito/runners/MockitoJUnitRunner.java"
] | [] | diff --git a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java
index 2a1558719b..fbdbfcf5eb 100644
--- a/src/main/java/org/mockito/junit/MockitoJUnitRunner.java
+++ b/src/main/java/org/mockito/junit/MockitoJUnitRunner.java
@@ -152,7 +152,7 @@ public MockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
this(new StrictRunner(new RunnerFactory().createStrict(klass), klass));
}
- MockitoJUnitRunner(InternalRunner runner) throws InvocationTargetException {
+ protected MockitoJUnitRunner(InternalRunner runner) throws InvocationTargetException {
this.runner = runner;
}
diff --git a/src/main/java/org/mockito/runners/MockitoJUnitRunner.java b/src/main/java/org/mockito/runners/MockitoJUnitRunner.java
index 74f025c6f1..5ad17a4a2a 100644
--- a/src/main/java/org/mockito/runners/MockitoJUnitRunner.java
+++ b/src/main/java/org/mockito/runners/MockitoJUnitRunner.java
@@ -9,6 +9,8 @@
import org.junit.runner.manipulation.Filter;
import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.notification.RunNotifier;
+import org.mockito.internal.runners.InternalRunner;
+import org.mockito.internal.runners.RunnerFactory;
/**
@@ -27,7 +29,7 @@ public class MockitoJUnitRunner extends org.mockito.junit.MockitoJUnitRunner {
@Deprecated
public static class Silent extends MockitoJUnitRunner {
public Silent(Class<?> klass) throws InvocationTargetException {
- super(klass);
+ super(new RunnerFactory().create(klass));
}
}
@@ -47,6 +49,10 @@ public MockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
super(klass);
}
+ MockitoJUnitRunner(InternalRunner runner) throws InvocationTargetException {
+ super(runner);
+ }
+
@Deprecated
@Override
public void run(final RunNotifier notifier) {
| null | train | train | 2017-10-22T16:21:02 | "2017-10-19T13:23:38Z" | szpak | train |
mockito/mockito/1130_1228 | mockito/mockito | mockito/mockito/1130 | mockito/mockito/1228 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8800423002840884)"
] | e10c5409e460c3ecd6b2ef9513a0b3802351d85f | 08c13b2a00a2d8c00d9bb62d40cc4e454aa3d7cb | [
"That seems fine to me. Please submit a pull request :smile: "
] | [
"Shouldn't it be RetentionPolicy.RUNTIME? Annotations with RetentionPolicy.CLASS are not preserved for the vm runtime execution, which is what I assume Findbugs needs.",
"Since this annotation is on our core public API methods, can you add a paragraph describing what this annotation means for the end users, written in a way that even a newbie would understand :)",
"Let's add \"since\" Javadoc tag",
"Actually, I think we should make this package-protected. It's not intended to be used by Mockito users",
"I don't think so, it seems to work in AssertJ: https://github.com/karlicoss/assertj-core/blob/master/src/main/java/org/assertj/core/util/CheckReturnValue.java",
"If you make it package-protected we won't be able to use this annotation on our public types that reside is subpackages.",
"ok :)"
] | "2017-10-27T13:38:24Z" | [] | Mockito should annotate when() methods with a custom annotation @CheckReturnValue | Static code checkers like error-Prone and FindBugs will help detecting invalid usage of Mockito in single-call situations if Mockito source code were annotated with @CheckReturnValue.
See:
* https://github.com/joel-costigliola/assertj-core/issues/157
* http://errorprone.info/bugpattern/CheckReturnValue
* https://github.com/joel-costigliola/assertj-core/pull/695
* https://github.com/joel-costigliola/assertj-core/blob/master/src/main/java/org/assertj/core/util/CheckReturnValue.java
Note like for AssertJ, any annotation with name should do, no need to depend on a specific library with @CheckReturnValue. | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/CheckReturnValue.java",
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/CheckReturnValue.java b/src/main/java/org/mockito/CheckReturnValue.java
new file mode 100644
index 0000000000..42c7545bff
--- /dev/null
+++ b/src/main/java/org/mockito/CheckReturnValue.java
@@ -0,0 +1,28 @@
+package org.mockito;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+/**
+ * This annotation is not supposed to be used by Mockito end-users. Instead, we
+ * use it to annotate methods for Static Analysis tools, including FindBugs and ErrorProne.
+ * These tools can check whether the return value of our Mockito methods are actually
+ * used. As such, Mockito State Validation can be performed at compile-time rather than run-time.
+ * This annotation is public, because we have to use it in multiple packages.
+ *
+ * @see <a href="https://github.com/findbugsproject/findbugs/blob/264ae7baf890d2b347d91805c90057062b5dcb1e/findbugs/src/java/edu/umd/cs/findbugs/detect/BuildCheckReturnAnnotationDatabase.java#L120">Findbugs source code</a>
+ * @see <a href="http://errorprone.info/bugpattern/CheckReturnValue">ErrorProne check</a>
+ * @since 2.11.4
+ */
+@Target({
+ ElementType.CONSTRUCTOR,
+ ElementType.METHOD,
+ ElementType.PACKAGE,
+ ElementType.TYPE
+})
+@Retention(RetentionPolicy.CLASS)
+@interface CheckReturnValue {
+}
diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 5893b13086..ceb4a72997 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -2001,6 +2001,7 @@ public static <T> T spy(Class<T> classToSpy) {
* @return OngoingStubbing object used to stub fluently.
* <strong>Do not</strong> create a reference to this returned object.
*/
+ @CheckReturnValue
public static <T> OngoingStubbing<T> when(T methodCall) {
return MOCKITO_CORE.when(methodCall);
}
@@ -2032,6 +2033,7 @@ public static <T> OngoingStubbing<T> when(T methodCall) {
* @param mock to be verified
* @return mock object itself
*/
+ @CheckReturnValue
public static <T> T verify(T mock) {
return MOCKITO_CORE.verify(mock, times(1));
}
@@ -2058,6 +2060,7 @@ public static <T> T verify(T mock) {
*
* @return mock object itself
*/
+ @CheckReturnValue
public static <T> T verify(T mock, VerificationMode mode) {
return MOCKITO_CORE.verify(mock, mode);
}
@@ -2177,6 +2180,7 @@ public static void verifyZeroInteractions(Object... mocks) {
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
+ @CheckReturnValue
public static Stubber doThrow(Throwable... toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
@@ -2199,6 +2203,7 @@ public static Stubber doThrow(Throwable... toBeThrown) {
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
+ @CheckReturnValue
public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
@@ -2225,6 +2230,7 @@ public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
*/
// Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
@SuppressWarnings ({"unchecked", "varargs"})
+ @CheckReturnValue
public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
}
@@ -2261,6 +2267,7 @@ public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? ext
* @return stubber - to select a method for stubbing
* @since 1.9.5
*/
+ @CheckReturnValue
public static Stubber doCallRealMethod() {
return MOCKITO_CORE.stubber().doCallRealMethod();
}
@@ -2287,6 +2294,7 @@ public static Stubber doCallRealMethod() {
* @param answer to answer when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
+ @CheckReturnValue
public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.stubber().doAnswer(answer);
}
@@ -2329,6 +2337,7 @@ public static Stubber doAnswer(Answer answer) {
*
* @return stubber - to select a method for stubbing
*/
+ @CheckReturnValue
public static Stubber doNothing() {
return MOCKITO_CORE.stubber().doNothing();
}
@@ -2379,6 +2388,7 @@ public static Stubber doNothing() {
* @param toBeReturned to be returned when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
+ @CheckReturnValue
public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned);
}
@@ -2433,6 +2443,7 @@ public static Stubber doReturn(Object toBeReturned) {
* @since 2.1.0
*/
@SuppressWarnings({"unchecked", "varargs"})
+ @CheckReturnValue
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
}
| null | train | train | 2017-10-22T16:21:02 | "2017-06-16T09:01:04Z" | tkruse | train |
mockito/mockito/1070_1229 | mockito/mockito | mockito/mockito/1070 | mockito/mockito/1229 | [
"timestamp(timedelta=0.0, similarity=0.9091651390028943)",
"keyword_pr_to_issue"
] | e10c5409e460c3ecd6b2ef9513a0b3802351d85f | b8c2811276a3cf8f1eb8b81c5f785369046c3d77 | [] | [
"Maybe it would be better to iterate over subprojects and depend on \"test\" task (by a type or by a name) and use that list to generate also files to include (istead of looking for `*.exec` file)?\r\n\r\nIt would be even less fragile to have an optional exclusions for specific modules if needed.",
"Do we really need it to be defined in every module separately? Maybe you could use the list of subprojects (I proposed above) to do it in a more generic way?",
"I tried to make that work, but ran into problems. First of all, not every subproject has this test task. Therefore, I had to somehow filter the correct project. However, if you do something like below Gradle will throw an exception:\r\n\r\n```groovy\r\nsubprojects {\r\n if (it.getTaskByName('test')\r\n dependsOn \"${it.path}:test\"\r\n}\r\n```\r\n\r\nMy Groovy is lackluster and I just couldn't get this to work.",
"Yes, because only this task will generate the correct `*.exec` files in `build/` which then have to be picked up by the root project. If you have a better solution, feel free to push to this PR!",
"I will try to tune that tomorrow. Stay tuned.",
"I'm curious why we need to specify the tool version. Can you get rid of the version and see if it works? If we bump Gradle, we generally want the best jacoco version that works with given Gradle version. Let's try if we can rely on the default.\r\n\r\nNot blocking for this PR.",
"Does this work? I suspect we can run into problems because we cannot guarantee that at this point subproject has any source sets (the sequence / order in which Gradle configures projects).",
"I looked at the current \"mockitoCoverage\" implementation and I think that the change is a bit more involved. For example, we should also include ```classDirectories``` from the subprojects.",
"Let's avoid code duplication. I'm sure @szpak will figure this out.",
"Let's avoid hardcoding the test task names and coupling with subprojects. \r\n\r\nSomething like that should work (please note that I have not tested it :):\r\n\r\n```Gradle\r\ntask mockitoCoverage(...)\r\n\r\nallprojects {\r\n plugins.withId(\"java\") {\r\n apply plugin: \"jacoco\"\r\n //configure jacoco version, etc.\r\n\r\n mockitoCoverage.dependsOn \"test\"\r\n //configure other parts of jacoco plugin or the mockitoCoverage task\r\n }\r\n}\r\n```",
"Gradle usually has outdated version of JaCoCo by default (see https://github.com/gradle/gradle/commit/987d86f36a05b9090ab498dfbe77fe3dbc0f8e39 - 6 months after the release of 0.7.9 - thanks to the PR from the JaCoCo committer). In addition Mockito tended (in the past) to do not use the newest Gradle version.\r\nTherefore, it's redundant right now, but it can be needed once 0.7.10 is released. As a result, having it just one place would be probably enough to be able to uncomment one line in `coverage.gradle`.",
"Sure, if not I will ask the Gradle 1.x core developer for help :).\r\n\r\nWiP.",
"It was more tricky and took much more time that I expected... I did it in 3 somehow different ways and in the end I left the simplest version (with one file gathering all coverage data). Feel free to comment and to enhance.",
"@mockitoguy Do you have a good idea how to get rid of it without changing the main Gradle configuration in Mockito to much?\r\n\r\nSubtasks doesn't have `Test` tasks enhances automatically due to the applying order.",
"Not sure. I don't fully see the problem with ordering.",
"It looks somewhat confusing that \"allprojects\" section is within the body of the \"mockitoCoverage\" task configuration.",
"Let's get rid of \"for client\" - I don't even know what it means :)",
"Does it actually generate html and xml? In the past the task could only generate only one kind of report.",
"Is this line needed?",
"It's caused by the fact that the root project in Mockito is not an empty parent project, but mockito-core in fact (which also generates coverage data).",
"According [documentation](https://docs.gradle.org/current/userguide/jacoco_plugin.html#sec:jacoco_specific_task_configuration):\r\n> The JaCoCo plugin adds a JacocoTaskExtension extension to all tasks of type Test. This extension allows the configuration of the JaCoCo specific properties of the test task.\r\n\r\nIt doesn't happen for subprojects here. I needed to call \"applyTo\" manually. I didn't see it in multiprojects with \"normal\" empty parent/root project.",
"Yes, it is (it's enabled in the configuration)\r\n.\r\nFor me the HTML link is enough. I don't know why the the link do XML was introduced. @TimvdLippe do you remember?",
"Rather yes. There is:\r\n```\r\ndependencies {\r\n testCompile \"org.mockito:mockito-core:$version\"\r\n testCompile project(path: ':', configuration: 'testUtil')\r\n testCompile libraries.junit4\r\n testCompile libraries.assertj\r\n}\r\n```\r\nin that file below.",
"That is used by CodeCov afaik",
"Yes, but do they use also a link displayed in the console? :)",
"Oh in that manner. I doubt it, but does it harm by reporting it?",
"Should we also take into account the Kotlin projects, as they are also generating coverage?",
"The groovy/kotlin plugins applies the `java` plugin under the hood.",
"Ah okay :+1: "
] | "2017-10-27T14:14:32Z" | [
"enhancement",
"kotlin",
"please contribute"
] | Fix coverage for subprojects | In #1032, the new coverage was incorrectly tracked by jacoco. A quick search showed this TODO (https://github.com/mockito/mockito/blob/release/2.x/gradle/root/coverage.gradle#L3) that points out it is actually not generating coverage for subprojects. Would like to see this fixed! | [
"gradle/root/coverage.gradle",
"subprojects/extTest/extTest.gradle",
"subprojects/kotlinTest/kotlinTest.gradle"
] | [
"gradle/root/coverage.gradle",
"subprojects/extTest/extTest.gradle",
"subprojects/kotlinTest/kotlinTest.gradle"
] | [] | diff --git a/gradle/root/coverage.gradle b/gradle/root/coverage.gradle
index 9196ad2cd4..a0f0448562 100644
--- a/gradle/root/coverage.gradle
+++ b/gradle/root/coverage.gradle
@@ -1,15 +1,27 @@
-apply plugin: 'jacoco'
+//TODO: Standard JaCoCo coverage doesn't work in Android module
+task mockitoCoverage(type: JacocoReport) {
-// TODO later include subprojects, possible ideas https://gist.github.com/aalmiray/e6f54aa4b3803be0bcac
+ allprojects { currentProject ->
+ plugins.withId("java") {
+ mockitoCoverage.sourceSets currentProject.sourceSets.main
-jacoco {
- toolVersion = "0.7.9"
-}
+ apply plugin: "jacoco"
+
+ jacoco {
+ toolVersion = '0.7.9' //Gradle 4.2.1 uses 0.7.8 by default
-task mockitoCoverage(type: JacocoReport, dependsOn: "test") {
- executionData files("${buildDir}/jacoco/test.exec")
+ if (currentProject != rootProject) { //already automatically enhanced in mockito main project as "java" plugin was applied before
+ applyTo test
+ }
+ }
+
+ currentProject.tasks.withType(Test) { testTask ->
+ mockitoCoverage.dependsOn testTask
+ }
+ }
+ }
- sourceSets sourceSets.main
+ executionData(file("$buildDir/jacoco/test.exec"))
reports {
xml.enabled true
@@ -27,8 +39,8 @@ task mockitoCoverage(type: JacocoReport, dependsOn: "test") {
}
doLast {
- println "Jacoco report for client created: file://${reports.xml.destination.toURI().path}"
+ logger.lifecycle "Jacoco HTML created: file://${new File(reports.html.destination, "index.html").toURI().path}"
}
}
-task coverageReport(dependsOn: ["test", "mockitoCoverage"]) {}
+task coverageReport(dependsOn: ["mockitoCoverage"]) {}
diff --git a/subprojects/extTest/extTest.gradle b/subprojects/extTest/extTest.gradle
index cd827bcc2f..35d2b9863d 100644
--- a/subprojects/extTest/extTest.gradle
+++ b/subprojects/extTest/extTest.gradle
@@ -1,3 +1,5 @@
+apply from: "$rootDir/gradle/dependencies.gradle"
+
apply plugin: 'java'
description = "End-to-end tests for Mockito and its extensions."
diff --git a/subprojects/kotlinTest/kotlinTest.gradle b/subprojects/kotlinTest/kotlinTest.gradle
index b3a22ae929..d7d349951e 100644
--- a/subprojects/kotlinTest/kotlinTest.gradle
+++ b/subprojects/kotlinTest/kotlinTest.gradle
@@ -18,4 +18,3 @@ dependencies {
testCompile 'org.jetbrains.kotlin:kotlin-stdlib:1.1.4-3'
testCompile 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.18'
}
-
| null | test | train | 2017-10-22T16:21:02 | "2017-05-05T12:38:36Z" | TimvdLippe | train |
mockito/mockito/1239_1242 | mockito/mockito | mockito/mockito/1239 | mockito/mockito/1242 | [
"timestamp(timedelta=0.0, similarity=0.969590801230008)",
"keyword_pr_to_issue"
] | b8c2811276a3cf8f1eb8b81c5f785369046c3d77 | ae314e5b41f947dc83d5b1e5ee268d289b61e837 | [
"Think it makes sense to add a check since we have it. Without it, the project will just always be inconsistent.",
"Absolutely +1. Thank you!"
] | [
"Coudn't we apply it automatically to all projects that apply Java plugin? Similar way it is done with JaCoCo - to do not miss another module once added.",
"Uh, yeah maybe. Not a Gradle expert, but I can give it a shot tomorrow!",
"Done. Please take a look :+1: ",
"Do we use that plugin to handle any other type of files than `.java` and `.groovy` (`.kt`?)? If not, maybe it would be good to narrow the scope to only submodules with code? It can be achieved the same way as with the coverage: `plugins.withId(\"java\") { ... }`.",
"Yes also any configuration or extra files. We can limit to Java projects, but I would rather check that all our files comply. Apparently we were missing quite some in total and the more we can catch, the better. WDYT?",
"If it's also for non source code files I'm ok with `allprojects` unconditionally."
] | "2017-11-03T12:23:46Z" | [] | Enable Checkstyle rule for checking existence of license headers | Whenever we add new files to the repository, we usually forget to add our license headers. This results in PRs such as #1227 where retroactively we add the license headers.
CheckStyle has a rule called [`Header`](http://checkstyle.sourceforge.net/config_header.html) which can enforce that we add our license header. I would propose to start enabling this rule to make sure all our source files comply to our licensing.
@mockito/core yay/nay? | [
"build.gradle",
"config/checkstyle/checkstyle.xml",
"doc/licenses/HEADER.txt",
"gradle/mockito-core/license.gradle",
"src/main/java/org/mockito/CheckReturnValue.java",
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidByteBuddyMockMaker.java",
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java",
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java"
] | [
"build.gradle",
"config/checkstyle/checkstyle.xml",
"config/checkstyle/java.header",
"doc/licenses/HEADER.txt",
"gradle/license.gradle",
"src/main/java/org/mockito/CheckReturnValue.java",
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidByteBuddyMockMaker.java",
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidLoadingStrategy.java",
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java"
] | [
"src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java",
"src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java",
"subprojects/extTest/src/test/java/org/mockitousage/plugins/stacktrace/MyStackTraceCleanerProvider.java",
"subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyMockMaker.java",
"subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyPluginSwitch.java",
"subprojects/inline/src/test/java/org/mockitoinline/FinalClassMockingTest.java",
"subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java",
"subprojects/inline/src/test/java/org/mockitoinline/StubbingLocationTest.java",
"subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/FunctionTest.kt",
"subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt",
"subprojects/testng/src/main/java/org/mockito/testng/MockitoAfterTestNGMethod.java",
"subprojects/testng/src/main/java/org/mockito/testng/MockitoBeforeTestNGMethod.java",
"subprojects/testng/src/main/java/org/mockito/testng/MockitoTestNGListener.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/ParentTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/SomeType.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectAnnotationUsage.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectStubbingSyntax.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java",
"subprojects/testng/src/test/java/org/mockitousage/testng/utils/FailureRecordingListener.java",
"subprojects/testng/src/test/resources/mockito-testng.xml"
] | diff --git a/build.gradle b/build.gradle
index 34b7d0fc3c..575662ecff 100644
--- a/build.gradle
+++ b/build.gradle
@@ -32,12 +32,12 @@ apply from: 'gradle/root/ide.gradle'
apply from: 'gradle/root/gradle-fix.gradle'
apply from: 'gradle/root/java6-compatibility.gradle'
apply from: 'gradle/java-library.gradle'
+apply from: 'gradle/license.gradle'
apply from: 'gradle/root/coverage.gradle'
apply from: 'gradle/mockito-core/inline-mock.gradle'
apply from: 'gradle/mockito-core/osgi.gradle'
apply from: 'gradle/mockito-core/javadoc.gradle'
-apply from: 'gradle/mockito-core/license.gradle'
apply from: 'gradle/mockito-core/testing.gradle'
apply from: 'gradle/dependencies.gradle'
diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml
index ea9a5320f5..b339c959c2 100644
--- a/config/checkstyle/checkstyle.xml
+++ b/config/checkstyle/checkstyle.xml
@@ -27,5 +27,9 @@
<property name="processJavadoc" value="true"/>
</module>
</module>
+ <module name="RegexpHeader">
+ <property name="headerFile" value="config/checkstyle/java.header"/>
+ <property name="fileExtensions" value="java"/>
+ </module>
</module>
diff --git a/config/checkstyle/java.header b/config/checkstyle/java.header
new file mode 100644
index 0000000000..3087970dfd
--- /dev/null
+++ b/config/checkstyle/java.header
@@ -0,0 +1,4 @@
+^/\*$
+^ \* Copyright \(c\) \d\d\d\d Mockito contributors$
+^ \* This program is made available under the terms of the MIT License.$
+^ \*/$
diff --git a/doc/licenses/HEADER.txt b/doc/licenses/HEADER.txt
index 9c1b1d3d76..23f5c49076 100644
--- a/doc/licenses/HEADER.txt
+++ b/doc/licenses/HEADER.txt
@@ -1,2 +1,2 @@
-Copyright (c) ${year} ${name}
-This program is made available under the terms of the MIT License.
\ No newline at end of file
+Copyright (c) ${year} Mockito contributors
+This program is made available under the terms of the MIT License.
diff --git a/gradle/license.gradle b/gradle/license.gradle
new file mode 100644
index 0000000000..f6eb52d899
--- /dev/null
+++ b/gradle/license.gradle
@@ -0,0 +1,16 @@
+def licenseHeaderFile = rootProject.file('doc/licenses/HEADER.txt')
+
+allprojects {
+ apply plugin: 'com.github.hierynomus.license'
+ license {
+ header = licenseHeaderFile
+ strictCheck = true
+ ignoreFailures = true
+ skipExistingHeaders = true
+ mapping {
+ java = 'SLASHSTAR_STYLE'
+ groovy = 'SLASHSTAR_STYLE'
+ }
+ ext.year = Calendar.getInstance().get(Calendar.YEAR)
+ }
+}
diff --git a/gradle/mockito-core/license.gradle b/gradle/mockito-core/license.gradle
deleted file mode 100644
index 5841ab2a37..0000000000
--- a/gradle/mockito-core/license.gradle
+++ /dev/null
@@ -1,14 +0,0 @@
-apply plugin: 'com.github.hierynomus.license'
-
-license {
- header = rootProject.file('doc/licenses/HEADER.txt')
- strictCheck = true
- ignoreFailures = true
- skipExistingHeaders = true
- mapping {
- java = 'SLASHSTAR_STYLE'
- groovy = 'SLASHSTAR_STYLE'
- }
- ext.year = Calendar.getInstance().get(Calendar.YEAR)
- ext.name = 'Mockito contributors'
-}
diff --git a/src/main/java/org/mockito/CheckReturnValue.java b/src/main/java/org/mockito/CheckReturnValue.java
index 42c7545bff..59bfc333fb 100644
--- a/src/main/java/org/mockito/CheckReturnValue.java
+++ b/src/main/java/org/mockito/CheckReturnValue.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito;
import java.lang.annotation.ElementType;
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 17473589b1..56ffcec0bb 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
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.android.internal.creation;
import org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker;
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 eeac19db28..600b9bc248 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
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.android.internal.creation;
import static org.mockito.internal.util.StringUtil.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 1e1dbb73d6..a79816c4f5 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
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.android.internal.creation;
import java.io.File;
| diff --git a/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java b/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java
index f6ee1d8575..51f23693bc 100644
--- a/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java
+++ b/src/test/java/org/mockitousage/bugs/GenericsMockitoAnnotationsTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.bugs;
import org.junit.Before;
diff --git a/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java b/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
index 146888c92f..f0e42ee188 100644
--- a/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationAfterDelayTest.java
@@ -1,5 +1,6 @@
/*
- * Copyright (c) 2007 Mockito contributors This program is made available under the terms of the MIT License.
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
*/
package org.mockitousage.verification;
diff --git a/subprojects/extTest/src/test/java/org/mockitousage/plugins/stacktrace/MyStackTraceCleanerProvider.java b/subprojects/extTest/src/test/java/org/mockitousage/plugins/stacktrace/MyStackTraceCleanerProvider.java
index cd9ed4039b..951c149d66 100644
--- a/subprojects/extTest/src/test/java/org/mockitousage/plugins/stacktrace/MyStackTraceCleanerProvider.java
+++ b/subprojects/extTest/src/test/java/org/mockitousage/plugins/stacktrace/MyStackTraceCleanerProvider.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.plugins.stacktrace;
import org.mockito.exceptions.stacktrace.StackTraceCleaner;
diff --git a/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyMockMaker.java b/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyMockMaker.java
index 4476d08356..0a8ea162bc 100644
--- a/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyMockMaker.java
+++ b/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyMockMaker.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.plugins.switcher;
import org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker;
diff --git a/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyPluginSwitch.java b/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyPluginSwitch.java
index 4c918e70e1..eb4423f361 100644
--- a/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyPluginSwitch.java
+++ b/subprojects/extTest/src/test/java/org/mockitousage/plugins/switcher/MyPluginSwitch.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.plugins.switcher;
import org.mockito.plugins.PluginSwitch;
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/FinalClassMockingTest.java b/subprojects/inline/src/test/java/org/mockitoinline/FinalClassMockingTest.java
index 9803d4b167..0f2ea78288 100644
--- a/subprojects/inline/src/test/java/org/mockitoinline/FinalClassMockingTest.java
+++ b/subprojects/inline/src/test/java/org/mockitoinline/FinalClassMockingTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitoinline;
import org.junit.Test;
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java b/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java
index a3feb34c67..19526db2a9 100644
--- a/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java
+++ b/subprojects/inline/src/test/java/org/mockitoinline/PluginTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitoinline;
import org.junit.Test;
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StubbingLocationTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StubbingLocationTest.java
index 050298dfce..8476006425 100644
--- a/subprojects/inline/src/test/java/org/mockitoinline/StubbingLocationTest.java
+++ b/subprojects/inline/src/test/java/org/mockitoinline/StubbingLocationTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitoinline;
import java.util.Collections;
diff --git a/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/FunctionTest.kt b/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/FunctionTest.kt
index 944263c7e3..c509648c9a 100644
--- a/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/FunctionTest.kt
+++ b/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/FunctionTest.kt
@@ -1,3 +1,7 @@
+/**
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.kotlin
import org.junit.Test
diff --git a/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt b/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt
index 191bc84c25..bfef4071e4 100644
--- a/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt
+++ b/subprojects/kotlinTest/src/test/kotlin/org/mockito/kotlin/SuspendTest.kt
@@ -1,3 +1,7 @@
+/**
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.kotlin
import kotlinx.coroutines.experimental.runBlocking
diff --git a/subprojects/testng/src/main/java/org/mockito/testng/MockitoAfterTestNGMethod.java b/subprojects/testng/src/main/java/org/mockito/testng/MockitoAfterTestNGMethod.java
index 257e068040..4e24e354b9 100644
--- a/subprojects/testng/src/main/java/org/mockito/testng/MockitoAfterTestNGMethod.java
+++ b/subprojects/testng/src/main/java/org/mockito/testng/MockitoAfterTestNGMethod.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.testng;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/main/java/org/mockito/testng/MockitoBeforeTestNGMethod.java b/subprojects/testng/src/main/java/org/mockito/testng/MockitoBeforeTestNGMethod.java
index b122a8a093..a69db36221 100644
--- a/subprojects/testng/src/main/java/org/mockito/testng/MockitoBeforeTestNGMethod.java
+++ b/subprojects/testng/src/main/java/org/mockito/testng/MockitoBeforeTestNGMethod.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.testng;
import org.mockito.Captor;
diff --git a/subprojects/testng/src/main/java/org/mockito/testng/MockitoTestNGListener.java b/subprojects/testng/src/main/java/org/mockito/testng/MockitoTestNGListener.java
index 370d106cab..f3d809c4c1 100644
--- a/subprojects/testng/src/main/java/org/mockito/testng/MockitoTestNGListener.java
+++ b/subprojects/testng/src/main/java/org/mockito/testng/MockitoTestNGListener.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockito.testng;
import org.testng.IInvokedMethod;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java
index fb4e7bd166..ae161e3c30 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/AnnotatedFieldsShouldBeInitializedByMockitoTestNGListenerTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.ArgumentCaptor;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java
index 79c3071408..193dbfa610 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/CaptorAnnotatedFieldShouldBeClearedTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.ArgumentCaptor;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java
index 76095f3af4..2093549f51 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/ConfigurationMethodTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java
index 5cbe4fc20d..7992980cce 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/DontResetMocksIfNoListenerTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java
index a84bfacb31..f2ebc8712b 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/EnsureMocksAreInitializedBeforeBeforeClassMethodTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java
index 53702190f2..5b2edb5328 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/InitializeChildTestWhenParentHasListenerTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java
index 8660b1893f..cc7d40aba0 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/MockFieldsShouldBeResetBetweenTestMethodsTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.InjectMocks;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/ParentTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/ParentTest.java
index 870d31b3a9..02ac09d850 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/ParentTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/ParentTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java
index e9dd50a83a..bc4a3d9032 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/ResetMocksInParentTestClassTooTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.testng.annotations.Test;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/SomeType.java b/subprojects/testng/src/test/java/org/mockitousage/testng/SomeType.java
index 87bba41e7d..6a662a6082 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/SomeType.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/SomeType.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import java.util.List;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java
index 19cfa5abaa..41cb55409c 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/TestWithoutListenerShouldNotInitializeAnnotatedFieldsTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng;
import org.mockito.ArgumentCaptor;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectAnnotationUsage.java b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectAnnotationUsage.java
index 1d4844ab14..610156cbb5 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectAnnotationUsage.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectAnnotationUsage.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng.failuretests;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectStubbingSyntax.java b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectStubbingSyntax.java
index 50f166b9e6..919bfba0ba 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectStubbingSyntax.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseIncorrectStubbingSyntax.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng.failuretests;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.java b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.java
index 8d0e05540c..83261d8c58 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng.failuretests;
import org.mockito.Mock;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java
index 0870b9bb72..836a12a270 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/failuretests/TestNGShouldFailWhenMockitoListenerFailsTest.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng.failuretests;
import org.mockito.exceptions.base.MockitoException;
diff --git a/subprojects/testng/src/test/java/org/mockitousage/testng/utils/FailureRecordingListener.java b/subprojects/testng/src/test/java/org/mockitousage/testng/utils/FailureRecordingListener.java
index 01763d7029..46f0d713f2 100644
--- a/subprojects/testng/src/test/java/org/mockitousage/testng/utils/FailureRecordingListener.java
+++ b/subprojects/testng/src/test/java/org/mockitousage/testng/utils/FailureRecordingListener.java
@@ -1,3 +1,7 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
package org.mockitousage.testng.utils;
import org.testng.IConfigurationListener;
diff --git a/subprojects/testng/src/test/resources/mockito-testng.xml b/subprojects/testng/src/test/resources/mockito-testng.xml
index 68e4a36abd..cab389cbca 100644
--- a/subprojects/testng/src/test/resources/mockito-testng.xml
+++ b/subprojects/testng/src/test/resources/mockito-testng.xml
@@ -1,4 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ Copyright (c) 2017 Mockito contributors
+ This program is made available under the terms of the MIT License.
+
+-->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Mockito TestNG usage" parallel="none">
<test verbose="1" name="Mockito TestNG Integration" annotations="JDK">
| train | train | 2017-11-02T11:57:10 | "2017-11-02T15:10:19Z" | TimvdLippe | train |
mockito/mockito/1254_1257 | mockito/mockito | mockito/mockito/1254 | mockito/mockito/1257 | [
"keyword_pr_to_issue"
] | 442277f4647ebf24930132b080b9971d3eef9e63 | dad7ca814ea76937b1c9af35f02ad97ba5f9b3c5 | [
"I'm observing a similar issue. Only happens with `mockito-inline`. Don't have time right now to distill the affected tests into a minimal reproduction case. Maybe @raphw has a hunch.",
"Alright, decided to look for a minimal reproduction case after all. This is what I came up with:\r\n```java\r\npackage com.example\r\n\r\nimport static org.mockito.ArgumentMatchers.eq;\r\nimport static org.mockito.Mockito.spy;\r\nimport static org.mockito.Mockito.verify;\r\n\r\nimport org.testng.annotations.Test;\r\n\r\npublic final class MockitoIssue1254Test {\r\n @Test\r\n public void test() {\r\n Dummy d = spy(new Dummy());\r\n d.foo();\r\n verify(d).bar(eq(\"baz\"));\r\n }\r\n\r\n static class Dummy {\r\n public void foo() {\r\n bar(\"baz\");\r\n }\r\n\r\n // Also fails if public.\r\n void bar(String s) {}\r\n }\r\n}\r\n```\r\n\r\nCauses:\r\n```\r\nWanted but not invoked:\r\ndummy.bar(\"baz\");\r\n-> at com.example.MockitoIssue1254Test$Dummy.bar(MockitoIssue1254Test.java:23)\r\n\r\nHowever, there was exactly 1 interaction with this mock:\r\ndummy.foo();\r\n-> at com.example.MockitoIssue1254Test.test(MockitoIssue1254Test.java:13)\r\n```\r\n\r\nThis test does pass with Mockito 2.11.0. It also passes with Mockito 2.12.0, provided `mockito-inline` is disabled.",
"Probably another error in the logic for self-invocation detection. I will have a look!",
"Ok, this was just me forgetting how my implementation intially worked. I fixed it locally and will push a fix soon.",
"Same for mocked methods on Spy. On 2.12.0 real method is called.",
"When is this going to be on Maven Central?",
"We could trigger a new release, @TimvdLippe, would you find some time?",
"Yeah I can try it tomorrow :)\n\nOp di 5 dec. 2017 om 20:55 schreef Rafael Winterhalter <\nnotifications@github.com>:\n\n> We could trigger a new release, @TimvdLippe\n> <https://github.com/timvdlippe>, would you find some time?\n>\n> —\n> You are receiving this because you were mentioned.\n>\n>\n> Reply to this email directly, view it on GitHub\n> <https://github.com/mockito/mockito/issues/1254#issuecomment-349422044>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AFrDb3sUMqw_c_exn9HiMDi5ls1QmDHdks5s9Z_LgaJpZM4QZVVK>\n> .\n>\n",
"Version 2.13.0 should be published and available soon in Maven Central!\r\n\r\nP.S. @mockitoguy the `[ci maven-central-release]` was working flawlessly :tada: ",
"Danke! Bedankt! Many thanks!",
"Can confirm that finally our suite of 13+ K Kotlin tests work after fixing #1183 and this one ✨ Thanks!",
">P.S. @mockitoguy the [ci maven-central-release] was working flawlessly 🎉\r\n\r\nAwesome! Thank you for pushing out the version!"
] | [
"With the issue fixed, this comment is no longer true. Would leave it out to avoid head-scratching.",
"Indeed, poorly copy-pasted. Thanks.",
"Can you add a code comment explaining why we need this? Please make it thorough, it would be great to share understanding! :)",
"Can we make the message more actionable? Is there anything the user can do? File a ticket?",
"Nice test coverage!\r\n\r\nI'm wondering if we should rather put the inline tests in main mockito codebase. The use cases should work for every Mockito mock maker, inline or not. We do run all our tests with inline mock as far as I remember.",
"Do we? I would not recall that. If so, yes, we should probably move the class.",
"It is my library, I can add a method to get hold of the object. But I think we are safe here as we shade the code, no real danger here.",
"Added a comment.",
"Nevermind, we do of course inline it and can therefore change the code.",
"^ The comment is still there ;)."
] | "2017-11-13T21:30:41Z" | [
"bug"
] | Wanted but not invoked on 2.12.0, but not on 2.11.0 | After updating Mockito from 2.11.0 to 2.12.0 the following test fails with `Wanted but not invoked`.
The weird thing is this happens only when running tests using Gradle. Android Studio runs the same test as successful. Just like #1183.
```java
package package.redacted;
import org.junit.Test;
import org.mockito.Mockito;
public class ViewModelTest {
class View {
private Runnable actionCallback = null;
void callAction(Runnable callback) {
actionCallback = callback;
}
void simulateActionCalled() {
if (actionCallback != null) {
actionCallback.run();
}
}
void showResult() {
}
}
class ViewModel {
public ViewModel(final View view) {
view.callAction(new Runnable() {
@Override
public void run() {
view.showResult();
}
});
}
}
@Test public void test() {
View view = Mockito.spy(new View());
ViewModel viewModel = new ViewModel(view);
view.simulateActionCalled();
Mockito.verify(view).showResult();
}
}
```
```
Wanted but not invoked:
view.showResult();
-> at package.redacted.ViewModelTest$View.showResult(ViewModelTest.java:22)
However, there were exactly 2 interactions with this mock:
view.callAction(
package.redacted.ViewModelTest$ViewModel$1@26645040
);
-> at package.redacted.ViewModelTest$ViewModel.<init>(ViewModelTest.java:28)
view.simulateActionCalled();
-> at package.redacted.ViewModelTest.test(ViewModelTest.java:41)
at package.redacted.ViewModelTest$View.showResult(ViewModelTest.java:22)
at package.redacted.ViewModelTest.test(ViewModelTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:108)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
``` | [
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java",
"src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java",
"src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java"
] | [
"subprojects/inline/src/test/java/org/mockitoinline/RecursionTest.java",
"subprojects/inline/src/test/java/org/mockitoinline/SuperCallTest.java"
] | 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 7d9f347f6c..02882a2274 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
@@ -107,18 +107,20 @@ public Callable<?> handle(Object instance, Method origin, Object[] arguments) th
return new ReturnValueWrapper(interceptor.doIntercept(instance,
origin,
arguments,
- realMethod,
+ realMethod,
new LocationImpl(t)));
}
@Override
public boolean isMock(Object instance) {
- return interceptors.containsKey(instance);
+ // We need to exclude 'interceptors.target' explicitly to avoid a recursive check on whether
+ // the map is a mock object what requires reading from the map.
+ return instance != interceptors.target && interceptors.containsKey(instance);
}
@Override
public boolean isMocked(Object instance) {
- return !selfCallInfo.isSelfInvocation(instance) && isMock(instance);
+ return selfCallInfo.checkSuperCall(instance) && isMock(instance);
}
@Override
@@ -160,12 +162,8 @@ public Object invoke() throws Throwable {
if (!Modifier.isPublic(origin.getDeclaringClass().getModifiers() & origin.getModifiers())) {
origin.setAccessible(true);
}
- Object previous = selfCallInfo.replace(instance);
- try {
- return tryInvoke(origin, instance, arguments);
- } finally {
- selfCallInfo.set(previous);
- }
+ selfCallInfo.set(instance);
+ return tryInvoke(origin, instance, arguments);
}
}
@@ -252,14 +250,19 @@ public Object call() {
private static class SelfCallInfo extends ThreadLocal<Object> {
- Object replace(Object instance) {
+ Object replace(Object value) {
Object current = get();
- set(instance);
+ set(value);
return current;
}
- boolean isSelfInvocation(Object instance) {
- return get() == instance;
+ boolean checkSuperCall(Object value) {
+ if (value == get()) {
+ set(null);
+ return false;
+ } else {
+ return true;
+ }
}
}
diff --git a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
index c1476936e2..b411a73a9d 100644
--- a/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
+++ b/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
@@ -26,7 +26,7 @@ public class WeakConcurrentMap<K, V> extends ReferenceQueue<K> implements Runnab
private static final AtomicLong ID = new AtomicLong();
- final ConcurrentMap<WeakKey<K>, V> target;
+ public final ConcurrentMap<WeakKey<K>, V> target;
private final Thread thread;
| diff --git a/subprojects/inline/src/test/java/org/mockitoinline/RecursionTest.java b/subprojects/inline/src/test/java/org/mockitoinline/RecursionTest.java
new file mode 100644
index 0000000000..2a4494e03e
--- /dev/null
+++ b/subprojects/inline/src/test/java/org/mockitoinline/RecursionTest.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitoinline;
+
+import org.junit.Test;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import static org.mockito.Mockito.spy;
+
+public class RecursionTest {
+
+ @Test
+ public void testMockConcurrentHashMap() {
+ ConcurrentMap<String, String> map = spy(new ConcurrentHashMap<String, String>());
+ map.putIfAbsent("a", "b");
+ }
+}
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/SuperCallTest.java b/subprojects/inline/src/test/java/org/mockitoinline/SuperCallTest.java
new file mode 100644
index 0000000000..1fe81969d4
--- /dev/null
+++ b/subprojects/inline/src/test/java/org/mockitoinline/SuperCallTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitoinline;
+
+import org.junit.Test;
+
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+public final class SuperCallTest {
+
+ @Test
+ public void testSuperMethodCall() {
+ Dummy d = spy(new Dummy());
+ d.foo();
+ verify(d).bar(eq("baz"));
+ }
+
+ static class Dummy {
+
+ public void foo() {
+ bar("baz");
+ }
+
+ // Also fails if public.
+ void bar(String s) {
+ return;
+ }
+ }
+}
| test | train | 2017-11-21T15:33:59 | "2017-11-10T10:07:26Z" | arturdryomov | train |
mockito/mockito/1067_1258 | mockito/mockito | mockito/mockito/1067 | mockito/mockito/1258 | [
"keyword_pr_to_issue"
] | 907e3de8a47c3733220c1ebf58741945c21df899 | cd5265ac9c1bc0e7b30f5f8e28c6d342f7451ab8 | [
"It seems to me as if you are defining circular class loading hierarchies. With Mockito 2, we are applying more fine grained locking to improve concurrency. The difference is displayed in the stack trace where `findOrInsert` aquires a lock for the class loader of the mock class before creating a mock. The previous solution always aquired a global lock what made it impossible to create to mock classes concurrently.\r\n\r\nThe relevant part:\r\n\r\n```\r\nat java.lang.ClassLoader.loadClass(ClassLoader.java:404)\r\n- waiting to lock <0x00000007959e4a78> (a sbt.classpath.ClasspathUtilities$$anon$1)\r\nat java.lang.ClassLoader.loadClass(ClassLoader.java:411)\r\n- locked <0x0000000795a868e8> (a sbt.classpath.ClasspathFilter)\r\n\t\r\nat java.lang.ClassLoader.loadClass(ClassLoader.java:404)\r\n- waiting to lock <0x0000000795a868e8> (a sbt.classpath.ClasspathFilter)\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)\r\n- locked <0x00000007959e4a78> (a sbt.classpath.ClasspathUtilities$$anon$1)\r\n```\r\n\r\nHow can it be that `sbt.classpath.ClasspathFilter` delegates to `sbt.classpath.ClasspathUtilities$$anon$1` where the latter apparently also reqires locking the former? Class loaders should only be used in strict hierarchies.",
"So both Maps are abstract, I'll try mocking concrete implementations. That might have caused the classloaders to kick in. I try to rewrite some of the tests to use specific implementations instead of abstract classes, but for i.e. ImmutableMap that's gonna be difficult as far as I can see.\r\n\r\nedit:\r\nSwitched to a concrete Map, just deadlocks somewhere else now, while mocking a Finagle Service[Request, Response] and a simple trait, same locks as before though.\r\n\r\n```\r\nFound one Java-level deadlock:\r\n=============================\r\n\"Timer-0\":\r\n waiting to lock monitor 0x00007f4d08002a48 (object 0x00000000c2857fb8, a sbt.classpath.ClasspathUtilities$$anon$1),\r\n which is held by \"pool-9-thread-6-ScalaTest-running-BRequestFilterSpec\"\r\n\"pool-9-thread-6-ScalaTest-running-BRequestFilterSpec\":\r\n waiting to lock monitor 0x00007f4d34003f08 (object 0x00000000c2857f60, a sbt.classpath.ClasspathFilter),\r\n which is held by \"pool-9-thread-7-ScalaTest-running-JFilterSpec\"\r\n\"pool-9-thread-7-ScalaTest-running-JFilterSpec\":\r\n waiting to lock monitor 0x00007f4d08002a48 (object 0x00000000c2857fb8, a sbt.classpath.ClasspathUtilities$$anon$1),\r\n which is held by \"pool-9-thread-6-ScalaTest-running-BRequestFilterSpec\"\r\n```",
"I've run into this same problem recently as well and my jstack was identical to the OP's. I've started playing around with the mockito versions and I'm not sure if this helps, but using mockito 2.6.6 in my tests didn't result in a deadlock, while using 2.6.7+ did result in deadlock.",
"Maybe we need to add a property that can be enabled to avoid the more fine-grained locking for the type cache. I would still like to know what is causing this as I even stress-tested the cache lock but I cannot reproduce the locking.\r\n\r\nIs there any project that I can build that reliably reproduces this?",
"I'm not sure if it's the same problem but I got similar deadlock after specs2 update:\r\n```\r\n17:57:32 \tat java.lang.ClassLoader.loadClass(ClassLoader.java:404)\r\n17:57:32 \t- waiting to lock <0x00000000d7fda228> (a java.lang.Object)\r\n17:57:32 \tat sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)\r\n17:57:32 \tat java.lang.ClassLoader.loadClass(ClassLoader.java:357)\r\n17:57:32 \tat java.lang.Class.getDeclaredMethods0(Native Method)\r\n17:57:32 \tat java.lang.Class.privateGetDeclaredMethods(Class.java:2701)\r\n17:57:32 \tat java.lang.Class.getDeclaredMethods(Class.java:1975)\r\n17:57:32 \tat net.bytebuddy.description.method.MethodList$ForLoadedMethods.<init>(MethodList.java:90)\r\n17:57:32 \tat net.bytebuddy.description.type.TypeDescription$ForLoadedType.getDeclaredMethods(TypeDescription.java:7232)\r\n17:57:32 \tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.getDeclaredMethods(TypeDescription.java:3349)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:576)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.analyze(MethodGraph.java:537)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.doAnalyze(MethodGraph.java:573)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$Default.compile(MethodGraph.java:508)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.MethodGraph$Compiler$AbstractBase.compile(MethodGraph.java:408)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.MethodRegistry$Default.prepare(MethodRegistry.java:418)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:162)\r\n17:57:32 \tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:155)\r\n17:57:32 \tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2560)\r\n17:57:32 \tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2662)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n17:57:32 \tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)\r\n17:57:32 \tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)\r\n17:57:32 \tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)\r\n17:57:32 \t- locked <0x0000000080591100> (a sun.misc.Launcher$AppClassLoader)\r\n17:57:32 \tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n17:57:32 \tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n17:57:32 \tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n17:57:32 \tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)\r\n17:57:32 \tat org.mockito.Mockito.mock(Mockito.java:1729)\r\n17:57:32 \tat org.mockito.Mockito.mock(Mockito.java:1642)\r\n17:57:32 \tat org.specs2.mock.MockitoMocker$class.mock(MockitoMocker.scala:21)\r\n17:57:32 \tat org.specs2.mock.mockito.TheMockitoMocker$$anon$1.mock(TheMockitoMocker.scala:8)\r\n17:57:32 \tat org.specs2.mock.mockito.MocksCreation$class.mock(MocksCreation.scala:18)\r\n```",
"@raphw \r\n> Is there any project that I can build that reliably reproduces this?\r\n\r\nThis seems to be happening for every travis build for https://github.com/lucidsoftware/xtract\r\n\r\nHowever, it doesn't happen when I build locally.\r\n\r\nI was able to reproduce by building it in the travisci/ci-garnet:packer-1512502276-986baf0 docker image. Which is how I was able to get a thread dump and figure out that this is a likely cause.\r\n\r\nNow that I have identified what the problem probably is, I'll try to fix future builds, but a commit id that is broken is 1939ab6798c974e4238439d04ba54a71ece5c31c.\r\n\r\nFrom the thread dump, I think the applicable code is:\r\n\r\n```scala\r\n private class PureXmlReader[T](result: T) extends XmlReader[T] {\r\n def read(elem: scala.xml.NodeSeq): ParseResult[T] = ParseSuccess(result)\r\n }\r\n\r\n private class PartialSuccessXmlReader[T](result: T, errors: Seq[ParseError]) extends XmlReader[T] {\r\n def read(elem: scala.xml.NodeSeq): ParseResult[T] = PartialParseSuccess(result, errors)\r\n }\r\n\r\n def successXmlReader[T](result: T): XmlReader[T] =\r\n spy(new PureXmlReader(result))\r\n\r\n def partialSuccessXmlReader[T](result: T, errors: Seq[ParseError]): XmlReader[T] =\r\n spy(new PartialSuccessXmlReader[T](result, errors))\r\n```\r\n\r\nIt seems successXmlReader and partialSuccessXmlReader are being called simultaneously, and creating the spies concurrently results in a deadlock. The fact that both PureXmlReader and PartialSuccessXmlReader extend XmlReader is suspicious.\r\n\r\nI can give you the full thread dump if you want, but it is pretty similar to the original post.",
"In my case I had to fix it by adding `sequential` to the Specification to preven examples from being executed in parallel.",
"Hey guys, we're planning to merge the fix soon. Thank you for patience and reporting another use case here!"
] | [
"@raphw, can we lock always using BOOTSTRAP_LOCK?\r\n\r\nIn JVM that runs tests, we have one instance of BOOTSTRAP_LOCK and (typically) one instance of the classloader. If using classloader is a performance tweak, do we have an evidence how much value it adds? Also, the lock is only used for \"new\" classes (not yet in cache). I am not convinced using \"classloader\" as monitor adds value.\r\n\r\nIt is a best practice to always use internal objects as synchronization monitors (private final Object). This way, nobody else will use that object for monitoring and we're safe from deadlocks.\r\n\r\nI'm not a fan of adding a system property to control this. It does not help with user experience because the user is impacted by a hanging build. After some googling, the user might be able to find an answer or he needs to reach out to us to learn about the property. But then what - he needs to remember to use the property in codebases that are exposed to this problem? Also, a system property is yet another method to configure Mockito - let's limit the various ways Mockito can be configured.\r\n\r\nHope you don't mind me complaining :) I'm super grateful you debugged this issue and offered a solution! For Mockito, it's best if we keep things simple, add new configuration options only when we really need to, and strive for great user experience."
] | "2017-11-13T21:31:29Z" | [] | Deadlock after upgrading to Mockito 2 and parallel tests execution | I updated Mockito and ScalaTest today from ScalaTest 2.x and Mockito 1.x and my tests suddenly froze in SBT (not in IntelliJ). After some playing around, I noticed every test class by itself passes and when I disabled running tests in parallel in SBT, the tests would work again.
I used jstack and came across this deadlock:
```
Found one Java-level deadlock:
=============================
"pool-9-thread-10-ScalaTest-running-ApiKeyVerificationFilterSpec":
waiting to lock monitor 0x00007fea6f039538 (object 0x00000007959e4a78, a sbt.classpath.ClasspathUtilities$$anon$1),
which is held by "pool-9-thread-2-ScalaTest-running-BRequestFilterSpec"
"pool-9-thread-2-ScalaTest-running-BRequestFilterSpec":
waiting to lock monitor 0x00007fea70e95548 (object 0x0000000795a868e8, a sbt.classpath.ClasspathFilter),
which is held by "pool-9-thread-10-ScalaTest-running-ApiKeyVerificationFilterSpec"
Java stack information for the threads listed above:
===================================================
"pool-9-thread-10-ScalaTest-running-ApiKeyVerificationFilterSpec":
at java.lang.ClassLoader.loadClass(ClassLoader.java:404)
- waiting to lock <0x00000007959e4a78> (a sbt.classpath.ClasspathUtilities$$anon$1)
at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
- locked <0x0000000795a868e8> (a sbt.classpath.ClasspathFilter)
at sbt.classpath.ClasspathFilter.loadClass(ClassLoaders.scala:59)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at net.bytebuddy.dynamic.loading.MultipleParentClassLoader.loadClass(MultipleParentClassLoader.java:68)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at sun.reflect.GeneratedSerializationConstructorAccessor35.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
at org.mockito.internal.creation.instance.ObjenesisInstantiator.newInstance(ObjenesisInstantiator.java:18)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:47)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
at org.mockito.Mockito.mock(Mockito.java:1729)
at org.mockito.Mockito.mock(Mockito.java:1642)
at org.scalatest.mockito.MockitoSugar$class.mock(MockitoSugar.scala:73)
at com.b.n.filter.ApiKeyVerificationFilterSpec.mock(ApiKeyVerificationFilterSpec.scala:25)
at com.b.n.filter.ApiKeyVerificationFilterSpec$ApiKeyFetchSetup$class.$init$(ApiKeyVerificationFilterSpec.scala:77)
at com.b.n.filter.ApiKeyVerificationFilterSpec$$anonfun$15$$anon$11.<init>(ApiKeyVerificationFilterSpec.scala:80)
at com.b.n.filter.ApiKeyVerificationFilterSpec$$anonfun$15.apply(ApiKeyVerificationFilterSpec.scala:80)
at com.b.n.filter.ApiKeyVerificationFilterSpec$$anonfun$15.apply(ApiKeyVerificationFilterSpec.scala:80)
at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
at org.scalatest.Transformer.apply(Transformer.scala:22)
at org.scalatest.Transformer.apply(Transformer.scala:20)
at org.scalatest.FunSpecLike$$anon$1.apply(FunSpecLike.scala:454)
at org.scalatest.TestSuite$class.withFixture(TestSuite.scala:196)
at org.scalatest.FunSpec.withFixture(FunSpec.scala:1630)
at org.scalatest.FunSpecLike$class.invokeWithFixture$1(FunSpecLike.scala:451)
at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:464)
at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:464)
at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289)
at org.scalatest.FunSpecLike$class.runTest(FunSpecLike.scala:464)
at com.b.n.filter.ApiKeyVerificationFilterSpec.org$scalatest$BeforeAndAfter$$super$runTest(ApiKeyVerificationFilterSpec.scala:25)
at org.scalatest.BeforeAndAfter$class.runTest(BeforeAndAfter.scala:203)
at com.b.n.filter.ApiKeyVerificationFilterSpec.runTest(ApiKeyVerificationFilterSpec.scala:25)
at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:497)
at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:497)
at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:396)
at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:384)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
at org.scalatest.SuperEngine.org$scalatest$SuperEngine$$runTestsInBranch(Engine.scala:379)
at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:461)
at org.scalatest.FunSpecLike$class.runTests(FunSpecLike.scala:497)
at org.scalatest.FunSpec.runTests(FunSpec.scala:1630)
at org.scalatest.Suite$class.run(Suite.scala:1147)
at org.scalatest.FunSpec.org$scalatest$FunSpecLike$$super$run(FunSpec.scala:1630)
at org.scalatest.FunSpecLike$$anonfun$run$1.apply(FunSpecLike.scala:501)
at org.scalatest.FunSpecLike$$anonfun$run$1.apply(FunSpecLike.scala:501)
at org.scalatest.SuperEngine.runImpl(Engine.scala:521)
at org.scalatest.FunSpecLike$class.run(FunSpecLike.scala:501)
at com.b.n.filter.ApiKeyVerificationFilterSpec.org$scalatest$BeforeAndAfter$$super$run(ApiKeyVerificationFilterSpec.scala:25)
at org.scalatest.BeforeAndAfter$class.run(BeforeAndAfter.scala:258)
at com.b.n.filter.ApiKeyVerificationFilterSpec.run(ApiKeyVerificationFilterSpec.scala:25)
at org.scalatest.tools.Framework.org$scalatest$tools$Framework$$runSuite(Framework.scala:314)
at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:480)
at sbt.TestRunner.runTest$1(TestFramework.scala:76)
at sbt.TestRunner.run(TestFramework.scala:85)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
at sbt.TestFramework$.sbt$TestFramework$$withContextLoader(TestFramework.scala:185)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1.apply(TestFramework.scala:202)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1.apply(TestFramework.scala:202)
at sbt.TestFunction.apply(TestFramework.scala:207)
at sbt.Tests$$anonfun$9.apply(Tests.scala:216)
at sbt.Tests$$anonfun$9.apply(Tests.scala:216)
at sbt.std.Transform$$anon$3$$anonfun$apply$2.apply(System.scala:44)
at sbt.std.Transform$$anon$3$$anonfun$apply$2.apply(System.scala:44)
at sbt.std.Transform$$anon$4.work(System.scala:63)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
at sbt.Execute.work(Execute.scala:237)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
"pool-9-thread-2-ScalaTest-running-BRequestFilterSpec":
at java.lang.ClassLoader.loadClass(ClassLoader.java:404)
- waiting to lock <0x0000000795a868e8> (a sbt.classpath.ClasspathFilter)
at sbt.classpath.ClasspathFilter.loadClass(ClassLoaders.scala:59)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at net.bytebuddy.dynamic.loading.MultipleParentClassLoader.loadClass(MultipleParentClassLoader.java:68)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at sun.reflect.GeneratedMethodAccessor20.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Direct.defineClass(ClassInjector.java:408)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:185)
- locked <0x0000000781ee0ff0> (a net.bytebuddy.dynamic.loading.MultipleParentClassLoader)
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:187)
at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4376)
at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:94)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
- locked <0x00000007959e4a78> (a sbt.classpath.ClasspathUtilities$$anon$1)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)
at org.mockito.Mockito.mock(Mockito.java:1729)
at org.mockito.Mockito.mock(Mockito.java:1642)
at org.scalatest.mockito.MockitoSugar$class.mock(MockitoSugar.scala:73)
at com.b.n.filter.BRequestFilterSpec.mock(BRequestFilterSpec.scala:18)
at com.b.n.filter.BRequestFilterSpec$Base$class.$init$(BRequestFilterSpec.scala:31)
at com.b.n.filter.BRequestFilterSpec$$anonfun$7$$anon$10.<init>(BRequestFilterSpec.scala:43)
at com.b.n.filter.BRequestFilterSpec$$anonfun$7.apply(BRequestFilterSpec.scala:43)
at com.b.n.filter.BRequestFilterSpec$$anonfun$7.apply(BRequestFilterSpec.scala:43)
at org.scalatest.OutcomeOf$class.outcomeOf(OutcomeOf.scala:85)
at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
at org.scalatest.Transformer.apply(Transformer.scala:22)
at org.scalatest.Transformer.apply(Transformer.scala:20)
at org.scalatest.FunSpecLike$$anon$1.apply(FunSpecLike.scala:454)
at org.scalatest.TestSuite$class.withFixture(TestSuite.scala:196)
at org.scalatest.FunSpec.withFixture(FunSpec.scala:1630)
at org.scalatest.FunSpecLike$class.invokeWithFixture$1(FunSpecLike.scala:451)
at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:464)
at org.scalatest.FunSpecLike$$anonfun$runTest$1.apply(FunSpecLike.scala:464)
at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289)
at org.scalatest.FunSpecLike$class.runTest(FunSpecLike.scala:464)
at com.b.n.filter.BRequestFilterSpec.org$scalatest$BeforeAndAfter$$super$runTest(BRequestFilterSpec.scala:18)
at org.scalatest.BeforeAndAfter$class.runTest(BeforeAndAfter.scala:203)
at com.b.n.filter.BRequestFilterSpec.runTest(BRequestFilterSpec.scala:18)
at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:497)
at org.scalatest.FunSpecLike$$anonfun$runTests$1.apply(FunSpecLike.scala:497)
at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:396)
at org.scalatest.SuperEngine$$anonfun$traverseSubNodes$1$1.apply(Engine.scala:384)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
at org.scalatest.SuperEngine.org$scalatest$SuperEngine$$runTestsInBranch(Engine.scala:379)
at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:461)
at org.scalatest.FunSpecLike$class.runTests(FunSpecLike.scala:497)
at org.scalatest.FunSpec.runTests(FunSpec.scala:1630)
at org.scalatest.Suite$class.run(Suite.scala:1147)
at org.scalatest.FunSpec.org$scalatest$FunSpecLike$$super$run(FunSpec.scala:1630)
at org.scalatest.FunSpecLike$$anonfun$run$1.apply(FunSpecLike.scala:501)
at org.scalatest.FunSpecLike$$anonfun$run$1.apply(FunSpecLike.scala:501)
at org.scalatest.SuperEngine.runImpl(Engine.scala:521)
at org.scalatest.FunSpecLike$class.run(FunSpecLike.scala:501)
at com.b.n.filter.BRequestFilterSpec.org$scalatest$BeforeAndAfter$$super$run(BRequestFilterSpec.scala:18)
at org.scalatest.BeforeAndAfter$class.run(BeforeAndAfter.scala:258)
at com.b.n.filter.BRequestFilterSpec.run(BRequestFilterSpec.scala:18)
at org.scalatest.tools.Framework.org$scalatest$tools$Framework$$runSuite(Framework.scala:314)
at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:480)
at sbt.TestRunner.runTest$1(TestFramework.scala:76)
at sbt.TestRunner.run(TestFramework.scala:85)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
at sbt.TestFramework$.sbt$TestFramework$$withContextLoader(TestFramework.scala:185)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1.apply(TestFramework.scala:202)
at sbt.TestFramework$$anon$2$$anonfun$$init$$1.apply(TestFramework.scala:202)
at sbt.TestFunction.apply(TestFramework.scala:207)
at sbt.Tests$$anonfun$9.apply(Tests.scala:216)
at sbt.Tests$$anonfun$9.apply(Tests.scala:216)
at sbt.std.Transform$$anon$3$$anonfun$apply$2.apply(System.scala:44)
at sbt.std.Transform$$anon$3$$anonfun$apply$2.apply(System.scala:44)
at sbt.std.Transform$$anon$4.work(System.scala:63)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
at sbt.Execute.work(Execute.scala:237)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
at sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Found 1 deadlock.
```
ApiKeyVerificationFilter, line 77 is `val apikey = mock[ImmutableMap[String, ChildData]]` and BRequestFilterSpec line 31 is val pmap = mock[ParamMap].
sbt prompt looks like this:
```
$ sbt8
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=256M; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512M; support was removed in 8.0
[info] Loading global plugins from /Users/m/.sbt/0.13/plugins
[info] Loading project definition from ...
[info] Set current project to newton-api (in build file:...)
> test
[info] NServiceModuleSpec:
[info] NServiceModule
[info] - should have a test !!! IGNORED !!!
-- hangs here --
```
Mac OS 10.11.6
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
sbt 0.13.9
"org.scalatest" %% "scalatest" % "3.0.1" % "test",
"org.mockito" % "mockito-core" % "2.7.22" % "test"
`parallelExecution in Test := true` in build.sbt - setting this to false circumvents the issue. | [
"src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java
index 34c31feef2..ea51edf780 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/TypeCachingBytecodeGenerator.java
@@ -36,7 +36,7 @@ public <T> Class<T> mockClass(final MockFeatures<T> params) {
public Class<?> call() throws Exception {
return bytecodeGenerator.mockClass(params);
}
- }, classLoader == null ? BOOTSTRAP_LOCK : classLoader);
+ }, BOOTSTRAP_LOCK);
} catch (IllegalArgumentException exception) {
Throwable cause = exception.getCause();
if (cause instanceof RuntimeException) {
| null | train | train | 2017-11-07T12:04:36 | "2017-05-03T22:52:41Z" | mmlac | train |
mockito/mockito/1086_1280 | mockito/mockito | mockito/mockito/1086 | mockito/mockito/1280 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.9041043942633712)"
] | 2316a320012c09c6b815bfdf00b008732a3ffe75 | 5caabead07bc8f796a243d81d1988925179449cf | [
"Yes, it is by design.\r\n\r\n\"Strict stubs\" are not \"strict mocks\", e.g. we detect unused or incorrectly declared stubs but we don't force the user to verify all interactions.\r\n\r\nIf above is not clear in the documentation, can you suggest and update to the Javadoc that would make this clear? Perhaps on Strictness type or on Strictness.STRICT_STUBS enum value.",
"Are there any plans for `Strict mocks` where the above would be detected?",
">Are there any plans for Strict mocks where the above would be detected?\r\n\r\nYes, we should start supporting strict mocks. I gave a talk at Devoxx conference in San Jose in March and I collected even more feedback for offering strict mocks as an alternative. We have a ticket open at #649 on this but so far we didn't accumulate enough energy to get started on this.\r\n\r\nYou motivated me to start working on this. I'll commit to produce a design spec for #649 so that it is ready to work on by an eager contributor. How does it sound? :)",
"> I gave a talk at Devoxx conference in San Jose in March and I collected even more feedback for offering strict mocks as an alternative.\r\n\r\nThat's also where I learned from the `MockitoRule` and the different options. Thanks for that!\r\n\r\n> How does it sound? :)\r\n\r\nAwesome.\r\n\r\nI'd also very much prefer something along the lines of:\r\n `Mockito.enableStrictMode();`\r\n\r\nWhere you opt in for strict modes by default and then maybe can opt out for particular mocks.\r\n\r\nDo you plan to integrate the above static method call into the MockitoRule so that you can maybe do something like:\r\n`@Rule public final MockitoRule mockitoRule = MockitoJUnit.rule().strictness(STRICT_MOCKS);` that has the behavior of `STRICT_STUBS` and strict mocking?\r\n",
"The design spec is ready at #1097. Do you want to contribute? :)",
"I'm definitely interested. I might have some time. Would it also be okay to start with a POC and from there go and implement out all of the details? ",
">Would it also be okay to start with a POC and from there go and implement out all of the details?\r\n\r\nAbsolutely! Feel free to submit PR with a POC for early review.",
"`release/2.x` is the correct branch to do so, right?",
"Yes please :)\nOp ma 29 mei 2017 om 18:14 schreef Niklas Baudy <notifications@github.com>:\n\n> release/2.x is the correct branch to do so, right?\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/mockito/mockito/issues/1086#issuecomment-304694849>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AFrDb9S1OMV6VFvnHQkIS66COktib-yMks5r-u7ngaJpZM4NcKVl>\n> .\n>\n"
] | [] | "2017-12-27T09:52:28Z" | [
"docs",
"please contribute"
] | Documentation update - MockitoJUnit.strictness(STRICT_STUBS) does not do verifyNoMoreInteractions | ### Problem
Our documentation about "strict stubs" does not clearly indicate the difference between "strict mocks" (described at #1097). In short, "strict stubs" are not "strict mocks", e.g. we detect unused or incorrectly declared stubs but we don't force the user to verify all interactions.
### Suggested implementation
Suggest an update to the Javadoc that would make things clear? Perhaps on Strictness type or on Strictness.STRICT_STUBS enum value.
### Original report
I'd expect to let this test fail:
```
public class SomeTest {
@Rule public final MockitoRule mockitoRule = MockitoJUnit.rule().strictness(STRICT_STUBS);
@Mock Something something;
@Test public void something() {
Single.just(1)
.doOnSuccess(something::add)
.test()
.assertResult(1);
}
interface Something {
void add(int i);
}
}
```
when using `strictness(STRICT_STUBS)`, since I'm not verifying that `something.add(1)` was called.
Adding:
```
@After public void tearDown() {
verifyNoMoreInteractions(something);
}
```
yields the desire red unit test:
```
org.mockito.exceptions.verification.NoInteractionsWanted:
No interactions wanted here:
-> at tearDown(SomeTest.java:27)
But found this interaction on mock 'something':
-> at io.reactivex.internal.operators.single.SingleDoOnSuccess$DoOnSuccess.onSuccess(SingleDoOnSuccess.java:53)
```
Is this by design?
Junit Version: 4.12
Mockito Version: 2.8.9
| [
"src/main/java/org/mockito/quality/Strictness.java"
] | [
"src/main/java/org/mockito/quality/Strictness.java"
] | [] | diff --git a/src/main/java/org/mockito/quality/Strictness.java b/src/main/java/org/mockito/quality/Strictness.java
index 4e1126ae85..c9da8d367c 100644
--- a/src/main/java/org/mockito/quality/Strictness.java
+++ b/src/main/java/org/mockito/quality/Strictness.java
@@ -80,7 +80,8 @@ public enum Strictness {
* <li>Cleaner, more DRY tests ("Don't Repeat Yourself"):
* If you use {@link org.mockito.Mockito#verifyNoMoreInteractions(Object...)}
* you no longer need to explicitly verify stubbed invocations.
- * They are automatically verified for you.</li>
+ * They are automatically verified for you. However if you have more invocations,
+ * the test won't fail since it won't check that there are no more interactions on that stub.</li>
* </ul>
*
* For more information see {@link Strictness}.
| null | train | train | 2017-12-11T03:35:26 | "2017-05-16T08:34:02Z" | vanniktech | train |
mockito/mockito/1306_1307 | mockito/mockito | mockito/mockito/1306 | mockito/mockito/1307 | [
"keyword_pr_to_issue"
] | 1a3bc2e7cfdaf126f67645b8a954cf315172e580 | de894403247eae574d90bac5011647c97666a7fc | [] | [
"Nit: no need to add `final` here",
"done"
] | "2018-02-06T22:58:21Z" | [] | InvocationFactory.createInvocation's realmethod cannot throw a Throwable | InvocationFactory.createInvocation takes a Callable that is used to call the real method of the Invocation. If the Invocation throws an Exception the Exception is forwarded from the Callable. Unfortunately Callable can only throw an Exception, not a Throwable.
Hence if the real method throws a Throwable that is neither an Error, RuntimeException or Exception it cannot be forwarded.
I recommend for InvocationFactory.createInvocation to take realMethod argument that can throw a full Throwable.
This is required for fixing: linkedin/dexmaker#64
| [
"src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java",
"src/main/java/org/mockito/internal/invocation/RealMethod.java",
"src/main/java/org/mockito/invocation/InvocationFactory.java",
"version.properties"
] | [
"src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java",
"src/main/java/org/mockito/internal/invocation/RealMethod.java",
"src/main/java/org/mockito/invocation/InvocationFactory.java",
"version.properties"
] | [
"src/test/java/org/mockito/InvocationFactoryTest.java",
"src/test/java/org/mockito/StaticMockingExperimentTest.java"
] | diff --git a/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java b/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java
index af8fd3d5fb..03ee54bea1 100644
--- a/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java
+++ b/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java
@@ -14,8 +14,17 @@
public class DefaultInvocationFactory implements InvocationFactory {
- public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, Callable realMethod, Object... args) {
- RealMethod.FromCallable superMethod = new RealMethod.FromCallable(realMethod);
+ public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, final Callable realMethod, Object... args) {
+ RealMethod superMethod = new RealMethod.FromCallable(realMethod);
+ return createInvocation(target, settings, method, superMethod, args);
+ }
+
+ public Invocation createInvocation(Object target, MockCreationSettings settings, Method method, RealMethodBehavior realMethod, Object... args) {
+ RealMethod superMethod = new RealMethod.FromBehavior(realMethod);
+ return createInvocation(target, settings, method, superMethod, args);
+ }
+
+ private Invocation createInvocation(Object target, MockCreationSettings settings, Method method, RealMethod superMethod, Object[] args) {
return MockMethodInterceptor.createInvocation(target, method, args, superMethod, settings);
}
}
diff --git a/src/main/java/org/mockito/internal/invocation/RealMethod.java b/src/main/java/org/mockito/internal/invocation/RealMethod.java
index cd74d3c440..b7c8c1748f 100644
--- a/src/main/java/org/mockito/internal/invocation/RealMethod.java
+++ b/src/main/java/org/mockito/internal/invocation/RealMethod.java
@@ -5,6 +5,7 @@
package org.mockito.internal.invocation;
import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
+import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.InvocationOnMock;
import java.io.Serializable;
@@ -31,14 +32,23 @@ public Object invoke() {
}
}
- class FromCallable implements RealMethod {
+ class FromCallable extends FromBehavior implements RealMethod {
+ public FromCallable(final Callable<?> callable) {
+ super(new InvocationFactory.RealMethodBehavior() {
+ @Override
+ public Object call() throws Throwable {
+ return callable.call();
+ }
+ });
+ }
+ }
- private static final long serialVersionUID = 47957363950483625L;
+ class FromBehavior implements RealMethod {
- private final Callable<?> callable;
+ private final InvocationFactory.RealMethodBehavior<?> behavior;
- public FromCallable(Callable<?> callable) {
- this.callable = callable;
+ FromBehavior(InvocationFactory.RealMethodBehavior<?> behavior) {
+ this.behavior = behavior;
}
@Override
@@ -49,7 +59,7 @@ public boolean isInvokable() {
@Override
public Object invoke() throws Throwable {
try {
- return callable.call();
+ return behavior.call();
} catch (Throwable t) {
new ConditionalStackTraceFilter().filter(t);
throw t;
diff --git a/src/main/java/org/mockito/invocation/InvocationFactory.java b/src/main/java/org/mockito/invocation/InvocationFactory.java
index 8339642215..1803718696 100644
--- a/src/main/java/org/mockito/invocation/InvocationFactory.java
+++ b/src/main/java/org/mockito/invocation/InvocationFactory.java
@@ -8,6 +8,7 @@
import org.mockito.MockitoFramework;
import org.mockito.mock.MockCreationSettings;
+import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
@@ -19,7 +20,7 @@
* <p>
* Please don't provide your own implementation of {@link Invocation} type.
* Mockito team needs flexibility to add new methods to this interface if we need to.
- * If you integrate Mockito framework and you need an instance of {@link Invocation}, use {@link #createInvocation(Object, MockCreationSettings, Method, Callable, Object...)}.
+ * If you integrate Mockito framework and you need an instance of {@link Invocation}, use {@link #createInvocation(Object, MockCreationSettings, Method, RealMethodBehavior, Object...)}.
*
* @since 2.10.0
*/
@@ -27,6 +28,11 @@
public interface InvocationFactory {
/**
+ * @deprecated Use {@link #createInvocation(Object, MockCreationSettings, Method, RealMethodBehavior, Object...)} instead.
+ *
+ * Why deprecated? We found use cases where we need to handle Throwable and ensure correct stack trace filtering
+ * (removing Mockito internals from the stack trace). Hence the introduction of {@link RealMethodBehavior}.
+ *
* Creates instance of an {@link Invocation} object.
* This method is useful for framework integrators to programmatically simulate method calls on mocks using {@link MockHandler}.
* It enables advanced framework integrations.
@@ -40,6 +46,32 @@ public interface InvocationFactory {
* @return invocation instance
* @since 2.10.0
*/
- @Incubating
+ @Deprecated
Invocation createInvocation(Object target, MockCreationSettings settings, Method method, Callable realMethod, Object... args);
+
+ /**
+ * Behavior of the real method.
+ *
+ * @since 2.14.0
+ */
+ interface RealMethodBehavior<R> extends Serializable {
+ R call() throws Throwable;
+ }
+
+ /**
+ * Creates instance of an {@link Invocation} object.
+ * This method is useful for framework integrators to programmatically simulate method calls on mocks using {@link MockHandler}.
+ * It enables advanced framework integrations.
+ *
+ * @param target the mock object the method is invoked on.
+ * @param settings creation settings of the mock object.
+ * @param method java method invoked on mock.
+ * @param realMethod real method behavior. Needed for spying / invoking real behavior on mock objects.
+ * @param args the java method arguments
+ *
+ * @return invocation instance
+ * @since 2.14.0
+ */
+ @Incubating
+ Invocation createInvocation(Object target, MockCreationSettings settings, Method method, RealMethodBehavior realMethod, Object... args);
}
diff --git a/version.properties b/version.properties
index c274109d06..e406ba6bbb 100644
--- a/version.properties
+++ b/version.properties
@@ -1,5 +1,5 @@
#Currently building Mockito version
-version=2.13.4
+version=2.14.0
#Previous version used to generate release notes delta
previousVersion=2.13.3
| diff --git a/src/test/java/org/mockito/InvocationFactoryTest.java b/src/test/java/org/mockito/InvocationFactoryTest.java
new file mode 100644
index 0000000000..893f95f465
--- /dev/null
+++ b/src/test/java/org/mockito/InvocationFactoryTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito;
+
+import org.junit.Test;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.InvocationFactory;
+import org.mockitoutil.TestBase;
+
+import java.util.concurrent.Callable;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.withSettings;
+
+public class InvocationFactoryTest extends TestBase {
+ static class TestClass {
+ public String testMethod() throws Throwable {
+ return "un-mocked";
+ }
+ }
+
+ final TestClass mock = spy(TestClass.class);
+
+ @Test
+ public void call_method_that_throws_a_throwable() throws Throwable {
+ Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock,
+ withSettings().build(TestClass.class),
+ TestClass.class.getDeclaredMethod("testMethod"),
+ new InvocationFactory.RealMethodBehavior() {
+ @Override
+ public Object call() throws Throwable {
+ throw new Throwable("mocked");
+ }
+ });
+
+ try {
+ Mockito.mockingDetails(mock).getMockHandler().handle(invocation);
+ } catch (Throwable t) {
+ assertEquals("mocked", t.getMessage());
+ return;
+ }
+
+ fail();
+ }
+
+ @Test
+ public void call_method_that_returns_a_string() throws Throwable {
+ Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock,
+ withSettings().build(TestClass.class),
+ TestClass.class.getDeclaredMethod("testMethod"),
+ new InvocationFactory.RealMethodBehavior() {
+ @Override
+ public Object call() throws Throwable {
+ return "mocked";
+ }
+ });
+
+ Object ret = Mockito.mockingDetails(mock).getMockHandler().handle(invocation);
+ assertEquals("mocked", ret);
+ }
+
+ @Test
+ public void deprecated_api_still_works() throws Throwable {
+ Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock,
+ withSettings().build(TestClass.class),
+ TestClass.class.getDeclaredMethod("testMethod"),
+ new Callable() {
+ public Object call() throws Exception {
+ return "mocked";
+ }
+ });
+
+ Object ret = Mockito.mockingDetails(mock).getMockHandler().handle(invocation);
+ assertEquals("mocked", ret);
+ }
+}
diff --git a/src/test/java/org/mockito/StaticMockingExperimentTest.java b/src/test/java/org/mockito/StaticMockingExperimentTest.java
index a74d5ebd8d..bb5e22573e 100644
--- a/src/test/java/org/mockito/StaticMockingExperimentTest.java
+++ b/src/test/java/org/mockito/StaticMockingExperimentTest.java
@@ -10,12 +10,12 @@
import org.mockito.exceptions.verification.WantedButNotInvoked;
import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.mockito.invocation.Invocation;
+import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.MockHandler;
import org.mockitoutil.TestBase;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
-import java.util.concurrent.Callable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
@@ -43,9 +43,9 @@ public class StaticMockingExperimentTest extends TestBase {
Foo mock = Mockito.mock(Foo.class);
MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();
Method staticMethod;
- Callable realMethod = new Callable() {
+ InvocationFactory.RealMethodBehavior realMethod = new InvocationFactory.RealMethodBehavior() {
@Override
- public Object call() throws Exception {
+ public Object call() throws Throwable {
return null;
}
};
| train | train | 2018-01-27T23:43:44 | "2018-02-06T21:31:53Z" | moltmann | train |
mockito/mockito/1314_1319 | mockito/mockito | mockito/mockito/1314 | mockito/mockito/1319 | [
"keyword_pr_to_issue"
] | cbc7a99db706621bdb6728cb64d2b0d9be6a8034 | 92a3e07e2b31c2b13e3cd072c15ee9feb28f505d | [
"Good idea. Do you want to submit a PR?",
"@mockitoguy I can work on it.\r\nAlso, to make it consistent I would suggest to extend the message to include all the invocations for other cases. As example for `TooLittleActualInvocations`.",
"Submitted PR #1319 "
] | [
"Not sure if it follows the convention since the `*` was used before and `java.*` imports were listed below.",
"`invocations` → `locations`?",
"Indentation might have changed.",
"`infocation` → `location`?",
"`allLocations` → `locations`? At this point it not entirely consistent with other calls if I understand correctly.",
"Same thing with imports as above.",
"As I can see the import layouts that was used before violates the conventions that are described here: https://github.com/mockito/mockito/blob/release/2.x/.github/CONTRIBUTING.md#coding-style\r\nShould I revert it or is it better to follow the conventions that are in the guide?",
"Here the imports also violates the described import layout",
"Done",
"Done",
"Done",
"Done",
"Let's put this assert in a separate test"
] | "2018-02-21T13:34:58Z" | [
"please contribute"
] | Undesired invocation message improvements | Let’s take a look at the following code.
```kotlin
package whatever
import org.junit.Test
import org.mockito.Mockito
class MultipleUndesiredInvocations {
interface Inner {
fun call()
}
interface SideEffect {
fun call()
class Impl(private val inner: Inner) : SideEffect {
override fun call() = inner.call()
}
}
interface Outer {
fun call()
class Impl(private val inner: Inner, sideEffect: SideEffect) : Outer {
init {
sideEffect.call()
}
override fun call() {
inner.call()
}
}
}
@Test
fun test() {
val inner = Mockito.mock(Inner::class.java)
val sideEffect = SideEffect.Impl(inner)
val outer = Outer.Impl(inner, sideEffect)
outer.call()
Mockito.verify(inner).call()
}
}
```
The `test` will fail, of course. The following message will be shown.
```
org.mockito.exceptions.verification.TooManyActualInvocations:
inner.call();
Wanted 1 time:
-> at whatever.MultipleUndesiredInvocations.test(MultipleUndesiredInvocations.kt:43)
But was 2 times. Undesired invocation:
-> at whatever.MultipleUndesiredInvocations$Outer$Impl.call(MultipleUndesiredInvocations.kt:30)
```
It is kind of fine, but the undesired call (for me) is actually inside the `SideEffect` class.
Is it possible to extend the message to show all undesired invocations somehow? It would be extremely helpful when debugging failed tests similar to the sample above — i. e. when a side-effect calls the target object. | [
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/invocation/InvocationsFinder.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/invocation/InvocationsFinder.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java",
"src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java"
] | diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 57094c0fa0..17823ffe5e 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -5,9 +5,27 @@
package org.mockito.internal.exceptions;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.exceptions.base.MockitoException;
-import org.mockito.exceptions.misusing.*;
+import org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue;
+import org.mockito.exceptions.misusing.CannotVerifyStubOnlyMock;
+import org.mockito.exceptions.misusing.FriendlyReminderException;
+import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
+import org.mockito.exceptions.misusing.MissingMethodInvocationException;
+import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockito.exceptions.misusing.NullInsteadOfMockException;
+import org.mockito.exceptions.misusing.PotentialStubbingProblem;
+import org.mockito.exceptions.misusing.RedundantListenerException;
+import org.mockito.exceptions.misusing.UnfinishedMockingSessionException;
+import org.mockito.exceptions.misusing.UnfinishedStubbingException;
+import org.mockito.exceptions.misusing.UnfinishedVerificationException;
+import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
+import org.mockito.exceptions.misusing.WrongTypeOfReturnValue;
import org.mockito.exceptions.verification.NeverWantedButInvoked;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.SmartNullPointerException;
@@ -28,12 +46,6 @@
import org.mockito.mock.MockName;
import org.mockito.mock.SerializableMode;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
import static org.mockito.internal.reporting.Pluralizer.pluralize;
import static org.mockito.internal.reporting.Pluralizer.were_exactly_x_interactions;
import static org.mockito.internal.util.StringUtil.join;
@@ -358,63 +370,71 @@ public static MockitoAssertionError wantedButNotInvokedInOrder(DescribedInvocati
));
}
- public static MockitoAssertionError tooManyActualInvocations(int wantedCount, int actualCount, DescribedInvocation wanted, Location firstUndesired) {
- String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, firstUndesired);
+ public static MockitoAssertionError tooManyActualInvocations(int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> locations) {
+ String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, locations);
return new TooManyActualInvocations(message);
}
private static String createTooManyInvocationsMessage(int wantedCount, int actualCount, DescribedInvocation wanted,
- Location firstUndesired) {
+ List<Location> invocations) {
return join(
wanted.toString(),
"Wanted " + pluralize(wantedCount) + ":",
new LocationImpl(),
- "But was " + pluralize(actualCount) + ". Undesired invocation:",
- firstUndesired,
+ "But was " + pluralize(actualCount) + ":",
+ createAllLocationsMessage(invocations),
""
);
}
- public static MockitoAssertionError neverWantedButInvoked(DescribedInvocation wanted, Location firstUndesired) {
+ public static MockitoAssertionError neverWantedButInvoked(DescribedInvocation wanted, List<Location> invocations) {
return new NeverWantedButInvoked(join(
wanted.toString(),
"Never wanted here:",
new LocationImpl(),
"But invoked here:",
- firstUndesired,
- ""
+ createAllLocationsMessage(invocations)
));
}
- public static MockitoAssertionError tooManyActualInvocationsInOrder(int wantedCount, int actualCount, DescribedInvocation wanted, Location firstUndesired) {
- String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, firstUndesired);
+ public static MockitoAssertionError tooManyActualInvocationsInOrder(int wantedCount, int actualCount, DescribedInvocation wanted, List<Location> invocations) {
+ String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, invocations);
return new VerificationInOrderFailure(join(
"Verification in order failure:" + message
));
}
- private static String createTooLittleInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted,
- Location lastActualInvocation) {
- String ending =
- (lastActualInvocation != null) ? lastActualInvocation + "\n" : "\n";
+ private static String createAllLocationsMessage(List<Location> locations) {
+ if (locations == null) {
+ return "\n";
+ }
+ StringBuilder sb = new StringBuilder();
+ for (Location location : locations) {
+ sb.append(location).append("\n");
+ }
+ return sb.toString();
+ }
+ private static String createTooLittleInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy,
+ DescribedInvocation wanted,
+ List<Location> locations) {
return join(
wanted.toString(),
"Wanted " + discrepancy.getPluralizedWantedCount() + (discrepancy.getWantedCount() == 0 ? "." : ":"),
new LocationImpl(),
"But was " + discrepancy.getPluralizedActualCount() + (discrepancy.getActualCount() == 0 ? "." : ":"),
- ending
+ createAllLocationsMessage(locations)
);
}
- public static MockitoAssertionError tooLittleActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, Location lastActualLocation) {
- String message = createTooLittleInvocationsMessage(discrepancy, wanted, lastActualLocation);
+ public static MockitoAssertionError tooLittleActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> allLocations) {
+ String message = createTooLittleInvocationsMessage(discrepancy, wanted, allLocations);
return new TooLittleActualInvocations(message);
}
- public static MockitoAssertionError tooLittleActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, Location lastActualLocation) {
- String message = createTooLittleInvocationsMessage(discrepancy, wanted, lastActualLocation);
+ public static MockitoAssertionError tooLittleActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> locations) {
+ String message = createTooLittleInvocationsMessage(discrepancy, wanted, locations);
return new VerificationInOrderFailure(join(
"Verification in order failure:" + message
diff --git a/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java b/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java
index 57c335fcef..260321babb 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationsFinder.java
@@ -138,6 +138,14 @@ private static List<Invocation> removeVerifiedInOrder(List<Invocation> invocatio
return unverified;
}
+ public static List<Location> getAllLocations(List<Invocation> invocations) {
+ List<Location> locations = new LinkedList<Location>();
+ for (Invocation invocation : invocations) {
+ locations.add(invocation.getLocation());
+ }
+ return locations;
+ }
+
private static class RemoveNotMatching implements Filter<Invocation> {
private final MatchableInvocation wanted;
diff --git a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
index 36e35a36d1..d0eb0b5eb8 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
@@ -17,7 +17,7 @@
import static org.mockito.internal.invocation.InvocationMarker.markVerifiedInOrder;
import static org.mockito.internal.invocation.InvocationsFinder.findAllMatchingUnverifiedChunks;
import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
-import static org.mockito.internal.invocation.InvocationsFinder.getLastLocation;
+import static org.mockito.internal.invocation.InvocationsFinder.getAllLocations;
public class AtLeastXNumberOfInvocationsChecker {
@@ -26,8 +26,8 @@ public static void checkAtLeastNumberOfInvocations(List<Invocation> invocations,
int actualCount = actualInvocations.size();
if (wantedCount > actualCount) {
- Location lastLocation = getLastLocation(actualInvocations);
- throw tooLittleActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
+ List<Location> allLocations = getAllLocations(actualInvocations);
+ throw tooLittleActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations);
}
markVerified(actualInvocations, wanted);
@@ -39,8 +39,8 @@ public static void checkAtLeastNumberOfInvocations(List<Invocation> invocations,
int actualCount = chunk.size();
if (wantedCount > actualCount) {
- Location lastLocation = getLastLocation(chunk);
- throw tooLittleActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
+ List<Location> allLocations = getAllLocations(chunk);
+ throw tooLittleActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations);
}
markVerifiedInOrder(chunk, wanted, orderingContext);
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
index 3fa340f3dc..1dfc2f1f25 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
@@ -5,6 +5,7 @@
package org.mockito.internal.verification.checkers;
+import java.util.Arrays;
import java.util.List;
import org.mockito.internal.reporting.Discrepancy;
import org.mockito.internal.verification.api.InOrderContext;
@@ -22,7 +23,7 @@
import static org.mockito.internal.invocation.InvocationsFinder.findFirstMatchingUnverifiedInvocation;
import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
import static org.mockito.internal.invocation.InvocationsFinder.findMatchingChunk;
-import static org.mockito.internal.invocation.InvocationsFinder.getLastLocation;
+import static org.mockito.internal.invocation.InvocationsFinder.getAllLocations;
public class NumberOfInvocationsChecker {
@@ -34,16 +35,14 @@ public static void checkNumberOfInvocations(List<Invocation> invocations, Matcha
int actualCount = actualInvocations.size();
if (wantedCount > actualCount) {
- Location lastInvocation = getLastLocation(actualInvocations);
- throw tooLittleActualInvocations(new Discrepancy(wantedCount, actualCount), wanted, lastInvocation);
+ List<Location> allLocations = getAllLocations(actualInvocations);
+ throw tooLittleActualInvocations(new Discrepancy(wantedCount, actualCount), wanted, allLocations);
}
if (wantedCount == 0 && actualCount > 0) {
- Location firstUndesired = actualInvocations.get(wantedCount).getLocation();
- throw neverWantedButInvoked(wanted, firstUndesired);
+ throw neverWantedButInvoked(wanted, getAllLocations(actualInvocations));
}
if (wantedCount < actualCount) {
- Location firstUndesired = actualInvocations.get(wantedCount).getLocation();
- throw tooManyActualInvocations(wantedCount, actualCount, wanted, firstUndesired);
+ throw tooManyActualInvocations(wantedCount, actualCount, wanted, getAllLocations(actualInvocations));
}
markVerified(actualInvocations, wanted);
@@ -55,12 +54,11 @@ public static void checkNumberOfInvocations(List<Invocation> invocations, Matcha
int actualCount = chunk.size();
if (wantedCount > actualCount) {
- Location lastInvocation = getLastLocation(chunk);
- throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastInvocation);
+ List<Location> allLocations = getAllLocations(chunk);
+ throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, allLocations);
}
if (wantedCount < actualCount) {
- Location firstUndesired = chunk.get(wantedCount).getLocation();
- throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, firstUndesired);
+ throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, getAllLocations(chunk));
}
markVerifiedInOrder(chunk, wanted, context);
@@ -72,7 +70,7 @@ public static void checkNumberOfInvocationsNonGreedy(List<Invocation> invocation
while( actualCount < wantedCount ){
Invocation next = findFirstMatchingUnverifiedInvocation(invocations, wanted, context );
if( next == null ){
- throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, lastLocation );
+ throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, Arrays.asList(lastLocation));
}
markVerified( next, wanted );
context.markVerified( next );
| diff --git a/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java b/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
index b07ece43cd..7172998c7e 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationsFinderTest.java
@@ -185,4 +185,15 @@ public void shouldFindPreviousInOrder() throws Exception {
previous = InvocationsFinder.findPreviousVerifiedInOrder(invocations, context);
assertSame(simpleMethodInvocationTwo, previous);
}
+
+ @Test
+ public void shouldFindAllStackTraces() {
+ List<Location> all = InvocationsFinder.getAllLocations(invocations);
+ Assertions.assertThat(all).contains(simpleMethodInvocation.getLocation(), simpleMethodInvocationTwo.getLocation(), differentMethodInvocation.getLocation());
+ }
+
+ @Test
+ public void shouldNotFindLocationsForEmptyInvocationsList() {
+ Assertions.assertThat(InvocationsFinder.getAllLocations(Collections.<Invocation>emptyList())).isEmpty();
+ }
}
diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
index af9d3cb801..61b2f2e7b4 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
@@ -5,10 +5,6 @@
package org.mockito.internal.verification.checkers;
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static org.assertj.core.api.Assertions.assertThat;
-
import java.util.List;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
@@ -28,6 +24,10 @@
import org.mockito.junit.MockitoJUnitRunner;
import org.mockitousage.IMethods;
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyList;
+import static org.assertj.core.api.Assertions.assertThat;
+
@RunWith(MockitoJUnitRunner.class)
public class NumberOfInvocationsCheckerTest {
@@ -58,7 +58,7 @@ public void shouldReportTooLittleActual() throws Exception {
}
@Test
- public void shouldReportWithLastInvocationStackTrace() throws Exception {
+ public void shouldReportAllInvocationsStackTrace() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation());
@@ -66,7 +66,7 @@ public void shouldReportWithLastInvocationStackTrace() throws Exception {
exception.expectMessage("mock.simpleMethod()");
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 2 times");
- exception.expectMessage(containsTimes("-> at", 2));
+ exception.expectMessage(containsTimes("-> at", 3));
NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100);
}
@@ -86,7 +86,7 @@ public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() th
}
@Test
- public void shouldReportWithFirstUndesiredInvocationStackTrace() throws Exception {
+ public void shouldReportWithAllInvocationsStackTrace() throws Exception {
Invocation first = buildSimpleMethod().toInvocation();
Invocation second = buildSimpleMethod().toInvocation();
Invocation third = buildSimpleMethod().toInvocation();
@@ -95,6 +95,8 @@ public void shouldReportWithFirstUndesiredInvocationStackTrace() throws Exceptio
wanted = buildSimpleMethod().toInvocationMatcher();
exception.expect(TooManyActualInvocations.class);
+ exception.expectMessage("" + first.getLocation());
+ exception.expectMessage("" + second.getLocation());
exception.expectMessage("" + third.getLocation());
NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 2);
}
diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
index 2e72033238..bc031ac904 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
@@ -5,11 +5,6 @@
package org.mockito.internal.verification.checkers;
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-
import java.util.List;
import org.hamcrest.BaseMatcher;
@@ -27,6 +22,11 @@
import org.mockito.invocation.Invocation;
import org.mockitousage.IMethods;
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+
public class NumberOfInvocationsInOrderCheckerTest {
private InvocationMatcher wanted;
@@ -102,7 +102,7 @@ public void shouldReportTooLittleActual() throws Exception {
}
@Test
- public void shouldReportWithLastInvocationStackTrace() throws Exception {
+ public void shouldReportWithAllInvocationsStackTrace() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation());
@@ -110,7 +110,7 @@ public void shouldReportWithLastInvocationStackTrace() throws Exception {
exception.expectMessage("mock.simpleMethod()");
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 2 times");
- exception.expectMessage(containsTimes("-> at", 2));
+ exception.expectMessage(containsTimes("-> at", 3));
NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context);
@@ -168,7 +168,7 @@ public void shouldReportNeverWantedButInvoked() throws Exception {
exception.expect(VerificationInOrderFailure.class);
exception.expectMessage("mock.simpleMethod()");
exception.expectMessage("Wanted 0 times");
- exception.expectMessage("But was 1 time. Undesired invocation");
+ exception.expectMessage("But was 1 time:");
exception.expectMessage("" + first.getLocation());
NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0, context);
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
index 4e5f464c53..8e1bf06322 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
@@ -155,7 +155,7 @@ public void shouldPrintTooManyInvocations() {
String expectedCause =
"\n" +
- "But was 2 times. Undesired invocation:" +
+ "But was 2 times:" +
"\n" +
"-> at";
assertThat(e).hasMessageContaining(expectedCause);
| train | train | 2018-03-25T10:57:40 | "2018-02-16T07:53:37Z" | arturdryomov | train |
mockito/mockito/1313_1321 | mockito/mockito | mockito/mockito/1313 | mockito/mockito/1321 | [
"keyword_pr_to_issue"
] | 6a56f6e0995732a14772630701d979c5759bdbe6 | 018a2e0c2746072fbb19de58d77cc87b1e12d00c | [
"Fantastic analysis, thank you! Do you want to take a stab at fixing it?\r\n\r\n(ping @raphw, original author of the this mock maker).",
"I will have a look. Great analysis indeed. We will have to weakly reference any mock instance stored in Mockito. This is a straight forwars fi, I hope.",
"I will do it once I have time. (The kid, you k ow.)",
"I saw two problems we need to keep in mind:\r\n- How to weak references interact with serializability\r\n- We have to be vigilant to prevent premature cleaning up of the mock. Is there any possible case where we can gain access to the the invocations / handler without a reference to the mock?",
"I uploaded a fix proposal as fb37a2e even though\r\n- I don't like that we use different kind of invocations for some tests\r\n- The tests pass and I think I serialize properly, but I am not 100% sure as I never dealt with serialization before",
"Hey guys! I was reviewing @moltmann's PR and I'm wondering what are the alternative options to solve the problem. Can we attach a state to the mock object so that MockMakers can do their magic without keeping weak maps of all mocks? @raphw, thoughts?",
"Unfortunately, I do not think that there is an alternative to weak references.\r\n\r\nThe Java instrumentation API allows the retransformation of Java byte code, it does not allow changing the shape of a class, e.g. adding fields. Naturally, the dispatcher would be placed in such a field such that the life time of a dispatcher would be implicitly bound to the mock instance. But since we cannot add this field, we have to place the instance outside of it such that we have to use weak references to reach the same effect.\r\n\r\nTherefore, I fear that this is the only way to go. ",
"Thank you for explanation!\r\n\r\nOne alternative/supplemental option is to make the lifecycle of mocks more formal. For example, JUnit rule / runner / mockito session can inform the mock maker that \"we're done with mock x\".",
"@mockitoguy If you can make this work, great. I see my mockmaker to be used to a legacy test suites though as they want to just mock one final method and not create a new test suite. Some older suites might not use junit or any other fancy feature.\r\n\r\nHence I would like to find a solution that does not require any changes outside of mockito.",
"@mockitoguy Is there any further change you want to c0ad83a?"
] | [] | "2018-02-21T17:35:28Z" | [] | InlineByteBuddyMockMaker does not clean up stale mocks | **Repro:**
1. Mockito 2.15.2 using mockito-inline
2. With -Xmx64m run
```
@RunWith(JUnit4.class)
public class Stress {
private static final int NUM_RUNS = 20000;
public static class TestClass {
public String returnA() {
return "A";
}
}
/**
* Test that mocks that are not referenced anymore are properly cleaned up.
*/
@Test
public void callALotOfMocks() {
for (int i = 0; i < NUM_RUNS; i++) {
TestClass mock = mock(TestClass.class);
when(mock.returnA()).thenReturn("B");
assertEquals("B", mock.returnA());
if (i % 1024 == 0) {
System.out.println("Mocked " + i + "/" + NUM_RUNS);
}
}
}
}
```
**Expected:**
The test eventually finishes
**Observed:**
> Mocked 0/20000
> Mocked 1024/20000
> Mocked 2048/20000
> Mocked 3072/20000
> Mocked 4096/20000
> Mocked 5120/20000
> Mocked 6144/20000
> Mocked 7168/20000
> Mocked 8192/20000
> Mocked 9216/20000
> Mocked 10240/20000
> Mocked 11264/20000
> Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
> at java.lang.StringCoding$StringDecoder.decode(StringCoding.java:149)
> at java.lang.StringCoding.decode(StringCoding.java:193)
> at java.lang.String.<init>(String.java:426)
> at java.util.jar.Attributes.read(Attributes.java:418)
> at java.util.jar.Manifest.read(Manifest.java:199)
>
> Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"
>
> Process finished with exit code 1
**Analysis:**
The `InlineByteBuddyMockMaker` uses a Map<WeakRef\<Mock\>, Handler> in the `mocks` field to store the mocks and their handlers. It relies that the mocks get garbage collected to remove the entry in the map. Unfortunately if there is an invocation on the mock, the handlers keep strong references to the mock in `InterceptedInvocation.mock`, `RealMethodCall.instance`, and `SerializableRealMethodCall.instance`. These are (strong) references by the handler. Hence the mock never gets cleaned up and the map grows indefinitely.
This is not a problem if the mocks get `Mockito.reset` properly or if using a mock maker that does not store the handlers. | [
"gradle/java-library.gradle",
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java",
"src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java",
"src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java",
"subprojects/inline/inline.gradle",
"version.properties"
] | [
"gradle/java-library.gradle",
"src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java",
"src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java",
"src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java",
"src/main/java/org/mockito/internal/invocation/mockref/MockReference.java",
"src/main/java/org/mockito/internal/invocation/mockref/MockStrongReference.java",
"src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java",
"subprojects/inline/inline.gradle",
"version.properties"
] | [
"src/test/java/org/mockito/internal/invocation/InvocationBuilder.java",
"src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java",
"src/test/java/org/mockitoutil/TestBase.java",
"subprojects/inline/src/test/java/org/mockitoinline/StressTest.java"
] | diff --git a/gradle/java-library.gradle b/gradle/java-library.gradle
index d41e3406b8..45c72f11d2 100644
--- a/gradle/java-library.gradle
+++ b/gradle/java-library.gradle
@@ -9,6 +9,7 @@ targetCompatibility = 1.6
test {
include "**/*Test.class"
+
testLogging {
exceptionFormat 'full'
showCauses true
diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
index 02882a2274..f39a1a2462 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java
@@ -16,6 +16,8 @@
import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
import org.mockito.internal.invocation.RealMethod;
import org.mockito.internal.invocation.SerializableMethod;
+import org.mockito.internal.invocation.mockref.MockReference;
+import org.mockito.internal.invocation.mockref.MockWeakReference;
import org.mockito.internal.util.concurrent.WeakConcurrentMap;
import java.io.IOException;
@@ -141,14 +143,14 @@ private static class RealMethodCall implements RealMethod {
private final Method origin;
- private final Object instance;
+ private final MockWeakReference<Object> instanceRef;
private final Object[] arguments;
private RealMethodCall(SelfCallInfo selfCallInfo, Method origin, Object instance, Object[] arguments) {
this.selfCallInfo = selfCallInfo;
this.origin = origin;
- this.instance = instance;
+ this.instanceRef = new MockWeakReference<Object>(instance);
this.arguments = arguments;
}
@@ -162,8 +164,8 @@ public Object invoke() throws Throwable {
if (!Modifier.isPublic(origin.getDeclaringClass().getModifiers() & origin.getModifiers())) {
origin.setAccessible(true);
}
- selfCallInfo.set(instance);
- return tryInvoke(origin, instance, arguments);
+ selfCallInfo.set(instanceRef.get());
+ return tryInvoke(origin, instanceRef.get(), arguments);
}
}
@@ -174,14 +176,14 @@ private static class SerializableRealMethodCall implements RealMethod {
private final SerializableMethod origin;
- private final Object instance;
+ private final MockReference<Object> instanceRef;
private final Object[] arguments;
private SerializableRealMethodCall(String identifier, Method origin, Object instance, Object[] arguments) {
this.origin = new SerializableMethod(origin);
this.identifier = identifier;
- this.instance = instance;
+ this.instanceRef = new MockWeakReference<Object>(instance);
this.arguments = arguments;
}
@@ -196,13 +198,13 @@ public Object invoke() throws Throwable {
if (!Modifier.isPublic(method.getDeclaringClass().getModifiers() & method.getModifiers())) {
method.setAccessible(true);
}
- MockMethodDispatcher mockMethodDispatcher = MockMethodDispatcher.get(identifier, instance);
+ MockMethodDispatcher mockMethodDispatcher = MockMethodDispatcher.get(identifier, instanceRef.get());
if (!(mockMethodDispatcher instanceof MockMethodAdvice)) {
throw new MockitoException("Unexpected dispatcher for advice-based super call");
}
- Object previous = ((MockMethodAdvice) mockMethodDispatcher).selfCallInfo.replace(instance);
+ Object previous = ((MockMethodAdvice) mockMethodDispatcher).selfCallInfo.replace(instanceRef.get());
try {
- return tryInvoke(method, instance, arguments);
+ return tryInvoke(method, instanceRef.get(), arguments);
} finally {
((MockMethodAdvice) mockMethodDispatcher).selfCallInfo.set(previous);
}
diff --git a/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java b/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java
index 875a903ecd..d08f6b1ac9 100644
--- a/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java
+++ b/src/main/java/org/mockito/internal/invocation/DefaultInvocationFactory.java
@@ -5,6 +5,7 @@
package org.mockito.internal.invocation;
import org.mockito.internal.creation.DelegatingMethod;
+import org.mockito.internal.invocation.mockref.MockWeakReference;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.progress.SequenceNumber;
import org.mockito.invocation.Invocation;
@@ -33,7 +34,7 @@ private Invocation createInvocation(Object target, MockCreationSettings settings
public static InterceptedInvocation createInvocation(Object mock, Method invokedMethod, Object[] arguments, RealMethod realMethod, MockCreationSettings settings, Location location) {
return new InterceptedInvocation(
- mock,
+ new MockWeakReference<Object>(mock),
createMockitoMethod(invokedMethod, settings),
arguments,
realMethod,
diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
index d3a9b976cb..b9cf0721f4 100644
--- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
+++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
@@ -4,6 +4,7 @@
*/
package org.mockito.internal.invocation;
+import org.mockito.internal.invocation.mockref.MockReference;
import org.mockito.internal.exceptions.VerificationAwareInvocation;
import org.mockito.internal.reporting.PrintSettings;
import org.mockito.invocation.Invocation;
@@ -19,7 +20,7 @@ public class InterceptedInvocation implements Invocation, VerificationAwareInvoc
private static final long serialVersionUID = 475027563923510472L;
- private final Object mock;
+ private final MockReference<Object> mockRef;
private final MockitoMethod mockitoMethod;
private final Object[] arguments, rawArguments;
private final RealMethod realMethod;
@@ -32,13 +33,13 @@ public class InterceptedInvocation implements Invocation, VerificationAwareInvoc
private boolean isIgnoredForVerification;
private StubInfo stubInfo;
- public InterceptedInvocation(Object mock,
+ public InterceptedInvocation(MockReference<Object> mockRef,
MockitoMethod mockitoMethod,
Object[] arguments,
RealMethod realMethod,
Location location,
int sequenceNumber) {
- this.mock = mock;
+ this.mockRef = mockRef;
this.mockitoMethod = mockitoMethod;
this.arguments = ArgumentsProcessor.expandArgs(mockitoMethod, arguments);
this.rawArguments = arguments;
@@ -99,7 +100,7 @@ public void ignoreForVerification() {
@Override
public Object getMock() {
- return mock;
+ return mockRef.get();
}
@Override
@@ -138,7 +139,7 @@ public boolean equals(Object o) {
return false;
}
InterceptedInvocation other = (InterceptedInvocation) o;
- return this.mock.equals(other.mock)
+ return this.mockRef.get().equals(other.mockRef.get())
&& this.mockitoMethod.equals(other.mockitoMethod)
&& this.equalArguments(other.arguments);
}
diff --git a/src/main/java/org/mockito/internal/invocation/mockref/MockReference.java b/src/main/java/org/mockito/internal/invocation/mockref/MockReference.java
new file mode 100644
index 0000000000..0dac2ea919
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/mockref/MockReference.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation.mockref;
+
+import java.io.Serializable;
+
+/**
+ * To avoid memory leaks for certain implementations of MockMaker,
+ * we need to use weak mock references internally. See #1313
+ */
+public interface MockReference<T> extends Serializable {
+ T get();
+}
diff --git a/src/main/java/org/mockito/internal/invocation/mockref/MockStrongReference.java b/src/main/java/org/mockito/internal/invocation/mockref/MockStrongReference.java
new file mode 100644
index 0000000000..3b20ee58fd
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/mockref/MockStrongReference.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation.mockref;
+
+import java.io.ObjectStreamException;
+
+public class MockStrongReference<T> implements MockReference<T> {
+
+ private final T ref;
+ private final boolean deserializeAsWeakRef;
+
+ public MockStrongReference(T ref, boolean deserializeAsWeakRef) {
+ this.ref = ref;
+ this.deserializeAsWeakRef = deserializeAsWeakRef;
+ }
+
+ @Override
+ public T get() {
+ return ref;
+ }
+
+ private Object readResolve() throws ObjectStreamException {
+ if (deserializeAsWeakRef) {
+ return new MockWeakReference<T>(ref);
+ } else {
+ return this;
+ }
+ }
+}
diff --git a/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java b/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java
new file mode 100644
index 0000000000..256745b362
--- /dev/null
+++ b/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation.mockref;
+
+import java.io.ObjectStreamException;
+import java.lang.ref.WeakReference;
+
+/**
+ * A weak reference that is converted into a strong reference when serialized.
+ * See {@link MockReference}.
+ */
+public class MockWeakReference<T> implements MockReference<T> {
+
+ private final WeakReference<T> ref;
+
+ public MockWeakReference(T t) {
+ this.ref = new WeakReference<T>(t);
+ }
+
+ private Object writeReplace() throws ObjectStreamException {
+ return new MockStrongReference<T>(get(), true);
+ }
+
+ @Override
+ public T get() {
+ T ref = this.ref.get();
+
+ if (ref == null) {
+ throw new IllegalStateException("The mock object was garbage collected. " +
+ "This should not happen in normal circumstances when using public API. " +
+ "Typically, the test class keeps strong reference to the mock object " +
+ "and it prevents getting the mock collected. Mockito internally needs " +
+ "to keep weak references to mock objects to avoid memory leaks for " +
+ "certain types of MockMaker implementations. If you see this exception " +
+ "using Mockito public API, please file a bug. For more information see " +
+ "issue #1313.");
+ }
+
+ return ref;
+ }
+}
diff --git a/subprojects/inline/inline.gradle b/subprojects/inline/inline.gradle
index be103615af..b8d2577ab5 100644
--- a/subprojects/inline/inline.gradle
+++ b/subprojects/inline/inline.gradle
@@ -8,3 +8,6 @@ dependencies {
}
tasks.javadoc.enabled = false
+
+//required by the "StressTest.java"
+test.maxHeapSize = "256m"
diff --git a/version.properties b/version.properties
index 7591fc5a63..91e1c5b39e 100644
--- a/version.properties
+++ b/version.properties
@@ -1,5 +1,5 @@
#Currently building Mockito version
-version=2.15.7
+version=2.16.0
#Previous version used to generate release notes delta
previousVersion=2.15.6
| diff --git a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
index c8943b180e..b3106a6993 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
@@ -6,6 +6,7 @@
package org.mockito.internal.invocation;
import org.mockito.Mockito;
+import org.mockito.internal.invocation.mockref.MockStrongReference;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
@@ -60,7 +61,7 @@ public Invocation toInvocation() {
}
}
- Invocation i = new InterceptedInvocation(mock,
+ Invocation i = new InterceptedInvocation(new MockStrongReference<Object>(mock, false),
new SerializableMethod(method),
args,
NO_OP,
diff --git a/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java b/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java
new file mode 100644
index 0000000000..1e3d8e9ab2
--- /dev/null
+++ b/src/test/java/org/mockito/internal/invocation/mockref/MockWeakReferenceTest.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation.mockref;
+
+import org.assertj.core.api.Assertions;
+import org.junit.Test;
+import org.mockito.internal.invocation.mockref.MockWeakReference;
+import org.mockitoutil.TestBase;
+
+import static org.junit.Assert.fail;
+
+public class MockWeakReferenceTest extends TestBase {
+
+ @Test
+ public void descriptive_exception_when_mock_was_collected() {
+ try {
+ //when
+ new MockWeakReference(null).get();
+ //then
+ fail();
+ } catch (Exception e) {
+ Assertions.assertThat(e).hasMessageContaining("The mock object was garbage collected");
+ }
+ }
+}
diff --git a/src/test/java/org/mockitoutil/TestBase.java b/src/test/java/org/mockitoutil/TestBase.java
index fe920e6541..ca3d7b8744 100644
--- a/src/test/java/org/mockitoutil/TestBase.java
+++ b/src/test/java/org/mockitoutil/TestBase.java
@@ -11,6 +11,7 @@
import org.mockito.StateMaster;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.configuration.ConfigurationAccess;
+import org.mockito.internal.invocation.mockref.MockStrongReference;
import org.mockito.internal.invocation.InterceptedInvocation;
import org.mockito.internal.debugging.LocationImpl;
import org.mockito.internal.invocation.InvocationBuilder;
@@ -64,8 +65,9 @@ protected static Invocation invocationOf(Class<?> type, String methodName, Objec
for (int i = 0; i < args.length; i++) {
types[i] = args[i].getClass();
}
- return new InterceptedInvocation(mock(type), new SerializableMethod(type.getMethod(methodName,
- types)), args, InterceptedInvocation.NO_OP, new LocationImpl(), 1);
+ return new InterceptedInvocation(new MockStrongReference<Object>(mock(type), false),
+ new SerializableMethod(type.getMethod(methodName, types)), args, InterceptedInvocation.NO_OP,
+ new LocationImpl(), 1);
}
protected static Invocation invocationAt(String location) {
diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StressTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StressTest.java
new file mode 100644
index 0000000000..c6a55064d4
--- /dev/null
+++ b/subprojects/inline/src/test/java/org/mockitoinline/StressTest.java
@@ -0,0 +1,38 @@
+/*
+ * 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;
+import static org.mockito.Mockito.withSettings;
+
+public class StressTest {
+ public class TestClass {
+ public String getStuff() {
+ return "A";
+ }
+ }
+
+ @Test
+ public void call_a_lot_of_mocks() {
+ //This requires smaller heap set for the test process, see "inline.gradle"
+ for (int i = 0; i < 40000; i++) {
+ TestClass mock = mock(TestClass.class);
+ when(mock.getStuff()).thenReturn("B");
+ assertEquals("B", mock.getStuff());
+
+ TestClass serializableMock = mock(TestClass.class, withSettings().serializable());
+ when(serializableMock.getStuff()).thenReturn("C");
+ assertEquals("C", serializableMock.getStuff());
+
+ if (i % 1024 == 0) {
+ System.out.println(i + "/40000 mocks called");
+ }
+ }
+ }
+}
| train | train | 2018-03-05T16:48:40 | "2018-02-15T23:19:06Z" | moltmann | train |
mockito/mockito/1323_1324 | mockito/mockito | mockito/mockito/1323 | mockito/mockito/1324 | [
"timestamp(timedelta=5.0, similarity=0.8825254719575555)"
] | d4a508e65dcfaeb8033c48ec4321f59a4ed2cb99 | c8893962d79a5790c81a02f65579b3a8ba9e3d23 | [] | [
"This is the current behavior, correct? E.g. your PR did not change it?",
"This comment explains what the code does but does not explain why (which is the point of code comments). Unfortunately, I don't know either :) I think it was a judgement call years ago and we will stick to it to keep compatibility. Thank you for cleaning up the TODO and adding test coverage.",
"This looks like a change in behavior. What is driving this? We are very careful when making changes in behavior that can cause issues when migrating to newer version of Mockito.",
"Thanks!",
"This exception message is not consistent with how we handle exceptions. Take a look at a Reporter class. Typically we throw an exception that is or derives from MockitoException. The message needs to be very clean, actionable to the end user. I suggest to create a high level unit test that demonstrates this use case from the standpoint of the end user. Run this test, observe the exception, would a newbie Mockito understand the exception message and was able to resolve the problem quickly?",
"I see, thank you! Now I think the TODO was added because it's strange when a _user_ passes a null varargs argument:\r\n```java\r\nthenReturn(\"foo\", (String []) null);\r\n// instead of \r\nthenReturn(\"foo\", (String) null);\r\n```\r\nIf that null array comes from somewhere else (e.g., a method `nextInvocationsArguments`), that almost always a programming error that must be fixed (we can't say if a user really means `{ null }`, or `{}`, or if that's an error).\r\n\r\nWill Mockito stick with this decision in 2.x only, or in 3+ too? Will you consider changing that in the next releases? In the latter case I'd keep a TODO, but expand it with explanation _and_ a reference to an issue.",
"This one is tricky, as it must not occur because of an _external_ precondition that _Mockito_ first validates this answer. If this precondition is met (i.e., Mockito never calls `answer` if `validateFor` fails), it will never fire. Therefore, I can't think of how to yield this exception through _public_ API.\r\n\r\nI've checked on 2.x with the following test, `answer` throws an NPE:\r\n\r\n```java\r\n @Test\r\n public void should_not_answer_null_throwable() throws Throwable {\r\n try {\r\n // Shall #validateFor first!\r\n new ThrowsException(null).answer(new InvocationBuilder().toInvocation());\r\n Assertions.fail(\"Should have raised NPE\");\r\n } catch (NullPointerException expected) {}\r\n }\r\n```\r\n\r\nI see such alternatives:\r\n1. Keep an implicit null check. I believe it's not OK because this check is performed on the object state, and not on a user-supplied argument.\r\n2. Add an explicit null check, throw NPE with description.\r\n3. Add an explicit null check, throw IllegalStateException with description.\r\n4. Add an explicit null check, report in a more user-friendly format.\r\n5. Add a `validateFor` check in `answer`. It will _definetely_ catch when validateFor isn't called, but is redundant in case when Mockito always validates this answer (= adheres to the Answer+ValidableAnswer contract).\r\n\r\nI'd say (5) is the safest one, but you make the same check twice (externally in the framework code + internally in the class itself). I can't say how expensive that is, or shall we trust the rest of the framework here, what do you think?\r\n\r\nIt seems `Reporter` is used to supply user-facing exceptions, but this one shall never occur in correct Mockito implementation. How do you report _internal_ errors?",
"Exactly, I've added to confirm that.",
"I considered how to clarify that in the case when any argument is null, we abort the stubbing.\r\n\r\nIt doesn't change _observable_ behavior, because `thenThrow(Class<? extends Throwable> throwableType)` does the same if null is passed (that was extracted in `abortNullExceptionType`).\r\n\r\nIf any code is added in `thenThrow(Class<? extends Throwable> throwableType)` _[before](https://github.com/mockito/mockito/pull/1324/files/84332358ad08f225c9bb293e5200792046d57ed7#diff-01345510e64bc217eb06fbf16e77739dR58)_ a null check, the behavior will become different.\r\n",
"If you think it's worth it, I'd do the same to [`thenThrow(Throwable.. throwables)`](https://github.com/mockito/mockito/pull/1324/files/84332358ad08f225c9bb293e5200792046d57ed7#diff-01345510e64bc217eb06fbf16e77739dR43).",
"Unless there is a strong reason not to, I plan to keep the code as is. Nobody complained about it. There is risk that the change will be incompatible. It's better to focus Mockito 3 on more interesting features!\r\n\r\nThank you for pointing this out and attempting to clear up the TODO!",
"Oh I see now, thank you for clarification!\r\n\r\nI don't see the value of this change. We are adding one extra method and creating small code duplication.",
"Oh, you're right, the user will never see it when using the public API. I missed that.\r\n\r\nIf this is only internal, IllegalStateException is perfect.",
"I'd rather keep the assignment for backwards compatibility. I made this change and will push it back to your pull request. Can you contribute a test that preserves this behavior?",
"Can you contribute a fix that makes it fail early when null passed via constructor? This would be cleaner (earlier feedback).",
"Oh, that's unexpected, thank you for adding a clarifying comment!\r\n\r\nI think I'll add a couple of tests:\r\n- The one that prevents the change I did.\r\n- The one that verifies we get the throwable returned from `fillInStackTrace` in subsequent invocations.",
"What's interesting is that the custom exception from #866 breaks the [Throwable#fillInStackTrace contract](https://docs.oracle.com/javase/9/docs/api/java/lang/Throwable.html#fillInStackTrace--): this method shall always return `this`, never `null` or a reference to another throwable.\r\n",
"I actually did it locally earlier, and got failures in some integration tests. It seems the constructor has to allow null throwable so that we don't get UnfinishedStubbingException (I certainly can't say if that shall or can be fixed). Here is an example of failing test output:\r\n```\r\norg.mockitousage.stubbing.StubbingWithThrowablesTest > shouldNotAllowSettingNullThrowable FAILED\r\n java.lang.AssertionError: \r\n Expected: (an instance of org.mockito.exceptions.base.MockitoException and exception with message a string containing \"Cannot stub with null throwable\")\r\n but: an instance of org.mockito.exceptions.base.MockitoException <org.junit.internal.runners.model.MultipleFailureException: There were 2 errors:\r\n org.mockito.exceptions.base.MockitoException(\r\n Cannot stub with null throwable!)\r\n org.mockito.exceptions.misusing.UnfinishedStubbingException(\r\n Unfinished stubbing detected here:\r\n -> at org.mockitousage.stubbing.StubbingWithThrowablesTest.shouldNotAllowSettingNullThrowable(StubbingWithThrowablesTest.java:154)\r\n\r\n E.g. thenReturn() may be missing.\r\n Examples of correct stubbing:\r\n when(mock.isOk()).thenReturn(true);\r\n when(mock.isOk()).thenThrow(exception);\r\n doThrow(exception).when(mock).someVoidMethod();\r\n Hints:\r\n 1. missing thenReturn()\r\n 2. you are trying to stub a final method, which is not supported\r\n 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed\r\n )> is a org.junit.internal.runners.model.MultipleFailureException\r\n Stacktrace was: org.junit.internal.runners.model.MultipleFailureException: There were 2 errors:\r\n org.mockito.exceptions.base.MockitoException(\r\n Cannot stub with null throwable!)\r\n org.mockito.exceptions.misusing.UnfinishedStubbingException(\r\n Unfinished stubbing detected here:\r\n -> at org.mockitousage.stubbing.StubbingWithThrowablesTest.shouldNotAllowSettingNullThrowable(StubbingWithThrowablesTest.java:154)\r\n\r\n E.g. thenReturn() may be missing.\r\n Examples of correct stubbing:\r\n when(mock.isOk()).thenReturn(true);\r\n when(mock.isOk()).thenThrow(exception);\r\n doThrow(exception).when(mock).someVoidMethod();\r\n Hints:\r\n 1. missing thenReturn()\r\n 2. you are trying to stub a final method, which is not supported\r\n 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed\r\n )\r\n at org.junit.runners.model.MultipleFailureException.assertEmpty(MultipleFailureException.java:67)\r\n at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:39)\r\n at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)\r\n at org.junit.rules.RunRules.evaluate(RunRules.java:20)\r\n at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\r\n at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\n at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\n at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\n at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\n at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\n at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\n at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\n at org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\n at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)\r\n at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)\r\n at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)\r\n at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)\r\n at sun.reflect.GeneratedMethodAccessor60.invoke(Unknown Source)\r\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n at java.lang.reflect.Method.invoke(Method.java:498)\r\n at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)\r\n at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\r\n at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)\r\n at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)\r\n at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)\r\n at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:108)\r\n at sun.reflect.GeneratedMethodAccessor59.invoke(Unknown Source)\r\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n at java.lang.reflect.Method.invoke(Method.java:498)\r\n at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)\r\n at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\r\n at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)\r\n at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)\r\n at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)\r\n at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)\r\n at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)\r\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\r\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\r\n at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)\r\n at java.lang.Thread.run(Thread.java:748)\r\n\r\n```",
"Isn't it already tested in NPEWhenCustomExceptionStackTraceReturnNullTest?",
"I like this test. Can you check if we have top level integration tests for those use cases? I did a quick search and I think we have some gaps.\r\n\r\nI'm wondering if top level tests under 'org.mockitousage.*' packages aren't better to verify and document this behavior. ThrowsExceptionTest is becoming big and complicated and it does seem to repeat the coverage of the other tests. Thoughts?",
"It is, shall I remove this unit test or expand the IT in `NPEWhenCustomExceptionStackTraceReturnNullTest`?",
"There is a similar integration test: `org.mockitousage.stubbing.StubbingConsecutiveAnswersTest#should_throw_consecutively`\r\n\r\nShall I remove this one?",
"As this test passed, the code \r\n```\r\nthrowable.fillInStackTrace();\r\nfilter.filter(throwable);\r\nthrow throwable;\r\n```\r\ndidn't break #866 , did it?",
"Shan't we add a comment that these implementations of `fillInStackTrace` are totally incorrect -- they violate the method contract? Any Throwable implementation must always return a reference to `this` from `fillInStackTrace`.",
"Go ahead! I wanted to preserve current behavior in a test.",
"Why `linkplain` here instead of `link`?"
] | "2018-02-23T19:00:21Z" | [] | Improve BaseStubbing & ThrowsException internals | I'd discovered some exception-stubbing related code that may express its intent more clearly during #1322 investigation.
Please see the PR for more details: #1324 | [
"src/main/java/org/mockito/internal/stubbing/BaseStubbing.java",
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java",
"src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java"
] | [
"src/main/java/org/mockito/internal/stubbing/BaseStubbing.java",
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java",
"src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java"
] | [
"src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java",
"src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java",
"src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
index ddb9a8dcb9..6dd99cd802 100644
--- a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
+++ b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
@@ -24,7 +24,8 @@ public OngoingStubbing<T> thenReturn(T value) {
public OngoingStubbing<T> thenReturn(T value, T... values) {
OngoingStubbing<T> stubbing = thenReturn(value);
if (values == null) {
- // TODO below does not seem right
+ // For no good reason we're configuring null answer here
+ // This has been like that since forever, so let's keep it for compatibility (unless users complain)
return stubbing.thenReturn(null);
}
for (T v : values) {
@@ -65,7 +66,7 @@ public OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType) {
@Override
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
if (nextToBeThrown == null) {
- thenThrow((Class<Throwable>) null);
+ return thenThrow((Class<Throwable>) null);
}
OngoingStubbing<T> stubbing = thenThrow(toBeThrown);
for (Class<? extends Throwable> t : nextToBeThrown) {
diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
index b18d05dae1..7771c0438f 100644
--- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
@@ -83,9 +83,9 @@ public Stubber doThrow(Class<? extends Throwable> toBeThrown) {
Throwable e;
try {
e = newInstance(toBeThrown);
- } catch (RuntimeException instanciationError) {
+ } catch (RuntimeException instantiationError) {
mockingProgress().reset();
- throw instanciationError;
+ throw instantiationError;
}
return doThrow(e);
}
diff --git a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java
index 037520fee3..502e359e00 100644
--- a/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java
+++ b/src/main/java/org/mockito/internal/stubbing/answers/ThrowsException.java
@@ -14,23 +14,36 @@
import static org.mockito.internal.exceptions.Reporter.cannotStubWithNullThrowable;
import static org.mockito.internal.exceptions.Reporter.checkedExceptionInvalid;
+/**
+ * An answer that always throws the same throwable.
+ */
public class ThrowsException implements Answer<Object>, ValidableAnswer, Serializable {
private static final long serialVersionUID = 1128820328555183980L;
private final Throwable throwable;
private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
+ /**
+ * Creates a new answer always throwing the given throwable. If it is null,
+ * {@linkplain ValidableAnswer#validateFor(InvocationOnMock) answer validation}
+ * will fail.
+ */
public ThrowsException(Throwable throwable) {
this.throwable = throwable;
}
public Object answer(InvocationOnMock invocation) throws Throwable {
+ if (throwable == null) {
+ throw new IllegalStateException("throwable is null: " +
+ "you shall not call #answer if #validateFor fails!");
+ }
if (MockUtil.isMock(throwable)) {
throw throwable;
}
Throwable t = throwable.fillInStackTrace();
if (t == null) {
+ //Custom exceptions sometimes return null, see #866
throw throwable;
}
filter.filter(t);
| diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
index 8b553aae98..2e71102aaf 100644
--- a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
+++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java
@@ -10,7 +10,9 @@
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.invocation.InvocationBuilder;
+import org.mockito.invocation.Invocation;
+import static junit.framework.TestCase.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@@ -19,7 +21,7 @@ public class ThrowsExceptionTest {
@Test
public void should_raise_wanted_throwable() throws Throwable {
try {
- new ThrowsException(new IllegalStateException("my dear throwable")).answer(new InvocationBuilder().method("canThrowException").toInvocation());
+ new ThrowsException(new IllegalStateException("my dear throwable")).answer(createMethodInvocation());
Assertions.fail("should have raised wanted exception");
} catch (Throwable throwable) {
assertThat(throwable).isInstanceOf(IllegalStateException.class).hasMessage("my dear throwable");
@@ -29,7 +31,7 @@ public void should_raise_wanted_throwable() throws Throwable {
@Test
public void should_throw_mock_exception_without_stacktrace() throws Exception {
try {
- new ThrowsException(mock(Exception.class)).answer(new InvocationBuilder().method("canThrowException").toInvocation());
+ new ThrowsException(mock(Exception.class)).answer(createMethodInvocation());
Assertions.fail("should have raised wanted exception");
} catch (Throwable throwable) {
assertThat(throwable.getStackTrace()).describedAs("no stack trace, it's mock").isNull();
@@ -46,7 +48,7 @@ public void should_fill_in_exception_stacktrace() throws Exception {
try {
// when
- new ThrowsException(throwableToRaise).answer(new InvocationBuilder().method("canThrowException").toInvocation());
+ new ThrowsException(throwableToRaise).answer(createMethodInvocation());
Assertions.fail("should have raised wanted exception");
} catch (Throwable throwable) {
// then
@@ -59,24 +61,42 @@ public void should_fill_in_exception_stacktrace() throws Exception {
@Test
public void should_invalidate_null_throwable() throws Throwable {
try {
- new ThrowsException(null).validateFor(new InvocationBuilder().toInvocation());
+ Invocation invocation = createMethodInvocation();
+ new ThrowsException(null).validateFor(invocation);
Assertions.fail("should have raised a MockitoException");
} catch (MockitoException expected) {}
}
+ @Test
+ public void should_throw_illegal_state_exception_if_null_answer() throws Throwable {
+ Invocation invocation = createMethodInvocation();
+ try {
+ new ThrowsException(null).answer(invocation);
+ fail();
+ } catch (IllegalStateException expected) {
+ }
+ }
+
@Test
public void should_pass_proper_checked_exception() throws Throwable {
- new ThrowsException(new CharacterCodingException()).validateFor(new InvocationBuilder().method("canThrowException").toInvocation());
+ new ThrowsException(new CharacterCodingException()).validateFor(createMethodInvocation());
}
@Test(expected = MockitoException.class)
public void should_fail_invalid_checked_exception() throws Throwable {
- new ThrowsException(new IOException()).validateFor(new InvocationBuilder().method("canThrowException").toInvocation());
+ new ThrowsException(new IOException()).validateFor(createMethodInvocation());
}
@Test
public void should_pass_RuntimeExceptions() throws Throwable {
- new ThrowsException(new Error()).validateFor(new InvocationBuilder().method("canThrowException").toInvocation());
- new ThrowsException(new RuntimeException()).validateFor(new InvocationBuilder().method("canThrowException").toInvocation());
+ new ThrowsException(new Error()).validateFor(createMethodInvocation());
+ new ThrowsException(new RuntimeException()).validateFor(createMethodInvocation());
+ }
+
+ /** Creates Invocation of a "canThrowException" method call. */
+ private static Invocation createMethodInvocation() {
+ return new InvocationBuilder()
+ .method("canThrowException")
+ .toInvocation();
}
}
diff --git a/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java b/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java
new file mode 100644
index 0000000000..5e3193e9ab
--- /dev/null
+++ b/src/test/java/org/mockitousage/bugs/FillInStackTraceScenariosTest.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitousage.bugs;
+
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockitousage.IMethods;
+import org.mockitoutil.TestBase;
+
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+
+/**
+ * These tests check that ThrowsException#answer throws an instance returned
+ * by Throwable#fillInStackTrace of the provided throwable.
+ *
+ * <p>A well-behaved Throwable implementation must always return a reference to this
+ * from #fillInStackTrace according to the method contract.
+ * However, Mockito throws the exception returned from #fillInStackTrace for backwards compatibility
+ * (or the provided exception if the method returns null).
+ *
+ * @see Throwable#fillInStackTrace()
+ * @see <a href="https://github.com/mockito/mockito/issues/866">#866</a>
+ */
+public class FillInStackTraceScenariosTest extends TestBase {
+
+ @Mock IMethods mock;
+
+ private class SomeException extends RuntimeException {}
+
+ class NullStackTraceException extends RuntimeException {
+ public Exception fillInStackTrace() {
+ return null;
+ }
+ }
+
+ class NewStackTraceException extends RuntimeException {
+ public Exception fillInStackTrace() {
+ return new SomeException();
+ }
+ }
+
+ //issue 866
+ @Test
+ public void avoids_NPE() {
+ when(mock.simpleMethod()).thenThrow(new NullStackTraceException());
+ try {
+ mock.simpleMethod();
+ fail();
+ } catch(NullStackTraceException e) {}
+ }
+
+ @Test
+ public void uses_return_value_from_fillInStackTrace() {
+ when(mock.simpleMethod()).thenThrow(new NewStackTraceException());
+ try {
+ mock.simpleMethod();
+ fail();
+ } catch(SomeException e) {}
+ }
+}
diff --git a/src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.java b/src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.java
deleted file mode 100644
index 92a130528a..0000000000
--- a/src/test/java/org/mockitousage/bugs/NPEWhenCustomExceptionStackTraceReturnNullTest.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.mockitousage.bugs;
-
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockitousage.IMethods;
-import org.mockitoutil.TestBase;
-
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.when;
-
-public class NPEWhenCustomExceptionStackTraceReturnNullTest extends TestBase {
-
- @Mock
- IMethods mock;
-
- class NullStackTraceException extends RuntimeException {
- @Override
- public Exception fillInStackTrace() {
- return null;
- }
- }
-
- //issue 866
- @Test
- public void shouldNotThrowNPE() {
- when(mock.simpleMethod()).thenThrow(new NullStackTraceException());
- try {
- mock.simpleMethod();
- fail();
- } catch(NullStackTraceException e) {}
- }
-}
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java
index f8fa2b536e..47c217280e 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java
@@ -41,6 +41,34 @@ public void should_return_consecutive_values_for_two_nulls() throws Exception {
assertNull(mock.simpleMethod());
}
+ @Test
+ public void should_return_consecutive_values_first_var_arg_null() throws Exception {
+ when(mock.simpleMethod()).thenReturn("one", (String) null);
+
+ assertEquals("one", mock.simpleMethod());
+ assertNull(mock.simpleMethod());
+ assertNull(mock.simpleMethod());
+ }
+
+ @Test
+ public void should_return_consecutive_values_var_arg_null() throws Exception {
+ when(mock.simpleMethod()).thenReturn("one", (String[]) null);
+
+ assertEquals("one", mock.simpleMethod());
+ assertNull(mock.simpleMethod());
+ assertNull(mock.simpleMethod());
+ }
+
+ @Test
+ public void should_return_consecutive_values_var_args_contain_null() throws Exception {
+ when(mock.simpleMethod()).thenReturn("one", "two", null);
+
+ assertEquals("one", mock.simpleMethod());
+ assertEquals("two", mock.simpleMethod());
+ assertNull(mock.simpleMethod());
+ assertNull(mock.simpleMethod());
+ }
+
@Test
public void should_return_consecutive_values_set_by_shorten_then_return_method() throws Exception {
when(mock.simpleMethod()).thenReturn("one", "two", "three");
diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
index 9f526bfc63..935372426a 100644
--- a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java
@@ -22,6 +22,9 @@
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
+
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.ThrowableAssert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -48,6 +51,48 @@ public void setup() {
mockTwo = mock(HashMap.class);
}
+ @Test
+ public void throws_same_exception_consecutively() {
+ when(mock.add("")).thenThrow(new ExceptionOne());
+
+ //1st invocation
+ Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ public void call() {
+ mock.add("");
+ }
+ }).isInstanceOf(ExceptionOne.class);
+
+ mock.add("1");
+
+ //2nd invocation
+ Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ public void call() {
+ mock.add("");
+ }
+ }).isInstanceOf(ExceptionOne.class);
+ }
+
+ @Test
+ public void throws_same_exception_consecutively_with_doThrow() {
+ doThrow(new ExceptionOne()).when(mock).clear();
+
+ //1st invocation
+ Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ public void call() {
+ mock.clear();
+ }
+ }).isInstanceOf(ExceptionOne.class);
+
+ mock.add("1");
+
+ //2nd invocation
+ Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ public void call() {
+ mock.clear();
+ }
+ }).isInstanceOf(ExceptionOne.class);
+ }
+
@Test
public void shouldStubWithThrowable() throws Exception {
IllegalArgumentException expected = new IllegalArgumentException("thrown by mock");
@@ -55,7 +100,6 @@ public void shouldStubWithThrowable() throws Exception {
exception.expect(sameInstance(expected));
mock.add("throw");
-
}
@Test
| train | train | 2018-03-13T05:04:39 | "2018-02-23T18:55:25Z" | dmitry-timofeev | train |
mockito/mockito/1326_1327 | mockito/mockito | mockito/mockito/1326 | mockito/mockito/1327 | [
"keyword_pr_to_issue",
"timestamp(timedelta=6.0, similarity=0.8442294612501725)"
] | 723300cc655e14c719233901d8adfdbfbf91ab52 | 1ecfc7ab5ab447b4eb0a3fef9aff84b338f406f6 | [] | [] | "2018-03-01T17:51:44Z" | [] | Reduce memory consumption of the typical LocationImpl | I recently noticed very heavy memory usage on our testsuite (which is using mockito) so I started profiling.
I eventually found #1313 but that's already being worked on. Also spotted a low hanging fruit: our testsuite is allocating about 6 *million* instances of `LocationImpl`.
It looks like I can't avoid that easily, however each `LocationImpl` also allocates a new `StackTraceFilter`, which can be easily avoided when the default is being applied; sending a PR shortly.
This should save us about 6 million empty and pointless `StackTraceFilter` :) | [
"src/main/java/org/mockito/internal/debugging/LocationImpl.java"
] | [
"src/main/java/org/mockito/internal/debugging/LocationImpl.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/debugging/LocationImpl.java b/src/main/java/org/mockito/internal/debugging/LocationImpl.java
index ce3de04a0a..8561b62d3e 100644
--- a/src/main/java/org/mockito/internal/debugging/LocationImpl.java
+++ b/src/main/java/org/mockito/internal/debugging/LocationImpl.java
@@ -11,11 +11,14 @@
public class LocationImpl implements Location, Serializable {
private static final long serialVersionUID = -9054861157390980624L;
+ //Limit the amount of objects being created, as this class is heavily instantiated:
+ private static final StackTraceFilter defaultStackTraceFilter = new StackTraceFilter();
+
private final Throwable stackTraceHolder;
private final StackTraceFilter stackTraceFilter;
public LocationImpl() {
- this(new StackTraceFilter());
+ this(defaultStackTraceFilter);
}
public LocationImpl(StackTraceFilter stackTraceFilter) {
@@ -23,7 +26,7 @@ public LocationImpl(StackTraceFilter stackTraceFilter) {
}
public LocationImpl(Throwable stackTraceHolder) {
- this(new StackTraceFilter(), stackTraceHolder);
+ this(defaultStackTraceFilter, stackTraceHolder);
}
private LocationImpl(StackTraceFilter stackTraceFilter, Throwable stackTraceHolder) {
| null | train | train | 2018-02-19T06:48:55 | "2018-03-01T17:49:29Z" | Sanne | train |
mockito/mockito/1346_1349 | mockito/mockito | mockito/mockito/1346 | mockito/mockito/1349 | [
"timestamp(timedelta=0.0, similarity=0.9362691284832727)",
"keyword_issue_to_pr",
"keyword_pr_to_issue"
] | 34877f1d9641e44b566dd95af1869aa9a9537cc0 | d10a54335d0cc6c0e65d747c01b1cef281ef6ae8 | [
"Hm that seems really weird. Could you please post the implementation of `TacticalStation` and `SpaceShip` (although I am assuming they are simple POJO's?)",
"(Oh never mind, I missed the small link at the end of the example to https://github.com/szpak/code-examples-and-poc/tree/mockito2junit5-bug/mockito2-junit5/src/main/java/info/solidsoft/blog/mockito/junit5 )",
"@szpak Please see https://github.com/mockito/mockito/blob/5e9a3c62fc1ca4cf12d5d19580613f418cebc895/subprojects/junit-jupiter/src/test/java/org/mockitousage/InjectMocksTest.java for a working test. I could make these tests fail with adding `final` to the field declaration, so that is what is going wrong. Removing `final` makes the tests pass.\r\n\r\nWhat I do not understand is how this could work with JUnit 4, as we have not changed any of that code. We are completely reusing all of that logic.",
"It also works with `final` if `MockitoAnnotations.initMocks(this);` is used. Therefore, I would suspect the way how it is triggered/executed in JUnit 5 extension.",
"@TimvdLippe @szpak I have debugged this issue a bit. Here is what I found: it does look like the problem is with triggering the same logic from `MockitoExtension.class`. \r\nThe root cause of the problem is that `beforeEach` creates two `testInstances` of the same test class for each test. \r\nLooks like method `collectParentTestInstances` is adding the same testInstance to the list of test instances.\r\nI can try to work on this issue if no one is assigned to is already.\r\n",
"PRs appreciated!\n\nOn Mon, 26 Mar 2018, 10:55 Serge Bishyr, <notifications@github.com> wrote:\n\n> @TimvdLippe <https://github.com/TimvdLippe> @szpak\n> <https://github.com/szpak> I have debugged this issue a bit. Here is what\n> I found: it does look like the problem is with triggering the same logic\n> from MockitoExtension.class.\n> The root cause of the problem is that beforeEach creates two testInstances\n> of the same test class for each test.\n> Looks like method collectParentTestInstances is adding the same\n> testInstance to the list of test instances.\n> I can try to work on this issue if no one is assigned to is already.\n>\n> —\n> You are receiving this because you were mentioned.\n>\n>\n> Reply to this email directly, view it on GitHub\n> <https://github.com/mockito/mockito/issues/1346#issuecomment-376094135>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AFrDb9w69sJERNCP5FZJXPrwdq0ltsI9ks5tiK0ZgaJpZM4S6Huw>\n> .\n>\n",
"Have added PR #1349 with the fix for the issue",
"It works flawlessly. Thanks @SeriyBg!\r\n\r\n@TimvdLippe As this bug can impact all those people preferring a constructor injection, what do you thing about releasing the new minor version (e.g. after #1350 is hopefully merged :) ) to Maven Central?",
"@szpak Yes after #1350 we will probably publish a new version. You can however already use the latest version from Bintray",
"I know Tim that I can, but JUnit 5 support is a notable feature and having it working correctly in the latest non-development version (available in Maven Central) seems very sensible for me. Great, that we agree on releasing a new stable (but IHMO still 2.17.x) version soon.",
"I'm seeing this same bug when using `SpringExtension.class` along with `MockitoExtension.class`:\r\n\r\n```\r\n@ExtendWith({MockitoExtension.class, SpringExtension.class})\r\npublic class InjectMocksTest {\r\n static class TacticalStation {}\r\n\r\n static class SpaceShip {\r\n private final TacticalStation tacticalStation;\r\n\r\n public SpaceShip(final TacticalStation tacticalStation) {\r\n this.tacticalStation = tacticalStation;\r\n }\r\n\r\n public TacticalStation getTacticalStation() {\r\n return tacticalStation;\r\n }\r\n }\r\n\r\n @InjectMocks\r\n private SpaceShip spaceShip;\r\n\r\n @Mock\r\n private TacticalStation tacticalStation;\r\n\r\n @Test\r\n public void shouldInjectMocks() {\r\n assertThat(tacticalStation).isNotNull();\r\n assertThat(spaceShip.getTacticalStation()).isEqualTo(tacticalStation);\r\n //Bug ↑ - different mocks are use in @Mock and @InjectMock\r\n }\r\n}\r\n```\r\n\r\nThis is using Mockito 3.1.0, JUnit 5.6.0, and Spring Boot 5.3.0.RELEASE.",
"> I'm seeing this same bug when using `SpringExtension.class` along with `MockitoExtension.class`:\r\n> \r\n> ```\r\n> @ExtendWith({MockitoExtension.class, SpringExtension.class})\r\n> public class InjectMocksTest {\r\n> static class TacticalStation {}\r\n> \r\n> static class SpaceShip {\r\n> private final TacticalStation tacticalStation;\r\n> \r\n> public SpaceShip(final TacticalStation tacticalStation) {\r\n> this.tacticalStation = tacticalStation;\r\n> }\r\n> \r\n> public TacticalStation getTacticalStation() {\r\n> return tacticalStation;\r\n> }\r\n> }\r\n> \r\n> @InjectMocks\r\n> private SpaceShip spaceShip;\r\n> \r\n> @Mock\r\n> private TacticalStation tacticalStation;\r\n> \r\n> @Test\r\n> public void shouldInjectMocks() {\r\n> assertThat(tacticalStation).isNotNull();\r\n> assertThat(spaceShip.getTacticalStation()).isEqualTo(tacticalStation);\r\n> //Bug ↑ - different mocks are use in @Mock and @InjectMock\r\n> }\r\n> }\r\n> ```\r\n> \r\n> This is using Mockito 3.1.0, JUnit 5.6.0, and Spring Boot 5.3.0.RELEASE.\r\n\r\nYes I am also facing this issue. Mine is also exactly the same scenario. Below are my dependencies,\r\norg.junit.jupiter:junit-jupiter-engine:5.6.0\r\norg.springframework.boot:spring-boot-starter:2.2.6.RELEASE\r\norg.springframework.boot:spring-boot-starter-test:2.2.6.RELEASE\r\norg.mockito:mockito-junit-jupiter:3.1.0"
] | [
"Lets use `isSame` here, as we literally want this object to be there.",
"Good catch, have changed it. Thanks!",
"I have amended the previous commit as it's a simple and small change"
] | "2018-03-26T09:44:50Z" | [
"bug",
"injection",
"junit5"
] | Different mocks are used for @Mock and @InjectMock in the same test class with JUnit 5 extension | I've been playing with the new JUnit 5 support in Mockito 2.17.0. I have found that with `@Mock` and `@InjectMocks` used in the same test class different mocks are injected. I would expect to have the same mock reused (as it works with JUnit 4 or manual `@Mock` initialization).
Sample code:
```
@ExtendWith(MockitoExtension.class)
public class SpaceShip5BugMiniTest {
@InjectMocks
private SpaceShip spaceShip;
@Mock
private TacticalStation tacticalStation;
@Test
public void shouldInjectMocks() {
assertThat(tacticalStation).isNotNull();
assertThat(spaceShip.getTacticalStation()).isEqualTo(tacticalStation);
//Bug ↑ - different mocks are use in @Mock and @InjectMock
}
}
```
Error message:
```
org.opentest4j.AssertionFailedError:
Expecting:
<"tacticalStation (TacticalStation$MockitoMock$991606095@61d6015a)">
to be equal to:
<"tacticalStation (TacticalStation$MockitoMock$991606095@b62d79)">
but was not.
Expected :tacticalStation
Actual :tacticalStation
```
The minimal (non-)working example is available [here](https://github.com/szpak/code-examples-and-poc/tree/mockito2junit5-bug/mockito2-junit5).
@TimvdLippe Do you have an idea what could be wrong?
Mockito 2.17.0 (2.17.1 is not being released due to (https://github.com/mockito/shipkit/issues/679), junit-jupiter 5.1.0, OpenJDK 1.8.0_161, Linux.
### Checklist:
- [x] The mockito message in the stacktrace have useful information, but it didn't help
- [x] The problematic code (if that's possible) is copied here;
Note that some configuration are impossible to mock via Mockito
- [x] Provide versions (mockito / jdk / os / any other relevant information)
- [x] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
(same as any question on stackoverflow.com)
- [x] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md)
| [
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java"
] | diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
index e8e576bd3d..349217474a 100644
--- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
+++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
@@ -5,6 +5,9 @@
package org.mockito.junit.jupiter;
+import java.util.LinkedHashSet;
+import java.util.Optional;
+import java.util.Set;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
@@ -15,10 +18,6 @@
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.quality.Strictness;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Optional;
-
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
@@ -101,7 +100,7 @@ public void postProcessTestInstance(Object testInstance, ExtensionContext contex
*/
@Override
public void beforeEach(final ExtensionContext context) {
- List<Object> testInstances = new LinkedList<>();
+ Set<Object> testInstances = new LinkedHashSet<>();
testInstances.add(context.getRequiredTestInstance());
this.collectParentTestInstances(context, testInstances);
@@ -135,7 +134,7 @@ private Optional<MockitoSettings> retrieveAnnotationFromTestClasses(final Extens
return annotation;
}
- private void collectParentTestInstances(ExtensionContext context, List<Object> testInstances) {
+ private void collectParentTestInstances(ExtensionContext context, Set<Object> testInstances) {
Optional<ExtensionContext> parent = context.getParent();
while (parent.isPresent() && parent.get() != context.getRoot()) {
| diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
index 3ce8c9c8f7..47361589a5 100644
--- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
+++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
@@ -4,15 +4,15 @@
*/
package org.mockitousage;
+import java.util.function.Function;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
-import java.util.function.Function;
-
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
@@ -21,6 +21,9 @@ class JunitJupiterTest {
@Mock
private Function<Integer, String> rootMock;
+ @InjectMocks
+ private ClassWithDependency classWithDependency;
+
@Test
void ensureMockCreationWorks() {
assertThat(rootMock).isNotNull();
@@ -70,4 +73,17 @@ void shouldWeCreateMocksInTheParentContext() {
assertThat(rootMock).isNotNull();
}
}
+
+ @Test
+ void should_be_injected_correct_instance_of_mock() {
+ assertThat(classWithDependency.dependency).isSameAs(rootMock);
+ }
+
+ private static class ClassWithDependency {
+ private final Function<Integer, String> dependency;
+
+ private ClassWithDependency(Function<Integer, String> dependency) {
+ this.dependency = dependency;
+ }
+ }
}
| train | train | 2018-03-25T15:09:22 | "2018-03-25T12:31:24Z" | szpak | train |
mockito/mockito/1348_1350 | mockito/mockito | mockito/mockito/1348 | mockito/mockito/1350 | [
"timestamp(timedelta=0.0, similarity=0.8727645311881962)",
"keyword_issue_to_pr",
"keyword_pr_to_issue"
] | c5ebb9c7339aa04a7c2f9e5f9dd6de37d5c8e681 | 6e94d29d1e049cf773ad2423ca55485ed71be558 | [
"I am 👍 for this feature with the following use case:\r\n\r\nInitialization of local variable mocks. Previously this would be `Mock<Generic> mock = mock(Mock.class)`. However, this loses the type-signature of `Generic`. With parameter mocks, we can do `@Mock Mock<Generic> mock` and still maintain the generic type signature.",
"I should also note that I haven't personally used parameter resolution the way it's shown above. Our team generally either injects the mock object at the class level and configures it in ``@BeforeEach`` **OR** we inject the mock object in the test method and configure it at the top of the test method's block.",
"Yes agreed. Rather than some \"magic\" shared by methods, I think a generics-type-safe replacement for local mock initialization is a lot better.",
"I just edited the description of this issue to include a link to the sample ``MockitoExtension`` (I had intended to provide that reference originally). I don't know if I'd refer to the the methods sharing the parameter instance as \"magic\" but without looking at the code it certainly isn't clear that the parameters are the shared if the types and names match. I definitely think that there are use-cases for this technique and the use of ``ExtensionContext.Store`` is a great way to provide references to objects from different methods. My main concern is that when there is a name collision and the types match, you might end up with behavior that's really hard to understand (without knowing how the underlying extension works).\r\n\r\nI'm not sure I'm a fan of the syntax you described above as it seems more redundant than ``@Mock MyWeirdThing myWeirdMock`` - I'm guessing I'm misunderstanding your intention (I get the erasure part).",
"In Junit 4, local mock initialization would be \r\n\r\n```java\r\nclass Test {\r\n @Test\r\n public void test() {\r\n Mock<String> mock = Mockito.mock(Mock.class);\r\n }\r\n class Mock<T> {}\r\n}\r\n```\r\nThis would issue a warning saying that the generic type of `String` is not correctly created by `Mockito.mock`. (Even though we know that our mocks will work)\r\n\r\nWith this feature, in JUnit 5, we can have:\r\n\r\n```java\r\nclass Test {\r\n @Test\r\n public void test(@Mock Mock<String> mock) {\r\n }\r\n class Mock<T> {}\r\n}\r\n```\r\nAnd the compiler will not warn any longer.",
"I don't remember ever seeing that warning - Perhaps because I've always used the Mockito runner or rule?",
"Correct. You do not get that warning when using the runner. But then you have mocks that are used in every single test. This targets the use case where you need 1 extra mock in only 1 testcase.",
"And if the ``MockitoExtension`` is the JUnit 5 replacement for the runner or rule, why wouldn't those warnings also be suppressed?",
"Because the point of Mock initialization is different. JUnit 4 only supported for attributes. We are now talking about method parameters. Hopefully when I implement this logic, it is more clear to you 😄 ",
"I'm not trying to be argumentative ... but as a pretty heavy user of the prototype ``MockitoExtension`` in the https://github.com/junit-team/junit5-samples project we'd have a lot of tests to update with this syntax. We'll also need to make sure the example in the users guide and (if they're kept) the code in the junit-samples project matches the official implementation. At this point I should probably let junit-team (I wish I could use a mention here) coordinate that with you.\r\n\r\n@sbrannen @marcphilipp @sormuras",
"Looking at the source of https://github.com/junit-team/junit5-samples/blob/7bf40178345d5ca837579c8ddb8c025401a98788/junit5-mockito-extension/src/main/java/com/example/mockito/MockitoExtension.java I think we should be fine. I will let you know when the PR is open so that you can test that out.\r\n\r\nOne note: the Mockito team was not involved with the development of the prototype, but I think we will approach very similar capabilities.",
"I was looking at https://github.com/junit-team/junit5-samples/blob/master/junit5-mockito-extension/src/test/java/com/example/mockito/MockitoExtensionWithNestedTests.java because it's got a bunch of use cases including test-local mocks and the \"magic\" you referred to above. Thinking though the syntax change you're describing, I'll assume that the tests would still run but with the same warning?\r\n\r\nI do realize that the Mockito team didn't produce the prototype and it would be unrealistic to think that you should be permanently limited by it architecturally. I did however think that the syntax \"proposed\" by the prototype was consistent with the field injection that already existed in Mockito. I'm going to assume that what is produced as the official extension will be well integrated and well maintained - and I never complain about stable tooling!",
"Opened #1350 with a proposal implementation.",
"Okay, to write down the reason I think mock sharing by parameter is not a good idea:\r\n\r\nFirst of all, there is a lot of duplicate code. For every test method, you need to list the mocks, which results in duplicate. Rather, using fields for these mocks removes the duplication.\r\n\r\nSecondly, by relying on fields, the compiler will complain when you make a typo (or change a type). With parameters, you rely on the name (String-based) and the type declared. Both are not compiler safe.\r\n\r\nLastly, because you can rely on fields, refactoring is a lot easier, as IDE's support renaming by field. This is not possible for parameters.\r\n\r\nFor these 3 reasons, I see field mock sharing superior to parameter mock sharing and am therefore against introducing this logic in the parameter resolution.",
"> For these 3 reasons, I see field mock sharing superior to parameter mock sharing and am therefore against introducing this logic in the parameter resolution.\r\n\r\nI totally understand the rationale. 👍 ",
"What about support for `@Spy` and `@Captor`? Should new issues be created, or can it be part of this one?",
"`@Spy` makes no sense, as it requires a concrete instance. `@Captor` could be done. Let's discuss that in a different issue :+1: as this issue has been resolved.",
"My memory was incorrect, as #1350 has NOT been merged yet.",
">`@Spy` makes no sense\r\n\r\nYou are completely right 😄.\r\n\r\nI've created #1382 for adding support for `@Captor`",
"There's `Mockito.spy(Class)` which would work for a method parameter.",
"@marcphilipp Ah, yes I see now. Not sure how useful that actually is, as I only learned today we expose that API 😂 "
] | [] | "2018-03-26T13:38:17Z" | [
"junit5"
] | Support @Mock injection in JUnit 5 method parameters | JUnit 5 has the ability to "inject" parameters into test methods via an extensible ``ParameterResolver`` interface. The JUnit 5 users guide provides an example that shows how such a ``ParameterResolver`` can supply mock objects as test parameters as follows (shamelessly copied from https://junit.org/junit5/docs/current/user-guide/#writing-tests-dependency-injection):
```
@ExtendWith(MockitoExtension.class)
class MyMockitoTest {
@BeforeEach
void init(@Mock Person person) {
when(person.getName()).thenReturn("Dilbert");
}
@Test
void simpleTestWithInjectedMock(@Mock Person person) {
assertEquals("Dilbert", person.getName());
}
}
```
The prototype ``MockitoExtension`` provided in the JUnit 5 samples project shows a simple implementation of the required ``supportsParameter()`` and ``resolveParameter()`` methods. (See: https://github.com/junit-team/junit5-samples/blob/r5.1.0/junit5-mockito-extension/src/main/java/com/example/mockito/MockitoExtension.java)
[ ] Add the ability to inject mock objects into test method parameters to the official ``MockitoExtension``. References #445 | [
"gradle/dependencies.gradle",
"src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"gradle/dependencies.gradle",
"src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java"
] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index 7a3cdfa2a7..784db4b47d 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -5,7 +5,7 @@ ext {
def versions = [:]
versions.bytebuddy = '1.8.15'
-versions.junitJupiter = '5.1.0'
+versions.junitJupiter = '5.1.1'
libraries.junit4 = 'junit:junit:4.12'
libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}"
diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
index 2f6757da78..91086d2a19 100644
--- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
+++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
@@ -14,13 +14,18 @@
* Instantiates a mock on a field annotated by {@link Mock}
*/
public class MockAnnotationProcessor implements FieldAnnotationProcessor<Mock> {
+ @Override
public Object process(Mock annotation, Field field) {
+ return processAnnotationForMock(annotation, field.getType(), field.getName());
+ }
+
+ public static Object processAnnotationForMock(Mock annotation, Class<?> type, String name) {
MockSettings mockSettings = Mockito.withSettings();
if (annotation.extraInterfaces().length > 0) { // never null
mockSettings.extraInterfaces(annotation.extraInterfaces());
}
if ("".equals(annotation.name())) {
- mockSettings.name(field.getName());
+ mockSettings.name(name);
} else {
mockSettings.name(annotation.name());
}
@@ -33,6 +38,6 @@ public Object process(Mock annotation, Field field) {
// see @Mock answer default value
mockSettings.defaultAnswer(annotation.answer());
- return Mockito.mock(field.getType(), mockSettings);
+ return Mockito.mock(type, mockSettings);
}
}
diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
index ad1d434d3d..54510daec1 100644
--- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
+++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
@@ -5,19 +5,20 @@
package org.mockito.junit.jupiter;
-import java.util.LinkedHashSet;
-import java.util.Optional;
-import java.util.Set;
-import org.junit.jupiter.api.extension.AfterEachCallback;
-import org.junit.jupiter.api.extension.BeforeEachCallback;
-import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
-import org.junit.jupiter.api.extension.TestInstancePostProcessor;
+import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoSession;
+import org.mockito.internal.configuration.MockAnnotationProcessor;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.quality.Strictness;
+import java.lang.reflect.Parameter;
+import java.util.LinkedHashSet;
+import java.util.Optional;
+import java.util.Set;
+
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
@@ -32,7 +33,7 @@
* public class ExampleTest {
*
* @Mock
- * private List list;
+ * private List<Integer> list;
*
* @Test
* public void shouldDoSomething() {
@@ -48,7 +49,7 @@
* public class ExampleTest {
*
* @Mock
- * private List list;
+ * private List<Integer> list;
*
* @Test
* public void shouldDoSomething() {
@@ -56,8 +57,57 @@
* }
* }
* </code></pre>
+ *
+ * This extension also supports JUnit Jupiter's method parameters.
+ * Use parameters for initialization of mocks that you use only in that specific test method.
+ * In other words, where you would initialize local mocks in JUnit 4 by calling {@link Mockito#mock(Class)},
+ * use the method parameter. This is especially beneficial when initializing a mock with generics, as you no
+ * longer get a warning about "Unchecked assignment".
+ * Please refer to JUnit Jupiter's documentation to learn when method parameters are useful.
+ *
+ * <pre class="code"><code class="java">
+ * <b>@ExtendWith(MockitoExtension.class)</b>
+ * public class ExampleTest {
+ *
+ * @Mock
+ * private List<Integer> sharedList;
+ *
+ * @Test
+ * public void shouldDoSomething() {
+ * sharedList.add(100);
+ * }
+ *
+ * @Test
+ * public void hasLocalMockInThisTest(@Mock List<Integer> localList) {
+ * localList.add(100);
+ * sharedList.add(100);
+ * }
+ * }
+ * </code></pre>
+ *
+ * Lastly, the extension supports JUnit Jupiter's constructor parameters.
+ * This allows you to do setup work in the constructor and set
+ * your fields to <code>final</code>.
+ * Please refer to JUnit Jupiter's documentation to learn when constructor parameters are useful.
+ *
+ * <pre class="code"><code class="java">
+ * <b>@ExtendWith(MockitoExtension.class)</b>
+ * public class ExampleTest {
+ *
+ * private final List<Integer> sharedList;
+ *
+ * ExampleTest(@Mock sharedList) {
+ * this.sharedList = sharedList;
+ * }
+ *
+ * @Test
+ * public void shouldDoSomething() {
+ * sharedList.add(100);
+ * }
+ * }
+ * </code></pre>
*/
-public class MockitoExtension implements TestInstancePostProcessor,BeforeEachCallback, AfterEachCallback {
+public class MockitoExtension implements TestInstancePostProcessor,BeforeEachCallback, AfterEachCallback, ParameterResolver {
private final static Namespace MOCKITO = create("org.mockito");
@@ -161,4 +211,15 @@ public void afterEach(ExtensionContext context) {
.finishMocking();
}
+ @Override
+ public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ return parameterContext.isAnnotated(Mock.class);
+ }
+
+ @SuppressWarnings("ConstantConditions")
+ @Override
+ public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ final Parameter parameter = parameterContext.getParameter();
+ return MockAnnotationProcessor.processAnnotationForMock(parameterContext.findAnnotation(Mock.class).get(), parameter.getType(), parameter.getName());
+ }
}
| diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
index 47361589a5..df9fce5e88 100644
--- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
+++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
@@ -11,6 +11,7 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
+import org.mockito.internal.util.MockUtil;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
@@ -35,6 +36,32 @@ void can_set_stubs_on_initialized_mock() {
assertThat(rootMock.apply(10)).isEqualTo("Return");
}
+ @Test
+ void initializes_parameters(@Mock Function<String, String> localMock) {
+ Mockito.when(localMock.apply("Para")).thenReturn("Meter");
+ assertThat(localMock.apply("Para")).isEqualTo("Meter");
+ }
+
+ @Test
+ void initializes_parameters_with_custom_configuration(@Mock(name = "overriddenName") Function<String, String> localMock) {
+ assertThat(MockUtil.getMockName(localMock).toString()).isEqualTo("overriddenName");
+ }
+
+ @Nested
+ class NestedTestWithConstructorParameter {
+ private final Function<Integer, String> constructorMock;
+
+ NestedTestWithConstructorParameter(@Mock Function<Integer, String> constructorMock) {
+ this.constructorMock = constructorMock;
+ }
+
+ @Test
+ void can_inject_into_constructor_parameter() {
+ Mockito.when(constructorMock.apply(42)).thenReturn("42");
+ assertThat(constructorMock.apply(42)).isEqualTo("42");
+ }
+ }
+
@Nested
class NestedTestWithExtraMock {
@Mock Runnable nestedMock;
| test | train | 2018-07-27T06:35:15 | "2018-03-25T21:08:04Z" | smoyer64 | train |
mockito/mockito/1346_1350 | mockito/mockito | mockito/mockito/1346 | mockito/mockito/1350 | [
"keyword_issue_to_pr"
] | c5ebb9c7339aa04a7c2f9e5f9dd6de37d5c8e681 | 6e94d29d1e049cf773ad2423ca55485ed71be558 | [
"Hm that seems really weird. Could you please post the implementation of `TacticalStation` and `SpaceShip` (although I am assuming they are simple POJO's?)",
"(Oh never mind, I missed the small link at the end of the example to https://github.com/szpak/code-examples-and-poc/tree/mockito2junit5-bug/mockito2-junit5/src/main/java/info/solidsoft/blog/mockito/junit5 )",
"@szpak Please see https://github.com/mockito/mockito/blob/5e9a3c62fc1ca4cf12d5d19580613f418cebc895/subprojects/junit-jupiter/src/test/java/org/mockitousage/InjectMocksTest.java for a working test. I could make these tests fail with adding `final` to the field declaration, so that is what is going wrong. Removing `final` makes the tests pass.\r\n\r\nWhat I do not understand is how this could work with JUnit 4, as we have not changed any of that code. We are completely reusing all of that logic.",
"It also works with `final` if `MockitoAnnotations.initMocks(this);` is used. Therefore, I would suspect the way how it is triggered/executed in JUnit 5 extension.",
"@TimvdLippe @szpak I have debugged this issue a bit. Here is what I found: it does look like the problem is with triggering the same logic from `MockitoExtension.class`. \r\nThe root cause of the problem is that `beforeEach` creates two `testInstances` of the same test class for each test. \r\nLooks like method `collectParentTestInstances` is adding the same testInstance to the list of test instances.\r\nI can try to work on this issue if no one is assigned to is already.\r\n",
"PRs appreciated!\n\nOn Mon, 26 Mar 2018, 10:55 Serge Bishyr, <notifications@github.com> wrote:\n\n> @TimvdLippe <https://github.com/TimvdLippe> @szpak\n> <https://github.com/szpak> I have debugged this issue a bit. Here is what\n> I found: it does look like the problem is with triggering the same logic\n> from MockitoExtension.class.\n> The root cause of the problem is that beforeEach creates two testInstances\n> of the same test class for each test.\n> Looks like method collectParentTestInstances is adding the same\n> testInstance to the list of test instances.\n> I can try to work on this issue if no one is assigned to is already.\n>\n> —\n> You are receiving this because you were mentioned.\n>\n>\n> Reply to this email directly, view it on GitHub\n> <https://github.com/mockito/mockito/issues/1346#issuecomment-376094135>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AFrDb9w69sJERNCP5FZJXPrwdq0ltsI9ks5tiK0ZgaJpZM4S6Huw>\n> .\n>\n",
"Have added PR #1349 with the fix for the issue",
"It works flawlessly. Thanks @SeriyBg!\r\n\r\n@TimvdLippe As this bug can impact all those people preferring a constructor injection, what do you thing about releasing the new minor version (e.g. after #1350 is hopefully merged :) ) to Maven Central?",
"@szpak Yes after #1350 we will probably publish a new version. You can however already use the latest version from Bintray",
"I know Tim that I can, but JUnit 5 support is a notable feature and having it working correctly in the latest non-development version (available in Maven Central) seems very sensible for me. Great, that we agree on releasing a new stable (but IHMO still 2.17.x) version soon.",
"I'm seeing this same bug when using `SpringExtension.class` along with `MockitoExtension.class`:\r\n\r\n```\r\n@ExtendWith({MockitoExtension.class, SpringExtension.class})\r\npublic class InjectMocksTest {\r\n static class TacticalStation {}\r\n\r\n static class SpaceShip {\r\n private final TacticalStation tacticalStation;\r\n\r\n public SpaceShip(final TacticalStation tacticalStation) {\r\n this.tacticalStation = tacticalStation;\r\n }\r\n\r\n public TacticalStation getTacticalStation() {\r\n return tacticalStation;\r\n }\r\n }\r\n\r\n @InjectMocks\r\n private SpaceShip spaceShip;\r\n\r\n @Mock\r\n private TacticalStation tacticalStation;\r\n\r\n @Test\r\n public void shouldInjectMocks() {\r\n assertThat(tacticalStation).isNotNull();\r\n assertThat(spaceShip.getTacticalStation()).isEqualTo(tacticalStation);\r\n //Bug ↑ - different mocks are use in @Mock and @InjectMock\r\n }\r\n}\r\n```\r\n\r\nThis is using Mockito 3.1.0, JUnit 5.6.0, and Spring Boot 5.3.0.RELEASE.",
"> I'm seeing this same bug when using `SpringExtension.class` along with `MockitoExtension.class`:\r\n> \r\n> ```\r\n> @ExtendWith({MockitoExtension.class, SpringExtension.class})\r\n> public class InjectMocksTest {\r\n> static class TacticalStation {}\r\n> \r\n> static class SpaceShip {\r\n> private final TacticalStation tacticalStation;\r\n> \r\n> public SpaceShip(final TacticalStation tacticalStation) {\r\n> this.tacticalStation = tacticalStation;\r\n> }\r\n> \r\n> public TacticalStation getTacticalStation() {\r\n> return tacticalStation;\r\n> }\r\n> }\r\n> \r\n> @InjectMocks\r\n> private SpaceShip spaceShip;\r\n> \r\n> @Mock\r\n> private TacticalStation tacticalStation;\r\n> \r\n> @Test\r\n> public void shouldInjectMocks() {\r\n> assertThat(tacticalStation).isNotNull();\r\n> assertThat(spaceShip.getTacticalStation()).isEqualTo(tacticalStation);\r\n> //Bug ↑ - different mocks are use in @Mock and @InjectMock\r\n> }\r\n> }\r\n> ```\r\n> \r\n> This is using Mockito 3.1.0, JUnit 5.6.0, and Spring Boot 5.3.0.RELEASE.\r\n\r\nYes I am also facing this issue. Mine is also exactly the same scenario. Below are my dependencies,\r\norg.junit.jupiter:junit-jupiter-engine:5.6.0\r\norg.springframework.boot:spring-boot-starter:2.2.6.RELEASE\r\norg.springframework.boot:spring-boot-starter-test:2.2.6.RELEASE\r\norg.mockito:mockito-junit-jupiter:3.1.0"
] | [] | "2018-03-26T13:38:17Z" | [
"bug",
"injection",
"junit5"
] | Different mocks are used for @Mock and @InjectMock in the same test class with JUnit 5 extension | I've been playing with the new JUnit 5 support in Mockito 2.17.0. I have found that with `@Mock` and `@InjectMocks` used in the same test class different mocks are injected. I would expect to have the same mock reused (as it works with JUnit 4 or manual `@Mock` initialization).
Sample code:
```
@ExtendWith(MockitoExtension.class)
public class SpaceShip5BugMiniTest {
@InjectMocks
private SpaceShip spaceShip;
@Mock
private TacticalStation tacticalStation;
@Test
public void shouldInjectMocks() {
assertThat(tacticalStation).isNotNull();
assertThat(spaceShip.getTacticalStation()).isEqualTo(tacticalStation);
//Bug ↑ - different mocks are use in @Mock and @InjectMock
}
}
```
Error message:
```
org.opentest4j.AssertionFailedError:
Expecting:
<"tacticalStation (TacticalStation$MockitoMock$991606095@61d6015a)">
to be equal to:
<"tacticalStation (TacticalStation$MockitoMock$991606095@b62d79)">
but was not.
Expected :tacticalStation
Actual :tacticalStation
```
The minimal (non-)working example is available [here](https://github.com/szpak/code-examples-and-poc/tree/mockito2junit5-bug/mockito2-junit5).
@TimvdLippe Do you have an idea what could be wrong?
Mockito 2.17.0 (2.17.1 is not being released due to (https://github.com/mockito/shipkit/issues/679), junit-jupiter 5.1.0, OpenJDK 1.8.0_161, Linux.
### Checklist:
- [x] The mockito message in the stacktrace have useful information, but it didn't help
- [x] The problematic code (if that's possible) is copied here;
Note that some configuration are impossible to mock via Mockito
- [x] Provide versions (mockito / jdk / os / any other relevant information)
- [x] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
(same as any question on stackoverflow.com)
- [x] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md)
| [
"gradle/dependencies.gradle",
"src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"gradle/dependencies.gradle",
"src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java"
] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index 7a3cdfa2a7..784db4b47d 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -5,7 +5,7 @@ ext {
def versions = [:]
versions.bytebuddy = '1.8.15'
-versions.junitJupiter = '5.1.0'
+versions.junitJupiter = '5.1.1'
libraries.junit4 = 'junit:junit:4.12'
libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}"
diff --git a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
index 2f6757da78..91086d2a19 100644
--- a/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
+++ b/src/main/java/org/mockito/internal/configuration/MockAnnotationProcessor.java
@@ -14,13 +14,18 @@
* Instantiates a mock on a field annotated by {@link Mock}
*/
public class MockAnnotationProcessor implements FieldAnnotationProcessor<Mock> {
+ @Override
public Object process(Mock annotation, Field field) {
+ return processAnnotationForMock(annotation, field.getType(), field.getName());
+ }
+
+ public static Object processAnnotationForMock(Mock annotation, Class<?> type, String name) {
MockSettings mockSettings = Mockito.withSettings();
if (annotation.extraInterfaces().length > 0) { // never null
mockSettings.extraInterfaces(annotation.extraInterfaces());
}
if ("".equals(annotation.name())) {
- mockSettings.name(field.getName());
+ mockSettings.name(name);
} else {
mockSettings.name(annotation.name());
}
@@ -33,6 +38,6 @@ public Object process(Mock annotation, Field field) {
// see @Mock answer default value
mockSettings.defaultAnswer(annotation.answer());
- return Mockito.mock(field.getType(), mockSettings);
+ return Mockito.mock(type, mockSettings);
}
}
diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
index ad1d434d3d..54510daec1 100644
--- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
+++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
@@ -5,19 +5,20 @@
package org.mockito.junit.jupiter;
-import java.util.LinkedHashSet;
-import java.util.Optional;
-import java.util.Set;
-import org.junit.jupiter.api.extension.AfterEachCallback;
-import org.junit.jupiter.api.extension.BeforeEachCallback;
-import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
-import org.junit.jupiter.api.extension.TestInstancePostProcessor;
+import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoSession;
+import org.mockito.internal.configuration.MockAnnotationProcessor;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.quality.Strictness;
+import java.lang.reflect.Parameter;
+import java.util.LinkedHashSet;
+import java.util.Optional;
+import java.util.Set;
+
import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
@@ -32,7 +33,7 @@
* public class ExampleTest {
*
* @Mock
- * private List list;
+ * private List<Integer> list;
*
* @Test
* public void shouldDoSomething() {
@@ -48,7 +49,7 @@
* public class ExampleTest {
*
* @Mock
- * private List list;
+ * private List<Integer> list;
*
* @Test
* public void shouldDoSomething() {
@@ -56,8 +57,57 @@
* }
* }
* </code></pre>
+ *
+ * This extension also supports JUnit Jupiter's method parameters.
+ * Use parameters for initialization of mocks that you use only in that specific test method.
+ * In other words, where you would initialize local mocks in JUnit 4 by calling {@link Mockito#mock(Class)},
+ * use the method parameter. This is especially beneficial when initializing a mock with generics, as you no
+ * longer get a warning about "Unchecked assignment".
+ * Please refer to JUnit Jupiter's documentation to learn when method parameters are useful.
+ *
+ * <pre class="code"><code class="java">
+ * <b>@ExtendWith(MockitoExtension.class)</b>
+ * public class ExampleTest {
+ *
+ * @Mock
+ * private List<Integer> sharedList;
+ *
+ * @Test
+ * public void shouldDoSomething() {
+ * sharedList.add(100);
+ * }
+ *
+ * @Test
+ * public void hasLocalMockInThisTest(@Mock List<Integer> localList) {
+ * localList.add(100);
+ * sharedList.add(100);
+ * }
+ * }
+ * </code></pre>
+ *
+ * Lastly, the extension supports JUnit Jupiter's constructor parameters.
+ * This allows you to do setup work in the constructor and set
+ * your fields to <code>final</code>.
+ * Please refer to JUnit Jupiter's documentation to learn when constructor parameters are useful.
+ *
+ * <pre class="code"><code class="java">
+ * <b>@ExtendWith(MockitoExtension.class)</b>
+ * public class ExampleTest {
+ *
+ * private final List<Integer> sharedList;
+ *
+ * ExampleTest(@Mock sharedList) {
+ * this.sharedList = sharedList;
+ * }
+ *
+ * @Test
+ * public void shouldDoSomething() {
+ * sharedList.add(100);
+ * }
+ * }
+ * </code></pre>
*/
-public class MockitoExtension implements TestInstancePostProcessor,BeforeEachCallback, AfterEachCallback {
+public class MockitoExtension implements TestInstancePostProcessor,BeforeEachCallback, AfterEachCallback, ParameterResolver {
private final static Namespace MOCKITO = create("org.mockito");
@@ -161,4 +211,15 @@ public void afterEach(ExtensionContext context) {
.finishMocking();
}
+ @Override
+ public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ return parameterContext.isAnnotated(Mock.class);
+ }
+
+ @SuppressWarnings("ConstantConditions")
+ @Override
+ public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
+ final Parameter parameter = parameterContext.getParameter();
+ return MockAnnotationProcessor.processAnnotationForMock(parameterContext.findAnnotation(Mock.class).get(), parameter.getType(), parameter.getName());
+ }
}
| diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
index 47361589a5..df9fce5e88 100644
--- a/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
+++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/JunitJupiterTest.java
@@ -11,6 +11,7 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
+import org.mockito.internal.util.MockUtil;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
@@ -35,6 +36,32 @@ void can_set_stubs_on_initialized_mock() {
assertThat(rootMock.apply(10)).isEqualTo("Return");
}
+ @Test
+ void initializes_parameters(@Mock Function<String, String> localMock) {
+ Mockito.when(localMock.apply("Para")).thenReturn("Meter");
+ assertThat(localMock.apply("Para")).isEqualTo("Meter");
+ }
+
+ @Test
+ void initializes_parameters_with_custom_configuration(@Mock(name = "overriddenName") Function<String, String> localMock) {
+ assertThat(MockUtil.getMockName(localMock).toString()).isEqualTo("overriddenName");
+ }
+
+ @Nested
+ class NestedTestWithConstructorParameter {
+ private final Function<Integer, String> constructorMock;
+
+ NestedTestWithConstructorParameter(@Mock Function<Integer, String> constructorMock) {
+ this.constructorMock = constructorMock;
+ }
+
+ @Test
+ void can_inject_into_constructor_parameter() {
+ Mockito.when(constructorMock.apply(42)).thenReturn("42");
+ assertThat(constructorMock.apply(42)).isEqualTo("42");
+ }
+ }
+
@Nested
class NestedTestWithExtraMock {
@Mock Runnable nestedMock;
| val | train | 2018-07-27T06:35:15 | "2018-03-25T12:31:24Z" | szpak | train |
mockito/mockito/1386_1387 | mockito/mockito | mockito/mockito/1386 | mockito/mockito/1387 | [
"timestamp(timedelta=2.0, similarity=0.8688001584516274)"
] | f5c988689df5313d3af311e78169c73e31f569da | 61655a491643f042a85203c1ea9433f717799d93 | [] | [] | "2018-05-13T21:56:54Z" | [] | Add AtMostOnce(),rename one testClass and one TODO. | Hi,
I would like to make a quick contribution on this project.
I add atMostOnce(), it seem's not to be a big feature. I just want to highlight the fact you have the function atLeastOnce() but nothing for the atMostOnce case.
I rename the testClass ThreadVerifiesContinuoslyInteractingMockTest on ThreadVerifiesContinuouslyInteractingMockTest and the TODO on toString() from HamcrestArgumentMatcher<T>.
| [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java",
"src/main/java/org/mockito/internal/verification/VerificationModeFactory.java",
"src/main/java/org/mockito/internal/verification/VerificationWrapper.java",
"src/main/java/org/mockito/verification/VerificationAfterDelay.java"
] | [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java",
"src/main/java/org/mockito/internal/verification/VerificationModeFactory.java",
"src/main/java/org/mockito/internal/verification/VerificationWrapper.java",
"src/main/java/org/mockito/verification/VerificationAfterDelay.java"
] | [
"src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java",
"src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java",
"src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java"
] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 5066eec3d7..ec710a66a5 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -320,6 +320,7 @@
* verify(mockedList, never()).add("never happened");
*
* //verification using atLeast()/atMost()
+ * verify(mockedList, atMostOnce()).add("once");
* verify(mockedList, atLeastOnce()).add("three times");
* verify(mockedList, atLeast(2)).add("three times");
* verify(mockedList, atMost(5)).add("three times");
@@ -2724,6 +2725,22 @@ public static VerificationMode atLeast(int minNumberOfInvocations) {
return VerificationModeFactory.atLeast(minNumberOfInvocations);
}
+ /**
+ * Allows at-most-once verification. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, atMostOnce()).someMethod("some arg");
+ * </code></pre>
+ * Alias to <code>atMost(1)</code>.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return verification mode
+ */
+ @CheckReturnValue
+ public static VerificationMode atMostOnce() {
+ return VerificationModeFactory.atMostOnce();
+ }
+
/**
* Allows at-most-x verification. E.g:
* <pre class="code"><code class="java">
diff --git a/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java b/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
index 9892422e77..5183136ae7 100644
--- a/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
+++ b/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
@@ -26,7 +26,7 @@ public boolean isVarargMatcher() {
}
public String toString() {
- //TODO SF add unit tests and integ test coverage for describeTo()
+ //TODO SF add unit tests and integ test coverage for toString()
return StringDescription.toString(matcher);
}
}
diff --git a/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java b/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java
index 1f8e8b6c25..b7c882daf6 100644
--- a/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationModeFactory.java
@@ -33,6 +33,10 @@ public static NoMoreInteractions noMoreInteractions() {
return new NoMoreInteractions();
}
+ public static VerificationMode atMostOnce() {
+ return atMost(1);
+ }
+
public static VerificationMode atMost(int maxNumberOfInvocations) {
return new AtMost(maxNumberOfInvocations);
}
diff --git a/src/main/java/org/mockito/internal/verification/VerificationWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapper.java
index b471342cf9..66336a94f1 100644
--- a/src/main/java/org/mockito/internal/verification/VerificationWrapper.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationWrapper.java
@@ -37,6 +37,10 @@ public VerificationMode atLeast(int minNumberOfInvocations) {
return copySelfWithNewVerificationMode(VerificationModeFactory.atLeast(minNumberOfInvocations));
}
+ public VerificationMode atMostOnce() {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.atMostOnce());
+ }
+
public VerificationMode atMost(int maxNumberOfInvocations) {
return copySelfWithNewVerificationMode(VerificationModeFactory.atMost(maxNumberOfInvocations));
}
diff --git a/src/main/java/org/mockito/verification/VerificationAfterDelay.java b/src/main/java/org/mockito/verification/VerificationAfterDelay.java
index b48cb6ba45..1b88ec1fad 100644
--- a/src/main/java/org/mockito/verification/VerificationAfterDelay.java
+++ b/src/main/java/org/mockito/verification/VerificationAfterDelay.java
@@ -49,6 +49,12 @@ public interface VerificationAfterDelay extends VerificationMode {
*/
VerificationMode atLeast(int minNumberOfInvocations);
+ /**
+ * Verifies that there is most 1 invocation during the given period. This will wait the full period given,
+ * unless too many invocations occur (in which case there will be an immediate failure)
+ */
+ VerificationMode atMostOnce();
+
/**
* Verifies that there is are most N invocations during the given period. This will wait the full period given,
* unless too many invocations occur (in which case there will be an immediate failure)
| diff --git a/src/test/java/org/concurrentmockito/ThreadVerifiesContinuoslyInteractingMockTest.java b/src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java
similarity index 94%
rename from src/test/java/org/concurrentmockito/ThreadVerifiesContinuoslyInteractingMockTest.java
rename to src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java
index 0f91bb3202..2cf6c5bcde 100644
--- a/src/test/java/org/concurrentmockito/ThreadVerifiesContinuoslyInteractingMockTest.java
+++ b/src/test/java/org/concurrentmockito/ThreadVerifiesContinuouslyInteractingMockTest.java
@@ -14,7 +14,7 @@
import static org.mockito.Mockito.verify;
//this test exposes the problem most of the time
-public class ThreadVerifiesContinuoslyInteractingMockTest extends TestBase {
+public class ThreadVerifiesContinuouslyInteractingMockTest extends TestBase {
@Mock private IMethods mock;
diff --git a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
index 0e574f0c5e..82753d1de2 100644
--- a/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
+++ b/src/test/java/org/mockitousage/stubbing/DeepStubbingTest.java
@@ -280,7 +280,7 @@ public void times_never_atLeast_atMost_verificationModes_should_work() {
verify(person.getAddress("the docks").getStreet(), times(3)).getName();
verify(person.getAddress("the docks").getStreet(Locale.CHINESE), never()).getName();
- verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atMost(1)).getName();
+ verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atMostOnce()).getName();
}
diff --git a/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java b/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java
index 2756ef8c71..d7a4d92c50 100644
--- a/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java
+++ b/src/test/java/org/mockitousage/verification/AtMostXVerificationTest.java
@@ -20,6 +20,7 @@
import static org.junit.Assert.fail;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.atMost;
+import static org.mockito.Mockito.atMostOnce;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -37,7 +38,7 @@ public void shouldVerifyAtMostXTimes() throws Exception {
verify(mock, atMost(3)).clear();
try {
- verify(mock, atMost(1)).clear();
+ verify(mock, atMostOnce()).clear();
fail();
} catch (MoreThanAllowedActualInvocations e) {}
}
@@ -69,7 +70,7 @@ public void shouldPrintDecentMessage() throws Exception {
mock.clear();
try {
- verify(mock, atMost(1)).clear();
+ verify(mock, atMostOnce()).clear();
fail();
} catch (MoreThanAllowedActualInvocations e) {
assertEquals("\nWanted at most 1 time but was 2", e.getMessage());
@@ -82,7 +83,7 @@ public void shouldNotAllowInOrderMode() throws Exception {
InOrder inOrder = inOrder(mock);
try {
- inOrder.verify(mock, atMost(1)).clear();
+ inOrder.verify(mock, atMostOnce()).clear();
fail();
} catch (MockitoException e) {
assertEquals("AtMost is not implemented to work with InOrder", e.getMessage());
| train | train | 2019-05-03T13:37:18 | "2018-05-13T21:23:03Z" | Ingvir | train |
mockito/mockito/1390_1391 | mockito/mockito | mockito/mockito/1390 | mockito/mockito/1391 | [
"keyword_pr_to_issue"
] | 758ca3782fba18b8eaf1faed5d68084145f8802d | 3f96f3b5adc7618ab0dc95d712a7b19b6b6e85ac | [] | [] | "2018-05-17T09:26:34Z" | [
"junit5"
] | MockitoExtension cannot be registered as a global junit5 extension. | `MockitoExtension` doesn't expose its constructor so it can't be loaded by `ServiceLoader.`
When trying to register `MockitoExtension` for automatic use using a file named `META-INF\services\org.junit.jupiter.api.extension.Extension` and content `org.mockito.junit.jupiter.MockitoExtension`
the below error is thrown, using mockito-junit-jupiter 2.18.3
```
org.junit.jupiter.api.extension.Extension: org.mockito.junit.jupiter.MockitoExtension Unable to get public no-arg constructor
java.util.ServiceConfigurationError: org.junit.jupiter.api.extension.Extension: org.mockito.junit.jupiter.MockitoExtension Unable to get public no-arg constructor
at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:581)
at java.base/java.util.ServiceLoader.getConstructor(ServiceLoader.java:672)
at java.base/java.util.ServiceLoader.access$1000(ServiceLoader.java:390)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(ServiceLoader.java:1232)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(ServiceLoader.java:1264)
at java.base/java.util.ServiceLoader$2.hasNext(ServiceLoader.java:1299)
at java.base/java.util.ServiceLoader$3.hasNext(ServiceLoader.java:1384)
at java.base/java.lang.Iterable.forEach(Iterable.java:74)
at org.junit.jupiter.engine.extension.ExtensionRegistry.registerAutoDetectedExtensions(ExtensionRegistry.java:102)
at org.junit.jupiter.engine.extension.ExtensionRegistry.createRegistryWithDefaultExtensions(ExtensionRegistry.java:86)
at org.junit.jupiter.engine.descriptor.JupiterEngineDescriptor.prepare(JupiterEngineDescriptor.java:37)
at org.junit.jupiter.engine.descriptor.JupiterEngineDescriptor.prepare(JupiterEngineDescriptor.java:28)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.prepare(HierarchicalTestExecutor.java:89)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:74)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:92)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$100(JUnitPlatformTestClassProcessor.java:77)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:73)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy1.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:123)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: java.lang.NoSuchMethodException: org.mockito.junit.jupiter.MockitoExtension.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3302)
at java.base/java.lang.Class.getConstructor(Class.java:2110)
at java.base/java.util.ServiceLoader$1.run(ServiceLoader.java:659)
at java.base/java.util.ServiceLoader$1.run(ServiceLoader.java:656)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.util.ServiceLoader.getConstructor(ServiceLoader.java:667)
... 46 more
```
- [X] The mockito message in the stacktrace have useful information, but it didn't help
- [X] The problematic code (if that's possible) is copied here;
Note that some configuration are impossible to mock via Mockito
- [X] Provide versions (mockito / jdk / os / any other relevant information)
- [X] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
(same as any question on stackoverflow.com)
- [X] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md) | [
"settings.gradle",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"settings.gradle",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java",
"subprojects/junitJupiterExtensionTest/junitJupiterExtensionTest.gradle"
] | [
"subprojects/junitJupiterExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java",
"subprojects/junitJupiterExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension",
"subprojects/junitJupiterExtensionTest/src/test/resources/junit-platform.properties"
] | diff --git a/settings.gradle b/settings.gradle
index 67fdf19066..74b7a84452 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -5,6 +5,7 @@ include 'extTest'
include 'kotlinTest'
include 'android'
include 'junit-jupiter'
+include 'junitJupiterExtensionTest'
rootProject.name = 'mockito'
diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
index 1ee5a3e02c..ad1d434d3d 100644
--- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
+++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
@@ -66,9 +66,9 @@ public class MockitoExtension implements TestInstancePostProcessor,BeforeEachCal
private final Strictness strictness;
- // This constructor is invoked by JUnit Jupiter via reflection
+ // This constructor is invoked by JUnit Jupiter via reflection or ServiceLoader
@SuppressWarnings("unused")
- private MockitoExtension() {
+ public MockitoExtension() {
this(Strictness.STRICT_STUBS);
}
diff --git a/subprojects/junitJupiterExtensionTest/junitJupiterExtensionTest.gradle b/subprojects/junitJupiterExtensionTest/junitJupiterExtensionTest.gradle
new file mode 100644
index 0000000000..1761dcd46d
--- /dev/null
+++ b/subprojects/junitJupiterExtensionTest/junitJupiterExtensionTest.gradle
@@ -0,0 +1,18 @@
+apply from: "$rootDir/gradle/dependencies.gradle"
+
+apply plugin: 'java'
+description = "End-to-end tests for automatic registration of MockitoExtension."
+
+sourceCompatibility = 1.8
+
+dependencies {
+ testCompile project(":junit-jupiter")
+ testCompile libraries.assertj
+ testCompile libraries.junitPlatformLauncher
+ testCompile libraries.junitJupiterApi
+ testRuntime libraries.junitJupiterEngine
+}
+
+test {
+ useJUnitPlatform()
+}
| diff --git a/subprojects/junitJupiterExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java b/subprojects/junitJupiterExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java
new file mode 100644
index 0000000000..a0d545c6b1
--- /dev/null
+++ b/subprojects/junitJupiterExtensionTest/src/test/java/org/mockitousage/NoExtendsTest.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitousage;
+
+
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+class NoExtendsTest {
+
+ @Mock
+ private List<String> mock;
+
+ @Test
+ void runs() {
+ when(mock.get(0)).thenReturn("foo");
+ assertThat(mock.get(0)).isEqualTo("foo");
+ }
+}
diff --git a/subprojects/junitJupiterExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/subprojects/junitJupiterExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension
new file mode 100644
index 0000000000..02593efe36
--- /dev/null
+++ b/subprojects/junitJupiterExtensionTest/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension
@@ -0,0 +1,1 @@
+org.mockito.junit.jupiter.MockitoExtension
diff --git a/subprojects/junitJupiterExtensionTest/src/test/resources/junit-platform.properties b/subprojects/junitJupiterExtensionTest/src/test/resources/junit-platform.properties
new file mode 100644
index 0000000000..25ce5c9844
--- /dev/null
+++ b/subprojects/junitJupiterExtensionTest/src/test/resources/junit-platform.properties
@@ -0,0 +1,1 @@
+junit.jupiter.extensions.autodetection.enabled = true
| train | train | 2018-04-28T11:45:47 | "2018-05-17T09:25:55Z" | anuraaga | train |
mockito/mockito/1401_1402 | mockito/mockito | mockito/mockito/1401 | mockito/mockito/1402 | [
"keyword_pr_to_issue",
"timestamp(timedelta=5.0, similarity=0.8708289949970366)"
] | 6ab43cd4651bde6aac54071caa9594dce55526f6 | c2034ea73dda4c4ef0f4fdcfdfa0981230e5dfc1 | [] | [] | "2018-06-06T16:33:06Z" | [] | VarargsMatcher doesn't work correctly when using HamcrestMatchers in Mockito 2 | ```
class A {
private B b;
public A(B b) {
this.b = b;
}
public Integer perform() {
return b.run("abcd", 1L, 2L);
}
}
class B {
public Integer run(String str, Long... price) {
return 10;
}
}
class HamcrestVarArgsMatcher extends TypeSafeMatcher<Long> implements VarargMatcher {
protected boolean matchesSafely(Long item) {
return item < 3;
}
public void describeTo(Description description) {
}
}
class Test {
@Test
public void varArgsMatcherUsingHamcrestMatcherWorks() {
B b = Mockito.mock(B.class);
A a = new A(b);
when(b.run(eq("abcd"), MockitoHamcrest.argThat(new HamcrestVarArgsMatcher()))).thenReturn(15);
assertThat(a.perform(), is(15)); // Actually returns 0
}
}
``` | [
"src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java",
"src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java"
] | [
"src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java",
"src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java"
] | [
"src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java"
] | diff --git a/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java b/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
index f5216eefa1..9892422e77 100644
--- a/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
+++ b/src/main/java/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
@@ -7,6 +7,7 @@
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.VarargMatcher;
public class HamcrestArgumentMatcher<T> implements ArgumentMatcher<T> {
@@ -20,6 +21,10 @@ public boolean matches(Object argument) {
return this.matcher.matches(argument);
}
+ public boolean isVarargMatcher() {
+ return matcher instanceof VarargMatcher;
+ }
+
public String toString() {
//TODO SF add unit tests and integ test coverage for describeTo()
return StringDescription.toString(matcher);
diff --git a/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
index e085c25a32..e47156f07f 100644
--- a/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
+++ b/src/main/java/org/mockito/internal/invocation/MatcherApplicationStrategy.java
@@ -12,6 +12,7 @@
import java.util.List;
import org.mockito.ArgumentMatcher;
+import org.mockito.internal.hamcrest.HamcrestArgumentMatcher;
import org.mockito.internal.matchers.CapturingMatcher;
import org.mockito.internal.matchers.VarargMatcher;
import org.mockito.invocation.Invocation;
@@ -95,15 +96,19 @@ private static MatcherApplicationType getMatcherApplicationType(Invocation invoc
return ONE_MATCHER_PER_ARGUMENT;
}
- if (rawArguments == matcherCount && isLastMatcherVargargMatcher(matchers)) {
+ if (rawArguments == matcherCount && isLastMatcherVarargMatcher(matchers)) {
return MATCH_EACH_VARARGS_WITH_LAST_MATCHER;
}
return ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
}
- private static boolean isLastMatcherVargargMatcher(final List<ArgumentMatcher<?>> matchers) {
- return lastMatcher(matchers) instanceof VarargMatcher;
+ private static boolean isLastMatcherVarargMatcher(final List<ArgumentMatcher<?>> matchers) {
+ ArgumentMatcher<?> argumentMatcher = lastMatcher(matchers);
+ if (argumentMatcher instanceof HamcrestArgumentMatcher<?>) {
+ return ((HamcrestArgumentMatcher<?>) argumentMatcher).isVarargMatcher();
+ }
+ return argumentMatcher instanceof VarargMatcher;
}
private static List<ArgumentMatcher<?>> appendLastMatcherNTimes(List<ArgumentMatcher<?>> matchers, int timesToAppendLastMatcher) {
| diff --git a/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
index ce389b09b0..46a75eb25e 100644
--- a/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
+++ b/src/test/java/org/mockito/internal/invocation/MatcherApplicationStrategyTest.java
@@ -14,13 +14,17 @@
import java.util.ArrayList;
import java.util.List;
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
+import org.mockito.internal.hamcrest.HamcrestArgumentMatcher;
import org.mockito.internal.matchers.Any;
import org.mockito.internal.matchers.Equals;
import org.mockito.internal.matchers.InstanceOf;
+import org.mockito.internal.matchers.VarargMatcher;
import org.mockito.invocation.Invocation;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@@ -186,6 +190,27 @@ public void shouldMatchAnyVarargEvenIfMatcherIsDecorated() {
recordAction.assertContainsExactly(ANY, ANY);
}
+ @Test
+ public void shouldMatchAnyVarargEvenIfMatcherIsWrappedInHamcrestMatcher() {
+ // given
+ invocation = varargs("1", "2");
+ HamcrestArgumentMatcher argumentMatcher = new HamcrestArgumentMatcher(new IntMatcher());
+ matchers = asList(argumentMatcher);
+
+ // when
+ getMatcherApplicationStrategyFor(invocation, matchers).forEachMatcherAndArgument(recordAction);
+
+ // then
+ recordAction.assertContainsExactly(argumentMatcher, argumentMatcher);
+ }
+
+ class IntMatcher extends BaseMatcher<Integer> implements VarargMatcher {
+ public boolean matches(Object o) {
+ return true;
+ }
+ public void describeTo(Description description) {}
+ }
+
private Invocation mixedVarargs(Object a, String... s) {
mock.mixedVarargs(a, s);
return getLastInvocation();
| train | train | 2018-06-05T16:33:56 | "2018-06-06T16:29:09Z" | aj-jaswanth | train |
mockito/mockito/1419_1426 | mockito/mockito | mockito/mockito/1419 | mockito/mockito/1426 | [
"timestamp(timedelta=0.0, similarity=0.8555848687526292)",
"keyword_pr_to_issue"
] | 4f72147c464c1a8a642d01fc3334e98e92b464cd | 5fc152d778584e2c4890d5ffd453f95b9df700de | [
"asm 6.2 alone does not fix this, neither does upgrading to latest bytebuddy help here.\r\nThe combination of asm 6.2, latest bytebuddy, a minor code change in mockito and setting `-Dnet.bytebuddy.experimental=true` helps here.",
"mockito-core-2.21.0.jar \t\r\nbyte-buddy-1.8.15.jar\r\n\r\nwith org.mockito.plugins.MockMaker \"mock-maker-inline\" the fix is not working with java 1.8_172 and java 11-ea+24.\r\n\r\nwithout \"mock-maker-inline\" it works\r\n\r\norg.mockito.exceptions.base.MockitoException: \r\nMockito cannot mock this class: interface de.espirit.or.schema.EntityType.\r\n\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 1.8\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 25.172-b11\r\nJVM name : Java HotSpot(TM) 64-Bit Server VM\r\nJVM version : 1.8.0_172-b11\r\nJVM info : mixed mode\r\nOS name : Mac OS X\r\nOS version : 10.13.6\r\n\r\n\r\nYou are seeing this disclaimer because Mockito is configured to create inlined mocks.\r\nYou can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.\r\n\r\nUnderlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface de.espirit.or.schema.EntityType, interface java.io.Serializable]\r\n\r\n\tat de.espirit.firstspirit.access.editor.TestEntityAssociate.beforeEach(TestEntityAssociate.java:27)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)\r\n\tat com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)\r\nCaused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface de.espirit.or.schema.EntityType, interface java.io.Serializable]\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:344)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:353)\r\n\t... 23 more\r\nCaused by: java.lang.IllegalStateException: \r\nByte Buddy could not instrument all classes within the mock's type hierarchy\r\n\r\nThis problem should never occur for javac-compiled classes. This problem has been observed for classes that are:\r\n - Compiled by older versions of scalac\r\n - Classes that are part of the Android distribution\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:164)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.mockClass(InlineBytecodeGenerator.java:141)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:344)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:353)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMockType(InlineByteBuddyMockMaker.java:200)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMock(InlineByteBuddyMockMaker.java:181)\r\n\tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n\tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1895)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1804)\r\n\t... 23 more\r\nCaused by: java.lang.NoSuchFieldError: ASM_API\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator$ParameterWritingVisitorWrapper$ParameterAddingClassVisitor.<init>(InlineBytecodeGenerator.java:251)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator$ParameterWritingVisitorWrapper$ParameterAddingClassVisitor.<init>(InlineBytecodeGenerator.java:246)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator$ParameterWritingVisitorWrapper.wrap(InlineBytecodeGenerator.java:242)\r\n\tat net.bytebuddy.asm.AsmVisitorWrapper$Compound.wrap(AsmVisitorWrapper.java:645)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining$RedefinitionClassVisitor.visit(TypeWriter.java:3672)\r\n\tat net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:492)\r\n\tat net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:355)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining.create(TypeWriter.java:2915)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1634)\r\n\tat net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder.make(RedefinitionDynamicTypeBuilder.java:171)\r\n\tat net.bytebuddy.dynamic.scaffold.inline.AbstractInliningDynamicTypeBuilder.make(AbstractInliningDynamicTypeBuilder.java:92)\r\n\tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2669)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.transform(InlineBytecodeGenerator.java:215)\r\n\tat sun.instrument.TransformerManager.transform(TransformerManager.java:188)\r\n\tat sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:428)\r\n\tat sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)\r\n\tat sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)\r\n\tat org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:161)\r\n\t... 37 more",
"We are experiencing the same error with Java 11 and inline mocks.",
"Having similar issue with mockito and Java 11. Unable to mock any class/interface, do we need implement any method for class loading,since defineclass method removed in Java11 ? I even edited my java.policy for assertion exception.\r\nhttps://dzone.com/articles/jdk-11-and-proxies-in-a-world-past-sunmiscunsafe\r\nhttp://hg.openjdk.java.net/jdk9/hs/jdk/rev/0d2ab72ba600\r\nmockito -2.21.0,\r\nbytebuddy-1.8.15\r\n\r\nBelow is the exception:\r\norg.mockito.exceptions.base.MockitoException: \r\n\r\nMockito cannot mock this class: class com.xxx.xxx.toolkit.config.Configuration.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 11\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 11-ea+26\r\nJVM name : Java HotSpot(TM) 64-Bit Server VM\r\nJVM version : 11-ea+26\r\nJVM info : mixed mode\r\nOS name : Mac OS X\r\nOS version : 10.13.4\r\n\r\n\r\nUnderlying exception : java.lang.IllegalStateException: Error invoking java.lang.invoke.MethodHandles$Lookup#defineClass\r\nCaused by: java.lang.IllegalStateException: Error invoking java.lang.invoke.MethodHandles$Lookup#defineClass\r\nCaused by: java.security.AccessControlException: access denied (\"java.lang.RuntimePermission\" \"defineClass\")\r\n",
"Same problem here...",
"Seeing a related error:\r\n```\r\norg.mockito.exceptions.base.MockitoException: \r\nMockito cannot mock this class: interface cloud.cosmin.checklister.repo.ListRepo.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 11\r\nJVM vendor name : AdoptOpenJDK\r\nJVM vendor version : 11.0.1+13\r\nJVM name : OpenJDK 64-Bit Server VM\r\nJVM version : 11.0.1+13\r\nJVM info : mixed mode\r\nOS name : Linux\r\nOS version : 4.15.0-39-generic\r\n\r\n\r\nUnderlying exception : java.lang.UnsupportedOperationException: Cannot define class using reflection\r\n\tat cloud.cosmin.checklister.rest.ListControllerTest.setUp(ListControllerTest.java:37)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\n\tat org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:106)\r\n\tat org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)\r\n\tat org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)\r\n\tat org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:66)\r\n\tat org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)\r\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\r\n\tat org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)\r\n\tat org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)\r\n\tat com.sun.proxy.$Proxy2.processTestClass(Unknown Source)\r\n\tat org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:117)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)\r\n\tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\r\n\tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:155)\r\n\tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:137)\r\n\tat org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)\r\n\tat org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)\r\n\tat org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n\tat org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)\r\n\tat java.base/java.lang.Thread.run(Thread.java:834)\r\nCaused by: java.lang.UnsupportedOperationException: Cannot define class using reflection\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Unavailable.defineClass(ClassInjector.java:821)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:185)\r\n\tat net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:187)\r\n\tat net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)\r\n\tat net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4457)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:121)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n\tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n\tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n\tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1855)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:36)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)\r\n\tat org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)\r\n\tat org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)\r\n\tat org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)\r\n\tat org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)\r\n\tat org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)\r\n\t... 48 more\r\nCaused by: java.lang.IllegalStateException: Could not find sun.misc.Unsafe\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$Disabled.initialize(ClassInjector.java:1366)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.inject(ClassInjector.java:1202)\r\n\tat net.bytebuddy.dynamic.loading.ClassLoadingStrategy$ForUnsafeInjection.load(ClassLoadingStrategy.java:458)\r\n\tat net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)\r\n\tat net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4457)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Indirect.make(ClassInjector.java:684)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$CreationAction.run(ClassInjector.java:302)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$CreationAction.run(ClassInjector.java:290)\r\n\tat java.base/java.security.AccessController.doPrivileged(Native Method)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.<clinit>(ClassInjector.java:70)\r\n\tat net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:184)\r\n\t... 71 more\r\nCaused by: java.lang.NoSuchMethodException: sun.misc.Unsafe.defineClass(java.lang.String, [B, int, int, java.lang.ClassLoader, java.security.ProtectionDomain)\r\n\tat java.base/java.lang.Class.getMethod(Class.java:2109)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$CreationAction.run(ClassInjector.java:1269)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$CreationAction.run(ClassInjector.java:1257)\r\n\tat java.base/java.security.AccessController.doPrivileged(Native Method)\r\n\tat net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.<clinit>(ClassInjector.java:1136)\r\n\t... 80 more\r\n```",
"@cstroe Are you sure that you don't have some older byte-buddy version on the classpath?\r\n\r\n(of course I assume that use you the latest version of Mockito and Byte Buddy provided by it).",
"@szpak Your intuition is correct. I am using Spring Boot version `2.0.5.RELEASE`, and it is using an older version of the Mockito library. In order to use the newest Mockito, I had to change my Gradle config:\r\n```\r\n testCompile('org.springframework.boot:spring-boot-starter-test') {\r\n exclude group: \"org.mockito\", module: \"mockito-core\"\r\n }\r\n testCompile(\"org.mockito:mockito-core:2.23.4\")\r\n```\r\n\r\nThat fixed my errors. Thank you for the help.",
"Great to hear.\r\n\r\nBtw, Spring Boot provides also an easier way to override dependency [versions](https://docs.spring.io/platform/docs/Cairo-BUILD-SNAPSHOT/reference/html/getting-started-overriding-versions.html). Here, overriding Mockito would be enough.\r\n\r\nBtw, AFAIR only Spring Boot 2.1 declared Java 11 compatibility. Therefore, you may want to upgrade to prevent further surprises :).",
"> testCompile('org.springframework.boot:spring-boot-starter-test') {\r\n> exclude group: \"org.mockito\", module: \"mockito-core\"\r\n> }\r\n> testCompile(\"org.mockito:mockito-core:2.23.4\")\r\n\r\nthis works like a charm, Thank You!",
"> \r\n> \r\n> > testCompile('org.springframework.boot:spring-boot-starter-test') {\r\n> > exclude group: \"org.mockito\", module: \"mockito-core\"\r\n> > }\r\n> > testCompile(\"org.mockito:mockito-core:2.23.4\")\r\n> \r\n> this works like a charm, Thank You!\r\n\r\nAnyone has an idea how to do this in pom.xml?",
"@JiDarwish It's basic maven dependency management ;)\r\n\r\n```xml\r\n<dependency>\r\n <groupId>org.springframework.boot</groupId>\r\n <artifactId>spring-boot-starter-test</artifactId>\r\n <scope>test</test>\r\n <exclusions>\r\n <exclusion>\r\n <groupId>org.mockito</groupId>\r\n <artifactId>mockito-core</artifactId>\r\n </exclusion>\r\n </exclustions>\r\n</dependency>\r\n<dependency>\r\n <groupId>org.mockito</groupId>\r\n <artifactId>mockito-core</artifactId>\r\n <version>2.23.4</version>\r\n <scope>test</scope>\r\n</dependency>\r\n```",
"@bric3 I did exactly the same, still didn't help :-(\r\n\r\n> Java : 11\r\n> JVM vendor name : Oracle Corporation\r\n> JVM vendor version : 11.0.2+9\r\n> JVM name : OpenJDK 64-Bit Server VM\r\n> JVM version : 11.0.2+9\r\n> JVM info : mixed mode\r\n> OS name : Mac OS X\r\n> OS version : 10.14.4",
"Ok, adding bytebuddy dep. on top of that helped!",
"> @JiDarwish It's basic maven dependency management ;)\r\n> \r\n> ```\r\n> <dependency>\r\n> <groupId>org.springframework.boot</groupId>\r\n> <artifactId>spring-boot-starter-test</artifactId>\r\n> <scope>test</test>\r\n> <exclusions>\r\n> <exclusion>\r\n> <groupId>org.mockito</groupId>\r\n> <artifactId>mockito-core</artifactId>\r\n> </exclusion>\r\n> </exclustions>\r\n> </dependency>\r\n> <dependency>\r\n> <groupId>org.mockito</groupId>\r\n> <artifactId>mockito-core</artifactId>\r\n> <version>2.23.4</version>\r\n> <scope>test</scope>\r\n> </dependency>\r\n> ```\r\n\r\nIf your project extend `spring-boot-starter-parent` you might just add : \r\n```\r\n\t<properties>\r\n\t\t<mockito.version>2.23.4</mockito.version>\r\n\t</properties>\r\n```\r\n\r\nIn your Maven file. "
] | [] | "2018-07-10T12:04:36Z" | [
"java-11"
] | Provide Java 11 compatibility | I ran tests with JAva 11 and getting the follwing exception. may be asm 6.2 fixes this?
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface de.espirit.firstspirit.access.Language.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 11
JVM vendor name : "Oracle Corporation"
JVM vendor version : 11-ea+18
JVM name : Java HotSpot(TM) 64-Bit Server VM
JVM version : 11-ea+18
JVM info : mixed mode
OS name : Linux
OS version : 4.9.0-6-amd64
You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.
Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface java.lang.Comparable, interface de.espirit.firstspirit.access.Language]
at de.espirit.firstspirit.generate.TestPluggableUrlCreator.setUp(TestPluggableUrlCreator.java:51)
at jdk.internal.reflect.GeneratedMethodAccessor15.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Caused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [interface java.lang.Comparable, interface de.espirit.firstspirit.access.Language]
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:344)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:353)
Caused by: java.lang.IllegalStateException:
Byte Buddy could not instrument all classes within the mock's type hierarchy
This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:
- Compiled by older versions of scalac
- Classes that are part of the Android distribution
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:120)
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.mockClass(InlineBytecodeGenerator.java:97)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:344)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:353)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMockType(InlineByteBuddyMockMaker.java:200)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMock(InlineByteBuddyMockMaker.java:181)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
at org.mockito.Mockito.mock(Mockito.java:1855)
at org.mockito.Mockito.mock(Mockito.java:1787)
Caused by: java.lang.IllegalArgumentException: Unsupported class file major version 55
at net.bytebuddy.jar.asm.ClassReader.<init>(ClassReader.java:166)
at net.bytebuddy.jar.asm.ClassReader.<init>(ClassReader.java:148)
at net.bytebuddy.jar.asm.ClassReader.<init>(ClassReader.java:136)
at net.bytebuddy.utility.OpenedClassReader.of(OpenedClassReader.java:54)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining.create(TypeWriter.java:2912)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1634)
at net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder.make(RedefinitionDynamicTypeBuilder.java:171)
at net.bytebuddy.dynamic.scaffold.inline.AbstractInliningDynamicTypeBuilder.make(AbstractInliningDynamicTypeBuilder.java:92)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2669)
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.transform(InlineBytecodeGenerator.java:181)
at java.instrument/java.lang.instrument.ClassFileTransformer.transform(ClassFileTransformer.java:246)
at java.instrument/sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at java.instrument/sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:563)
at java.instrument/sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at java.instrument/sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:167)
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:117)
| [
"gradle/dependencies.gradle",
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java"
] | [
"gradle/dependencies.gradle",
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java"
] | [] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index c1af6f9ed6..7f64f84d2c 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -4,7 +4,7 @@ ext {
def versions = [:]
-versions.bytebuddy = '1.8.10'
+versions.bytebuddy = '1.8.13'
versions.junitJupiter = '5.1.0'
libraries.junit4 = 'junit:junit:4.12'
@@ -23,7 +23,7 @@ libraries.errorprone = 'com.google.errorprone:error_prone_core:2.3.1'
libraries.objenesis = 'org.objenesis:objenesis:2.6'
-libraries.asm = 'org.ow2.asm:asm:6.1.1'
+libraries.asm = 'org.ow2.asm:asm:6.2'
def kotlinVersion = '1.2.10'
libraries.kotlin = [
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 71ae6a6d4f..64139c20eb 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
@@ -23,6 +23,7 @@
import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.pool.TypePool;
+import net.bytebuddy.utility.OpenedClassReader;
import net.bytebuddy.utility.RandomString;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.concurrent.WeakConcurrentMap;
@@ -247,7 +248,7 @@ private static class ParameterAddingClassVisitor extends ClassVisitor {
private final TypeDescription typeDescription;
private ParameterAddingClassVisitor(ClassVisitor cv, TypeDescription typeDescription) {
- super(Opcodes.ASM6, cv);
+ super(OpenedClassReader.ASM_API, cv);
this.typeDescription = typeDescription;
}
| null | val | train | 2018-06-15T14:56:43 | "2018-07-02T11:12:56Z" | andrepdo | train |
mockito/mockito/1431_1433 | mockito/mockito | mockito/mockito/1431 | mockito/mockito/1433 | [
"keyword_issue_to_pr"
] | 198bdc373b803aa85bf90ac150c2723802fbb678 | 68f5a0782009708d649505b7e2dad5d30445846c | [
"Interesting. Thanks for the bug report.\r\n\r\nI noticed a change in serialization in the release notes (http://www.oracle.com/technetwork/java/javase/8u181-relnotes-4479407.html) yesterday.\r\n\r\n> core-libs/java.io:serialization\r\n> ➜ Better stack walking\r\n> New access checks have been added during the object creation phase of deserialization. This should not affect ordinary uses of deserialization. However, reflective frameworks that make use of JDK-internal APIs may be impacted. The new checks can be disabled if necessary by setting the system property jdk.disableSerialConstructorChecks to the value \"true\". This must be done by adding the argument -Djdk.disableSerialConstructorChecks=true to the Java command line.\r\n>\r\n> JDK-8197925 (not public)\r\n\r\nI'll verify that asap.\r\n\r\n\r\n-- Brice\r\nMisplet on my phone\r\n\r\n\r\n",
"I'm looking into it right now. Thank you for reporting!\r\n\r\nOur JDK10 build has been exposed: https://travis-ci.org/mockito/mockito/jobs/405198762",
"I confirm that disabling the constructor checks works. Running the tests with the following properties make them pass. \r\n\r\n```diff\r\ndiff --git i/build.gradle w/build.gradle\r\nindex b47d86bbf..da61d692e 100644\r\n--- i/build.gradle\r\n+++ w/build.gradle\r\n@@ -91,6 +91,10 @@ task wrapper(type: Wrapper) {\r\n gradleVersion = '4.7'\r\n }\r\n\r\n+test {\r\n+ systemProperty \"jdk.disableSerialConstructorChecks\", \"true\"\r\n+}\r\n+\r\n //Posting Build scans to https://scans.gradle.com\r\n buildScan {\r\n licenseAgreementUrl = 'https://gradle.com/terms-of-service'\r\n```\r\n\r\nIt seems that remove the `Any` constructor did the trick. \r\n\r\n```diff\r\ndiff --git i/src/main/java/org/mockito/internal/matchers/Any.java w/src/main/java/org/mockito/internal/matchers/Any.java\r\nindex f9f0069bd..ad4cca35a 100644\r\n--- i/src/main/java/org/mockito/internal/matchers/Any.java\r\n+++ w/src/main/java/org/mockito/internal/matchers/Any.java\r\n@@ -13,8 +13,8 @@ public class Any implements ArgumentMatcher<Object>, VarargMatcher ,Serializable\r\n\r\n public static final Any ANY = new Any();\r\n\r\n- private Any() {\r\n- }\r\n+ // private Any() {\r\n+ // }\r\n\r\n public boolean matches(Object actual) {\r\n return true;\r\n```\r\n\r\nHowever I suspect that user tests relying on mocks of an object with private no-arg constructor that is serialized using `ObjectInputStream` maybe have to declare this system property. Although it seems like an edgy case.",
"Created PR to fix this problem: #1433",
"Fixed on master :tada:",
"@mockitoguy can you make a patch release to maven central for this?",
"@TimvdLippe the fix in #1433 only affects mockito's build\r\n\r\nMockito users will see the same errors in their build if they are in the same conditions.",
"@mockitoguy \r\nif you take a look at other classes in matchers directory, eg. Contains.java.\r\nthey have similar problem. there's no accessible non-arg constructor\r\n\r\nmockito UT doesn't try to serialize them. \r\n"
] | [] | "2018-07-18T13:34:04Z" | [
"bug",
"java-8",
"java-10",
"build"
] | Mockito not able to be built with OracleJDK8u181-b13 | Oracle has released [JDK8u181-b13](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) today. I tried to build Mockito with JDK8u181 but some of the Mockito unit tests failed at the build.
```
org.mockitousage.basicapi.MocksSerializationForAnnotationTest > should_serialize_object_mock FAILED
java.io.InvalidClassException: org.mockito.internal.matchers.Any$MockitoMock$1346699744; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:169)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:874)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2043)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:27)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:23)
at org.mockitousage.basicapi.MocksSerializationForAnnotationTest.should_serialize_object_mock(MocksSerializationForAnnotationTest.java:277)
org.mockitousage.basicapi.MocksSerializationForAnnotationTest > should_serialize_real_partial_mock FAILED
java.io.InvalidClassException: org.mockito.internal.matchers.Any$MockitoMock$122170722; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:169)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:874)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2043)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:27)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:23)
at org.mockitousage.basicapi.MocksSerializationForAnnotationTest.should_serialize_real_partial_mock(MocksSerializationForAnnotationTest.java:289)
org.mockitousage.basicapi.MocksSerializationForAnnotationTest > should_serialization_work FAILED
java.io.InvalidClassException: org.mockito.internal.matchers.Any$MockitoMock$1346699744; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:169)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:874)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2043)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:27)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:23)
at org.mockitoutil.SimpleSerializationUtil.serializeAndBack(SimpleSerializationUtil.java:17)
at org.mockitousage.basicapi.MocksSerializationForAnnotationTest.should_serialization_work(MocksSerializationForAnnotationTest.java:176)
org.mockitousage.basicapi.MocksSerializationTest > should_serialize_object_mock FAILED
java.io.InvalidClassException: org.mockito.internal.matchers.Any$MockitoMock$1346699744; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:169)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:874)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2043)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:27)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:23)
at org.mockitousage.basicapi.MocksSerializationTest.should_serialize_object_mock(MocksSerializationTest.java:302)
org.mockitousage.basicapi.MocksSerializationTest > should_serialize_real_partial_mock FAILED
java.io.InvalidClassException: org.mockito.internal.matchers.Any$MockitoMock$122170722; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:169)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:874)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2043)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:27)
at org.mockitoutil.SimpleSerializationUtil.deserializeMock(SimpleSerializationUtil.java:23)
at org.mockitousage.basicapi.MocksSerializationTest.should_serialize_real_partial_mock(MocksSerializationTest.java:315)
1888 tests completed, 5 failed, 47 skipped
```
I roughly looked at the cause of the failure and found that `org.mockito.internal.matchers.Any` class has a private constructor. In [Oracle doc for Serializable interface](https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html), it states:
> During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
This could be the cause of the issue when `Any.class` is mocked by `deserializeMock`.
Java version:
```
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
```
The problem is reproducible by setting OracleJDK8u181 as JAVA_HOME and run `./gradlew build` in Mockito root.
| [
"src/main/java/org/mockito/internal/matchers/Any.java"
] | [
"src/main/java/org/mockito/internal/matchers/Any.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/matchers/Any.java b/src/main/java/org/mockito/internal/matchers/Any.java
index f9f0069bd9..58b6404355 100644
--- a/src/main/java/org/mockito/internal/matchers/Any.java
+++ b/src/main/java/org/mockito/internal/matchers/Any.java
@@ -9,13 +9,10 @@
import org.mockito.ArgumentMatcher;
-public class Any implements ArgumentMatcher<Object>, VarargMatcher ,Serializable {
+public class Any implements ArgumentMatcher<Object>, VarargMatcher, Serializable {
public static final Any ANY = new Any();
- private Any() {
- }
-
public boolean matches(Object actual) {
return true;
}
| null | test | train | 2018-07-16T09:06:13 | "2018-07-18T01:44:11Z" | ghost | train |
mockito/mockito/1438_1439 | mockito/mockito | mockito/mockito/1438 | mockito/mockito/1439 | [
"timestamp(timedelta=40740.0, similarity=0.8866171351360362)"
] | 2613e0ba972c54dab34d1e2e36d37ec95dad366f | 6b6e1a74c530d1708c4a981b0b2ff4bedec0edc8 | [
"Thank you for contribution!"
] | [] | "2018-07-21T16:47:04Z" | [
"docs"
] | ignoreStubs documentation should be updated for strictness | Driven by #1436, we need to update 'ignoreStubs' docs to include information about Mockito strictness (effectively replaces the need for 'ignoreStubs'). | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 44d6b3e0dd..4471b83b92 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -2535,7 +2535,10 @@ public static InOrder inOrder(Object... mocks) {
/**
* Ignores stubbed methods of given mocks for the sake of verification.
- * Sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
+ * Please consider using {@link Strictness#STRICT_STUBS} feature which eliminates the need for <code>ignoreStubs()</code>
+ * and provides other benefits.
+ * <p>
+ * <code>ignoreStubs()</code> is sometimes useful when coupled with <code>verifyNoMoreInteractions()</code> or verification <code>inOrder()</code>.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* <p>
* <b>Warning</b>, <code>ignoreStubs()</code> might lead to overuse of <code>verifyNoMoreInteractions(ignoreStubs(...));</code>
@@ -2591,6 +2594,20 @@ public static InOrder inOrder(Object... mocks) {
* inOrder.verify(list).clear();
* inOrder.verifyNoMoreInteractions();
* </code></pre>
+ * Stubbed invocations are automatically verified with {@link Strictness#STRICT_STUBS} feature
+ * and it eliminates the need for <code>ignoreStubs()</code>. Example below uses JUnit Rules:
+ * <pre class="code"><code class="java">
+ * @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
+ *
+ * List list = mock(List.class);
+ * when(list.get(0)).thenReturn("foo");
+ *
+ * list.size();
+ * verify(list).size();
+ *
+ * list.get(0); // Automatically verified by STRICT_STUBS
+ * verifyNoMoreInteractions(list); // No need of ignoreStubs()
+ * </code></pre>
*
* @since 1.9.0
* @param mocks input mocks that will be changed
| null | val | train | 2018-07-21T14:50:26 | "2018-07-21T12:43:51Z" | mockitoguy | train |
mockito/mockito/1444_1446 | mockito/mockito | mockito/mockito/1444 | mockito/mockito/1446 | [
"keyword_pr_to_issue",
"timestamp(timedelta=162048.0, similarity=0.8437745467741583)"
] | 101c588e06f44a81a6bd600234cb4907ff2ada20 | 56019897f07e370087224533f42ee7b89acadb18 | [
"It's a bug. Thank you for reporting!",
"@epeee, can you take a look at this?",
"Upstream bug in Shipkit: https://github.com/mockito/shipkit/issues/741",
"@mockitoguy sorry, I was busy yesterday. \r\nI can have a look at the upstream bug in shipkit tomorrow.",
"Not sure if it is related but the `2.20.1` is available in JCenter but not in Maven Central.",
"There is some delay. Bintray log shows that the sync was successful. Let's wait until the end of the day.\r\n\r\nThanks for checking!",
"OSS repo has the right artifacts so I think it's just a delay before it's searchable in central. Proof - [pom.xml](https://oss.sonatype.org/service/local/artifact/maven/redirect?r=releases&g=org.mockito&a=mockito-inline&v=2.20.1&e=pom) in the Sonatype OSS 'release' repo.\r\n\r\nLet's keep the ticket open until we add tests for the artifacts. @ming13, do you want to contribute a test that would verify artifact IDs? This should be a form of a Gradle task.",
"The issue is fixed in 2.20.1. I've added tests to prevent the issue in the future.\r\n\r\nThanks again for reporting!!!"
] | [] | "2018-07-26T03:39:08Z" | [] | Artifact ID changes | Since `2.20.0` Mockito Maven artifact IDs [have changed](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.mockito%22).
* `mockito-android` → `android`
* `mockito-inline` → `inline`
* `mockito-junit-jupiter` → `junit-jupiter`
Not sure if it is an intended change or not, so decided to clarify things a bit. So... Is it an intended change? It isn’t mentioned in the changelog. | [
"build.gradle",
"doc/release-notes/official.md",
"gradle/java-library.gradle"
] | [
"build.gradle",
"doc/release-notes/official.md",
"gradle/java-library.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index 9045d4c59e..b6f4a2ddc7 100644
--- a/build.gradle
+++ b/build.gradle
@@ -98,3 +98,14 @@ buildScan {
licenseAgreementUrl = 'https://gradle.com/terms-of-service'
licenseAgree = 'yes'
}
+
+//workaround for #1444, delete when Shipkit bug is fixed
+subprojects {
+ afterEvaluate {
+ def lib = publishing.publications.javaLibrary
+ if(lib && !lib.artifactId.startsWith("mockito-")) {
+ lib.artifactId = "mockito-" + lib.artifactId
+ }
+ }
+}
+//end workaround
diff --git a/doc/release-notes/official.md b/doc/release-notes/official.md
index f2464ac967..9788c97055 100644
--- a/doc/release-notes/official.md
+++ b/doc/release-notes/official.md
@@ -1,6 +1,9 @@
<sup><sup>*Release notes were automatically generated by [Shipkit](http://shipkit.org/)*</sup></sup>
#### 2.20.0
+
+__Deprecated__ because auxiliary artifacts were published with wrong identifiers ([#1444](https://github.com/mockito/mockito/issues/1444))
+
- 2018-07-24 - [55 commits](https://github.com/mockito/mockito/compare/v2.19.6...v2.20.0) by [Szczepan Faber](https://github.com/mockitoguy) (52), epeee (3) - published to [![Bintray](https://img.shields.io/badge/Bintray-2.20.0-green.svg)](https://bintray.com/mockito/maven/mockito/2.20.0)
- Update gradle (v4.9) and shipkit (v2.0.28) [(#1435)](https://github.com/mockito/mockito/pull/1435)
- Strictness configurable per mock / stubbing [(#1272)](https://github.com/mockito/mockito/pull/1272)
diff --git a/gradle/java-library.gradle b/gradle/java-library.gradle
index 45c72f11d2..ecf217ca9a 100644
--- a/gradle/java-library.gradle
+++ b/gradle/java-library.gradle
@@ -1,7 +1,11 @@
apply plugin: "java"
group = 'org.mockito'
-archivesBaseName = "mockito-" + project.name
+
+if (!archivesBaseName.startsWith("mockito-")) {
+ archivesBaseName = "mockito-" + project.name
+}
+
bintrayUpload.enabled = true
sourceCompatibility = 1.6
| null | train | train | 2018-07-24T06:36:25 | "2018-07-25T08:09:20Z" | arturdryomov | train |
mockito/mockito/1510_1525 | mockito/mockito | mockito/mockito/1510 | mockito/mockito/1525 | [
"keyword_issue_to_pr"
] | 57d877de14e72c301d78d9163d9c5c5442754b4b | a2fc469fd9063e0e9a98adb1f3e35c29561dfff2 | [
"This is probably broken by https://github.com/mockito/mockito/commit/28fa11092b55595727eb3c40059a5f632f3f29cc Could you revert the Bytebuddy version and see if that fixes it?",
"Sure thing, @TimvdLippe - I'm not 100% sure on the best way to go about that, though. Any pointers on how to most easily pull down and point to the correct artifacts? I've got it cloned, but am not sure which gradle projects represent the `core` and `android` artifacts.\r\n\r\n(I'm assuming that `subprojects/android` is likely `mockito-android - but just trying to include the root project in my app gives a gradle error, making me suspect I'm doing this wrong)",
"You should be able to pin the version of ByteBuddy to a specific version in your `pom.xml` or Gradle file. No need to clone this repository :smile: ",
"So this is fixed as of #1525 ?",
"> So this is fixed as of #1525 ? \r\n\r\nDoesn't look so. `mockito-android 2.23.0` and `bytebuddy 1.9.3` fails with exception. same mockito and `bytebuddy 1.8.10` works for me ",
"Use 2.23.4",
"> Use 2.23.4\r\n\r\nHow should it fix the issue?\r\n\r\n```\r\n+--- org.mockito:mockito-android:2.23.4\r\n| +--- org.mockito:mockito-core:2.23.4\r\n| | +--- net.bytebuddy:byte-buddy:1.9.3\r\n| | +--- net.bytebuddy:byte-buddy-agent:1.9.3\r\n| | \\--- org.objenesis:objenesis:2.6\r\n| \\--- net.bytebuddy:byte-buddy-android:1.9.3\r\n| +--- net.bytebuddy:byte-buddy:1.9.3\r\n| \\--- com.jakewharton.android.repackaged:dalvik-dx:1\r\n| \\--- com.jakewharton.android.repackaged:libcore-dex:2\r\n```\r\nFails, but \r\n```\r\n+--- org.mockito:mockito-android:2.23.4\r\n| +--- org.mockito:mockito-core:2.23.4\r\n| | +--- net.bytebuddy:byte-buddy:1.9.3 -> 1.8.10\r\n| | +--- net.bytebuddy:byte-buddy-agent:1.9.3 -> 1.8.10\r\n| | \\--- org.objenesis:objenesis:2.6\r\n| \\--- net.bytebuddy:byte-buddy-android:1.9.3 -> 1.8.10\r\n| +--- net.bytebuddy:byte-buddy:1.8.10\r\n| \\--- com.jakewharton.android.repackaged:dalvik-dx:1\r\n| \\--- com.jakewharton.android.repackaged:libcore-dex:2\r\n```\r\nworks. What am I missing?",
"@plastiv \r\n\r\nCheck the answer from: https://stackoverflow.com/a/51891596/8034839 \r\n\r\nTry to use the version 2.18.3\r\n\r\n```\r\ntestImplementation 'org.mockito:mockito-core:2.18.3'\r\nandroidTestImplementation 'org.mockito:mockito-android:2.18.3'\r\n```\r\n",
"Hmm - it doesn't seem to be working for me, even with a forced ByteBuddy. Here's a code snippet from my build.gradle to force this:\r\n\r\n```\r\nconfigurations.all {\r\n resolutionStrategy {\r\n force 'net.bytebuddy:byte-buddy:1.8.10'\r\n force 'net.bytebuddy:byte-buddy-agent:1.8.10'\r\n }\r\n}\r\n```\r\n\r\nAnd you can see in my dependencies:\r\n```\r\n+--- org.mockito:mockito-android:2.23.4\r\n| +--- org.mockito:mockito-core:2.23.4\r\n| | +--- net.bytebuddy:byte-buddy:1.9.3 -> 1.8.10\r\n| | +--- net.bytebuddy:byte-buddy-agent:1.9.3 -> 1.8.10\r\n| | \\--- org.objenesis:objenesis:2.6\r\n| \\--- net.bytebuddy:byte-buddy-android:1.9.3\r\n| +--- net.bytebuddy:byte-buddy:1.9.3 -> 1.8.10\r\n| \\--- com.jakewharton.android.repackaged:dalvik-dx:1\r\n| \\--- com.jakewharton.android.repackaged:libcore-dex:2\r\n```\r\n\r\nAny further ideas what might be causing this?",
"@tmtrademarked Try also downgrading `net.bytebuddy:byte-buddy-android:1.8.10`",
"Well, I feel silly now. That should have been obvious. Thanks! That does in fact fix the problem.",
"It looks like this may be fixed in the newest byte-buddy versions. Unpinning my byte buddy and updating to Mockito 2.24.0 (which brings in byte-buddy 1.9.7) seems to fix the problem on my builds!",
"Glad to hear! Closing per above comment."
] | [
"Version 3.0.1 requires Java 8. If this is an issue, we need to keep using the older version.",
"I reverted this change."
] | "2018-10-30T06:42:01Z" | [
"android"
] | Newest Mockito Android fails on Android P | The latest releases of Mockito Android appear to break compatibility with Android P. Specifically in instrumentation tests, I encounter an error when attempting to mock an Android framework class. Here's the mocking code I'm using:
```
@Override
protected ConnectivityManager provideConnectivityManager_impl(Context context) {
NetworkInfo info = mock(NetworkInfo.class);
when(info.isConnectedOrConnecting()).thenReturn(true);
ConnectivityManager manager = provide(ConnectivityManager.class);
when(manager.getActiveNetworkInfo()).thenReturn(info);
return manager;
}
```
Here is the error I encounter:
```
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class android.net.NetworkInfo.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
IMPORTANT INFORMATION FOR ANDROID USERS:
The regular Byte Buddy mock makers cannot generate code on an Android VM!
To resolve this, please use the 'mockito-android' dependency for your application:
http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22
Java : 0.9
JVM vendor name : The Android Project
JVM vendor version : 2.1.0
JVM name : Dalvik
JVM version : 0.9
JVM info : null
OS name : Linux
OS version : 4.4.124+
Underlying exception : java.lang.IllegalArgumentException: On Android P, a class injection can only be applied to BaseDexClassLoader: net.bytebuddy.dynamic.loading.MultipleParentClassLoader@ecc1346
at com.blueapron.service.mock.InstrumentAppModule.provideConnectivityManager_impl(InstrumentAppModule.java:63)
at com.blueapron.service.dagger.ApplicationModule.provideConnectivityManager(ApplicationModule.java:149)
at com.blueapron.service.dagger.ApplicationModule_ProvideConnectivityManagerFactory.proxyProvideConnectivityManager(ApplicationModule_ProvideConnectivityManagerFactory.java:44)
at com.blueapron.service.dagger.ApplicationModule_ProvideConnectivityManagerFactory.provideInstance(ApplicationModule_ProvideConnectivityManagerFactory.java:33)
at com.blueapron.service.dagger.ApplicationModule_ProvideConnectivityManagerFactory.get(ApplicationModule_ProvideConnectivityManagerFactory.java:28)
at com.blueapron.service.dagger.ApplicationModule_ProvideConnectivityManagerFactory.get(ApplicationModule_ProvideConnectivityManagerFactory.java:10)
```
The class doesn't appear to be final or private, making the error message confusing.
I have verified that the same exact test passes with the 2.19.0 libraries, and fails with anything higher, starting at 2.20.1 and continuing through the 2.23.0 libraries. So it doesn't appear to be a configuration issue with my instrumentation tests. (I initially thought this was caused by incorrectly including mockito-core instead of mockito-android, but since I can produce the failure by *only* changing the mockito version, this feels unlikely)
Any ideas what has gone wrong here?
I do solemnly swear that:
- [ X ] The mockito message in the stacktrace have useful information, but it didn't help
- [ X ] The problematic code (if that's possible) is copied here;
Note that some configuration are impossible to mock via Mockito
- [ X ] Provide versions (mockito / jdk / os / any other relevant information)
- [ X ] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
(same as any question on stackoverflow.com)
- [ X ] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md)
| [
"gradle/dependencies.gradle"
] | [
"gradle/dependencies.gradle"
] | [] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index e5f96c5002..6b43944095 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -4,7 +4,7 @@ ext {
def versions = [:]
-versions.bytebuddy = '1.9.0'
+versions.bytebuddy = '1.9.3'
versions.junitJupiter = '5.1.1'
libraries.junit4 = 'junit:junit:4.12'
@@ -20,9 +20,10 @@ libraries.bytebuddyandroid = "net.bytebuddy:byte-buddy-android:${versions.bytebu
libraries.errorprone = 'com.google.errorprone:error_prone_core:2.3.1'
+// objenesis 3.x with full Java 11 support requires Java 8, bump version when Java 7 support is dropped
libraries.objenesis = 'org.objenesis:objenesis:2.6'
-libraries.asm = 'org.ow2.asm:asm:6.2'
+libraries.asm = 'org.ow2.asm:asm:7.0'
def kotlinVersion = '1.2.10'
def kotlinVersion_1_3 = '1.3.0-rc-57'
| null | train | train | 2018-10-19T16:09:01 | "2018-10-05T19:31:53Z" | tmtrademarked | train |
mockito/mockito/1541_1544 | mockito/mockito | mockito/mockito/1541 | mockito/mockito/1544 | [
"timestamp(timedelta=1.0, similarity=0.8680414470106933)"
] | 30d3127ee2c4e41452787a058a31b7a553ba3b00 | 8dd8d1ad916c37fdebfccbfe72d46534fd82f5fa | [
"Great investigation! Do you have a suggestion on how to resolve this?",
"Tried different approaches. I believe I found one solution that works well. Created a PR."
] | [] | "2018-11-24T17:50:01Z" | [] | Mock object premature garbage collected when using 'One-liner stubs' | ### Problem:
'One-liner stubs' may throw an exception because the actual mock object is already garbage collected when trying to return the mock.
### Reproduce:
1. Mockito 2.23.5 using mockito-inline
2. -Xmx256m
```
public class OneLinerStubStressTest {
public class TestClass {
public String getStuff() {
return "A";
}
}
private static String generateString() {
final int length = 10000;
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() {
final String returnValue = generateString();
for (int i = 0; i < 40000; i++) {
final TestClass mock = when(mock(TestClass.class).getStuff())
.thenReturn(returnValue).getMock();
assertEquals(returnValue, mock.getStuff());
}
}
}
```
#### Expected:
Test finishes successfully
#### Actual:
```
java.lang.IllegalStateException: The mock object was garbage collected. This should not happen in normal circumstances when using public API. Typically, the test class keeps strong reference to the mock object and it prevents getting the mock collected. Mockito internally needs to keep weak references to mock objects to avoid memory leaks for certain types of MockMaker implementations. If you see this exception using Mockito public API, please file a bug. For more information see issue #1313.
at org.mockito.internal.invocation.mockref.MockWeakReference.get(MockWeakReference.java:32)
at org.mockito.internal.invocation.InterceptedInvocation.getMock(InterceptedInvocation.java:103)
at org.mockito.internal.stubbing.InvocationContainerImpl.invokedMock(InvocationContainerImpl.java:157)
at org.mockito.internal.stubbing.ConsecutiveStubbing.getMock(ConsecutiveStubbing.java:28)
```
### Analysis:
As part of #1313 `DefaultInvocationFactory` and `InterceptedInvocation` were refactored to keep week reference to the mock. This was necessary in order to get rid of strong references by the handlers which caused memory leaks. On the other hand this requires to have a strong reference to the mock in the test class in order to prevent premature garbage collection. Unfortunately if using 'One-liner stubs' (https://static.javadoc.io/org.mockito/mockito-core/2.23.4/org/mockito/Mockito.html#one_liner_stub) the mock object may be premature cleaned up. This occurs because we gain access to the `InterceptedInvocation` when calling `getMock()` (which tries to get the mock from the invocation), without having any strong reference to the mock itself. At this point the mock may already be cleaned up. | [
"src/main/java/org/mockito/internal/stubbing/BaseStubbing.java",
"src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java",
"src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java",
"subprojects/inline/inline.gradle"
] | [
"src/main/java/org/mockito/internal/stubbing/BaseStubbing.java",
"src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java",
"src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java",
"subprojects/inline/inline.gradle"
] | [
"subprojects/inline/src/test/java/org/mockitoinline/OneLinerStubStressTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
index 6dd99cd802..4c86cbd05d 100644
--- a/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
+++ b/src/main/java/org/mockito/internal/stubbing/BaseStubbing.java
@@ -4,17 +4,31 @@
*/
package org.mockito.internal.stubbing;
-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.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;
+
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));
@@ -79,6 +93,12 @@ public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class
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 a5cdc04829..32ef8eedfd 100644
--- a/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java
+++ b/src/main/java/org/mockito/internal/stubbing/ConsecutiveStubbing.java
@@ -8,23 +8,17 @@
import org.mockito.stubbing.OngoingStubbing;
public class ConsecutiveStubbing<T> extends BaseStubbing<T> {
- private final InvocationContainerImpl invocationContainerImpl;
- public ConsecutiveStubbing(InvocationContainerImpl invocationContainerImpl) {
- this.invocationContainerImpl = invocationContainerImpl;
+ private final InvocationContainerImpl invocationContainer;
+
+ ConsecutiveStubbing(InvocationContainerImpl invocationContainer) {
+ super(invocationContainer.invokedMock());
+ this.invocationContainer = invocationContainer;
}
public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
- invocationContainerImpl.addConsecutiveAnswer(answer);
+ invocationContainer.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 cd27c392dd..419160421e 100644
--- a/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/OngoingStubbingImpl.java
@@ -19,6 +19,7 @@ public class OngoingStubbingImpl<T> extends BaseStubbing<T> {
private Strictness strictness;
public OngoingStubbingImpl(InvocationContainerImpl invocationContainer) {
+ super(invocationContainer.invokedMock());
this.invocationContainer = invocationContainer;
}
@@ -32,22 +33,11 @@ public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
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/subprojects/inline/inline.gradle b/subprojects/inline/inline.gradle
index b8d2577ab5..22db17b067 100644
--- a/subprojects/inline/inline.gradle
+++ b/subprojects/inline/inline.gradle
@@ -9,5 +9,6 @@ dependencies {
tasks.javadoc.enabled = false
-//required by the "StressTest.java"
+//required by the "StressTest.java" and "OneLinerStubStressTest.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
new file mode 100644
index 0000000000..44ff95959e
--- /dev/null
+++ b/subprojects/inline/src/test/java/org/mockitoinline/OneLinerStubStressTest.java
@@ -0,0 +1,41 @@
+/*
+ * 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());
+ }
+ }
+}
| train | train | 2018-11-21T00:13:43 | "2018-11-22T22:32:39Z" | maxgrabenhorst | train |
mockito/mockito/1545_1546 | mockito/mockito | mockito/mockito/1545 | mockito/mockito/1546 | [
"timestamp(timedelta=1.0, similarity=0.9250358639836104)"
] | ceb1d29743c1abf733c2014bb3aa0bc364cf9007 | 51a77d3228bd6dc83e3ae36bb168eb5098602809 | [] | [
"Great! We don't want local cache on CI.",
"Why do we need this setting or the next one? Can we rely on Gradle's defaults?",
"good question, let's rely on defaults for now and adjust them if needed later on."
] | "2018-11-26T21:02:18Z" | [
"please contribute",
"build"
] | Enable Gradle Build cache for faster local builds | Let's enable Gradle build cache for faster local builds.
https://docs.gradle.org/current/userguide/build_cache.html | [
".gitignore",
"gradle.properties",
"settings.gradle"
] | [
".gitignore",
"gradle.properties",
"settings.gradle"
] | [] | diff --git a/.gitignore b/.gitignore
index b91f27c74a..9d0c115582 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,7 @@ bin/
# Gradle & builds
build
+build-cache
target
out
.gradle
diff --git a/gradle.properties b/gradle.properties
index 41f55a5303..5970e287bb 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,2 +1,3 @@
org.gradle.daemon=true
org.gradle.parallel=true
+org.gradle.caching=true
diff --git a/settings.gradle b/settings.gradle
index 8dd114e648..15bc234122 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -18,3 +18,9 @@ rootProject.children.each { project ->
}
enableFeaturePreview('STABLE_PUBLISHING')
+
+buildCache {
+ local {
+ enabled = !System.getenv().containsKey("CI")
+ }
+}
| null | train | train | 2018-11-26T17:06:01 | "2018-11-26T17:06:16Z" | mockitoguy | train |
mockito/mockito/1514_1549 | mockito/mockito | mockito/mockito/1514 | mockito/mockito/1549 | [
"timestamp(timedelta=0.0, similarity=0.8578591718360361)",
"keyword_pr_to_issue"
] | 16271ee313350e47855dc4a225e1edcb048a9a91 | d49c667860fce0758a0da9290c7290d06db78f7e | [
"A fix (if this **is** an issue) might be simple:\r\n\r\n```\r\nIndex: src/main/java/org/mockito/internal/stubbing/StubberImpl.java\r\nIDEA additional info:\r\nSubsystem: com.intellij.openapi.diff.impl.patch.CharsetEP\r\n<+>UTF-8\r\n===================================================================\r\n--- src/main/java/org/mockito/internal/stubbing/StubberImpl.java\t(revision 11e28796ecd89470ca50632e0fe9b2e4260e323a)\r\n+++ src/main/java/org/mockito/internal/stubbing/StubberImpl.java\t(date 1532965613000)\r\n@@ -93,6 +93,9 @@\r\n } catch (RuntimeException instantiationError) {\r\n mockingProgress().reset();\r\n throw instantiationError;\r\n+ } catch (InstantiationError instantiationError) {\r\n+ mockingProgress().reset();\r\n+ throw instantiationError;\r\n }\r\n return doThrow(e);\r\n }\r\n```",
"@dmitry-timofeev, do you want to take a stab at it? Please provide top level test that demonstrates the problem, too. It would be really helpful. Thank you!",
"Hi @mockitoguy , thank you for having a look. I'm a little busy at work, therefore I won't be able to in the coming weeks.",
"That's fair, we will try find time to work on this. Thank you for reporting!"
] | [] | "2018-11-27T16:56:06Z" | [
"bug"
] | Mockito remains in unfinished stubbing state if a stubbing fails | If one of `doThrow` instructions failed due to InstantiationError, Mockito remains in "unfinished stubbing" state and can no longer mock anything.
I had this issue in a single JUnit 4 test, but the fact that Mockito remained in "unfinished stubbing" state used to result in _all_ tests being marked as failed (I couldn't reproduce the last effect with the latest Mockito neither in JUnit 4 nor with JUnit 5 now, so the issue is applicable to a single test invocation only).
```java
import java.util.List;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
import org.mockito.Mockito;
class UninstantiableTest {
@RepeatedTest(2)
void tryThrow01(RepetitionInfo i) {
if (i.getCurrentRepetition() == 1) {
// Stub using uninstantiable exception.
try {
List mock = Mockito.mock(List.class);
Mockito.doThrow(UninstantiableException.class).when(mock).clear();
} catch (InstantiationError expected) {
// Get a j.l.InstantiationError.
}
}
// Try to stub another mock, this time using a valid exception type.
{
List mock = Mockito.mock(List.class);
// The following operation results in "UnfinishedStubbing"
Mockito.doThrow(RuntimeException.class).when(mock).clear();
}
}
abstract static class UninstantiableException extends RuntimeException {}
}
```
Mockito version 2.23.0
check that
- [x] The mockito message in the stacktrace have useful information, but it didn't help
- [x] The problematic code (if that's possible) is copied here;
Note that some configuration are impossible to mock via Mockito
- [x] Provide versions (mockito / jdk / os / any other relevant information)
- [x] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
(same as any question on stackoverflow.com)
- [x] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md)
| [
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java"
] | [
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java"
] | [
"src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java",
"subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
index 2172809e36..42795a723b 100644
--- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
@@ -87,12 +87,16 @@ public Stubber doThrow(Class<? extends Throwable> toBeThrown) {
mockingProgress().reset();
throw notAnException();
}
- Throwable e;
+ Throwable e = null;
try {
e = newInstance(toBeThrown);
- } catch (RuntimeException instantiationError) {
- mockingProgress().reset();
- throw instantiationError;
+ } finally {
+ if (e == null) {
+ //this means that an exception or error was thrown when trying to create new instance
+ //we don't want 'catch' statement here because we want the exception to be thrown to the user
+ //however, we do want to clean up state (e.g. "stubbing started").
+ mockingProgress().reset();
+ }
}
return doThrow(e);
}
| diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java
new file mode 100644
index 0000000000..b0c29d5bee
--- /dev/null
+++ b/src/test/java/org/mockitousage/stubbing/StubbingWithBadThrowablesTest.java
@@ -0,0 +1,37 @@
+/*
+ * 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/subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java
new file mode 100644
index 0000000000..2ef3128016
--- /dev/null
+++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/UninstantiableThrowableTest.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitousage;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.RepeatedTest;
+import org.junit.jupiter.api.RepetitionInfo;
+import org.mockito.Mockito;
+
+import java.util.List;
+
+//issue 1514
+class UninstantiableThrowableTest {
+
+ @RepeatedTest(2)
+ void should_behave_consistently(RepetitionInfo i) {
+ List mock = Mockito.mock(List.class);
+ if (i.getCurrentRepetition() == 1) {
+ Assertions.assertThatThrownBy(
+ () -> Mockito.doThrow(UninstantiableException.class).when(mock).clear())
+ .isInstanceOf(InstantiationError.class);
+ }
+
+ // The following operation results in "UnfinishedStubbing"
+ Mockito.doThrow(RuntimeException.class).when(mock).clear();
+ }
+
+ abstract static class UninstantiableException extends RuntimeException { }
+}
| test | train | 2018-11-27T17:45:54 | "2018-10-09T18:09:07Z" | dmitry-timofeev | train |
mockito/mockito/1553_1554 | mockito/mockito | mockito/mockito/1553 | mockito/mockito/1554 | [
"timestamp(timedelta=9.0, similarity=0.9413523180519786)"
] | 613c94a69ed6e455700544419921d1c9977844ef | bf16d192f013629115e5c3b1a40bbc394ccd700e | [] | [] | "2018-11-28T23:07:03Z" | [
"build"
] | VerifyError thrown when JUnit 3 is in the classpath | With JUnit 3 in the classpath, VerifyError will be thrown during JUnit detection in ExceptionFactory. This is because JUnit's ComparisonFailure class only starts extending AssertionError in JUnit 4.
**Expected Behavior**
When JUnit 3 is in the classpath, Mockito should behave as if JUnit was not there at all.
A real example where handling this here instead of updating JUnit in the consumer would be beneficial is related to my company's usage of ZooKeeper. ZooKeeper 3.4 leaks a JUnit 3.8.1 dependency that is fixed in 3.5, but 3.5 is still in beta and has been in the works for several years. Projects that use TestNG (most of ours) but which use ZooKeeper (usually transitively) run into this issue.
**Example**
src/test/java/com/example/ExampleTest.java
```
package com.example;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
@Test
public class ExampleTest {
public void testMockitoWithJUnit3() {
Client mockClient = mock(Client.class);
mockClient.call("one");
verify(mockClient).call("two");
}
public interface Client {
void call(String argument);
}
}
```
build.gradle
```
plugins {
id 'java'
id 'idea'
}
repositories {
mavenCentral()
}
dependencies {
testImplementation group: 'junit', name: 'junit', version: '3.8.2'
testImplementation group: 'org.mockito', name: 'mockito-core', version: '2.23.4'
testImplementation group: 'org.testng', name: 'testng', version: '6.14.3'
}
test {
useTestNG()
}
```
**Error**
```
java.lang.VerifyError: Bad return type
Exception Details:
Location:
org/mockito/internal/junit/ExceptionFactory$JUnitArgsAreDifferent.create(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/AssertionError; @10: areturn
Reason:
Type 'org/mockito/exceptions/verification/junit/ArgumentsAreDifferent' (current frame, stack[0]) is not assignable to 'java/lang/AssertionError' (from method signature)
Current Frame:
bci: @10
flags: { }
locals: { 'java/lang/String', 'java/lang/String', 'java/lang/String' }
stack: { 'org/mockito/exceptions/verification/junit/ArgumentsAreDifferent' }
Bytecode:
0000000: bb00 0259 2a2b 2cb7 0003 b0
at org.mockito.internal.junit.ExceptionFactory.canLoadJunitClass(ExceptionFactory.java:33)
at org.mockito.internal.junit.ExceptionFactory.<clinit>(ExceptionFactory.java:12)
at org.mockito.internal.exceptions.Reporter.argumentsAreDifferent(Reporter.java:313)
...
``` | [
"src/main/java/org/mockito/internal/junit/ExceptionFactory.java"
] | [
"src/main/java/org/mockito/internal/junit/ExceptionFactory.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
index 3664aea1a8..ee288d614a 100644
--- a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
+++ b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
@@ -31,7 +31,7 @@ private static AssertionError createJUnitArgumentsAreDifferent(String message, S
private static boolean canLoadJunitClass() {
try {
JUnitArgsAreDifferent.create("message", "wanted", "actual");
- } catch (NoClassDefFoundError onlyIfJUnitIsNotAvailable) {
+ } catch (Throwable onlyIfJUnitIsNotAvailable) {
return false;
}
return true;
| null | train | train | 2018-11-28T17:19:50 | "2018-11-28T22:58:55Z" | tjni | train |
mockito/mockito/1068_1566 | mockito/mockito | mockito/mockito/1068 | mockito/mockito/1566 | [
"timestamp(timedelta=8.0, similarity=0.8412190641305102)"
] | 18990118a96da215a28feccf709d86025d04a06b | a6bb28dcb72cbd08ac9e6848e523f37f1d362dd7 | [
"Given that @brachi-wernick opened a PR for this and it appears that we never commented on this issue: I don't think we should allow this. You should use the real Function in all cases, as a spy of the function would just delegate to the actual function.\r\n\r\nTherefore I am inclined to close this issue and corresponding PR. @mockito/core any opinion on this one?",
"@TimvdLippe just let me know for next time. Should i solve issues only after you commented on them?",
"Yes please. Sorry for not getting to this issue sooner. We should have commented :cry: Your help is still appreciated though, so feel free to sent more PRs! Issues tagged with \"Please contribute\" are definitely open for community PRs: https://github.com/mockito/mockito/issues?q=is%3Aissue+is%3Aopen+label%3A%22please+contribute%22",
"Closing per https://github.com/mockito/mockito/issues/1068#issuecomment-446266057",
"@TimvdLippe sorry for commenting on a closed issue, but can you reconsider reopening it? We might have missed the point of spying on a lambda. I don't think the idea would be to stub the methods or something like that, but to verify their recorded information. For instance, this becomes extremely useful when we want to test callbacks, and we only care if the lambda was called, how many times, which arguments, etc.\r\n\r\nSimilar libraries in other languages have this feature since verifying is the most useful part of a `spy()`. A good example is [Sinon.JS](https://sinonjs.org), in which we even find an example of this usage in the documentation: https://sinonjs.org/releases/v13/spies/\r\n\r\nI found myself in this same situation while improving some tests on a library of my authoring called [Maybe](https://github.com/JoseLion/maybe). Here's the gist of the use case 🙂 \r\n```java\r\n@Test void runs_the_effect_callback() {\r\n final Consumer<IOException> effectSpy = spy(error -> { });\r\n\r\n Maybe.fromSupplier(throwingOp).doOnError(IOException.class, effectSpy);\r\n\r\n verify(effectSpy, times(1)).accept(FAIL_EXCEPTION);\r\n}\r\n```\r\n\r\nAs you can see, the test only cares to verify if the `effect` callback was invoked once with the specific argument. I think there's no other way of doing this with Mockito, and since spying to the lambda will fail, I'm using @danwallach's workaround for now. \r\n\r\nI hope you find this helpful in improving Mockito 🙂 \r\n\r\nCheers!"
] | [] | "2018-12-11T16:16:03Z" | [] | feature request: spying on lambdas | Here's some Java8 code that works today (even with Mockito 1.x):
```
Function<Integer, Integer> incrementer = x -> x + 1;
Function<Integer, Integer> spyIncrementer =
mock(Function.class, AdditionalAnswers.delegatesTo(incrementer));
```
I then use `spyIncrementer` as an argument to the code that I really want to test and write a series of `verify` calls to check how `spyIncrementer` was used. In particular, I'm testing a memoization system that should only ever call call this lambda once with any given argument, so there are a series of Mockito calls along the lines of `verify(spyIncrementer, atMost(1)).apply(1);`
It would be preferable to be able to write something more like:
```
Function<Integer, Integer> spyIncrementer = spy(x -> x + 1);
```
With `org.mockito:mockito-inline:2.7.22`, this yields a `NoClassDefFoundError`. If you instead use `org.mockito:mockito-core:2.7.22`, you get _Mockito cannot mock/spy because : - final class_. | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/test/java/org/mockito/MockitoTest.java"
] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index e2a0ade374..24ee6da878 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -1805,6 +1805,34 @@ public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings());
}
+ /**
+ *
+ * @param function a lambda expression
+ * @param <T> the lambda argument type
+ * @param <R> the lambda result type
+ * @return mock object for that lambda
+ * The following test will succeed
+ * </code></pre>
+ * @Test
+ * public void mockLambda(){
+ * Function<Integer,Integer> mock = Mockito.mock(x -> x + 1);
+ * assertEquals(2,foo(mock,1).intValue());
+ * }
+ *
+ * public Integer foo(Function<Integer, Integer> func, Integer arg) {
+ * return func.apply(arg);
+ * }
+ * </code></pre>
+ */
+ public static <T, R> java.util.function.Function<T,R> mock(java.util.function.Function<T,R> function){
+ java.util.function.Function<T,R> mock = Mockito.mock(java.util.function.Function.class);
+ when(mock.apply(any())).thenAnswer(invocation -> {
+ T arg = invocation.getArgument(0);
+ return function.apply(arg);
+ });
+ return mock;
+ }
+
/**
* Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
* <p>
| diff --git a/src/test/java/org/mockito/MockitoTest.java b/src/test/java/org/mockito/MockitoTest.java
index ca8c4d4342..7253ba1c43 100644
--- a/src/test/java/org/mockito/MockitoTest.java
+++ b/src/test/java/org/mockito/MockitoTest.java
@@ -6,10 +6,13 @@
package org.mockito;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
import java.util.List;
+import java.util.function.Function;
+
import org.junit.Test;
import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.internal.creation.MockSettingsImpl;
@@ -62,4 +65,13 @@ public void shouldStartingMockSettingsContainDefaultBehavior() {
assertThat(Mockito.RETURNS_DEFAULTS).isEqualTo(settings.getDefaultAnswer());
}
+ @Test
+ public void mockLambda(){
+ Function<Integer,Integer> mock = Mockito.mock(x -> x + 1);
+ assertEquals(2,foo(mock,1).intValue());
+ }
+
+ public Integer foo(Function<Integer, Integer> func, Integer arg) {
+ return func.apply(arg);
+ }
}
| val | train | 2018-12-04T22:23:48 | "2017-05-04T13:31:59Z" | danwallach | train |
mockito/mockito/1472_1583 | mockito/mockito | mockito/mockito/1472 | mockito/mockito/1583 | [
"keyword_issue_to_pr"
] | eb54a7e72ce7c39c1ac3ccc3193f13d518946fe0 | 9838a7c0f27340f3fdb9f24a17c282a09d0fa369 | [
"I suppose it's worth noting that in the (hopefully) very short term, adding this class in the appropriate package is a simple workaround if you don't want to generalize setting the suggested property:\r\n\r\n```java\r\npackage android.support.test;\r\n\r\nimport android.content.Context;\r\n\r\npublic class InstrumentationRegistry {\r\n public static Context getTargetContext() {\r\n return androidx.test.InstrumentationRegistry.getTargetContext();\r\n }\r\n}\r\n```",
"I did this in the class where I got this error and it fixed the problem for me. \r\n\r\n`static {\r\n System.setProperty(\"org.mockito.android.target\", ApplicationProvider.getApplicationContext().getCacheDir().getPath()); \r\n}`",
"This should be fixed in #1583"
] | [
"Can you refactor the common part into a method so that only the String is different? That makes maintaining this piece of code a bit easier.",
"done"
] | "2019-01-08T18:19:56Z" | [
"android"
] | mockito-android "Could not look up implicit location for storing generated classes" with Jetpack (androidx) | I have Android emulator tests with these basic dependencies:
```
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test:rules:1.1.0-alpha4'
androidTestImplementation 'org.mockito:mockito-android:2.21.0'
```
Attempting to mock any interface results in exceptions similar to the following:
```
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface com.bumptech.glide.request.RequestListener.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
IMPORTANT INFORMATION FOR ANDROID USERS:
The regular Byte Buddy mock makers cannot generate code on an Android VM!
To resolve this, please use the 'mockito-android' dependency for your application:
http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22
Java : 0.9
JVM vendor name : The Android Project
JVM vendor version : 2.1.0
JVM name : Dalvik
JVM version : 0.9
JVM info : null
OS name : Linux
OS version : 3.18.91+
Underlying exception : org.mockito.exceptions.base.MockitoException:
Could not look up implicit location for storing generated classes
You can configure an explicit location by setting the system property
'org.mockito.android.target' to a folder for storing generated class files
This location must be in private scope for most API versions, for example:
MyActivity.this.getDir("target", Context.MODE_PRIVATE)
or
getInstrumentation().getTargetContext().getCacheDir().getPath()
```
A complete project where this is reproducible is available here: https://github.com/sjudd/glide/tree/broken_androidx_mockito_android
After checking out the project (and branch) and starting an Android emulator, you can reproduce with `./gradlew :instrumentation:connectedCheck.`
I believe this is caused by Mockito relying on reflection with the android.support package here: https://github.com/mockito/mockito/blob/ee175c682aca82ac25fd2d00250f5188d6a9e954/subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java#L26-L30
A simple solution is to just add in a check for the identical class in the androidx package. I'll send a pull request for that shortly.
| [
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java"
] | [
"subprojects/android/src/main/java/org/mockito/android/internal/creation/AndroidTempFileLocator.java"
] | [] | 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 a79816c4f5..34e179b40f 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,12 +23,10 @@ class AndroidTempFileLocator {
} catch (Throwable ignored) {
}
if (t == null) {
- 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) {
- }
+ t = getCacheDirFromInstrumentationRegistry("android.support.test.InstrumentationRegistry");
+ }
+ if (t == null) {
+ t = getCacheDirFromInstrumentationRegistry("androidx.test.InstrumentationRegistry");
}
if (t == null) {
try {
@@ -46,6 +44,16 @@ class AndroidTempFileLocator {
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)) {
| null | val | train | 2019-01-06T21:48:15 | "2018-08-10T21:51:10Z" | sjudd | train |
mockito/mockito/1584_1585 | mockito/mockito | mockito/mockito/1584 | mockito/mockito/1585 | [
"keyword_pr_to_issue"
] | 467a1bfb75b03a7ec526b5256629639cd990a7e0 | 00cc06b387c3af8aaaed3a14fcb38df7d69db6c1 | [
"@raphw FYI"
] | [] | "2019-01-09T16:11:43Z" | [] | ClassLoader built by mockito is not able to load declared types in the hierarchy in OSGi | We develop in OSGi environment and we are using latest version of mockito available on maven central 2.23.4
We got an issue when we mock classes given to guice (sisu) for injection. Sisu/Guice analyse all declared fields and methods for the input type and its super classes to built a sort of index of known types. In OSGi it fails with ClassNotFoundException on mocked classes. The reason is that the mocked class built with `SubclassBytecodeGenerator` has a classloader not able to load types reachable only by supertypes. In OSGi this does not happen because each class has associated the classloader from which is loaded. This guarantee that the class is able to reach/load each type it declares (by its methods, fields or annotations).
Example:
- Bundle A
`foo.Class1` has a protected method that returns foo.impl.OtherClass
`foo.impl.OtherClass`
- Bundle B (imports only `foo` package from bundle A)
`acme.Class2 extends Class1`
`Mockito.mock(foo.Class1).getDeclaredMethods()` will fails. To fix this issue `SubclassBytecodeGenerator` should compose a classloader (`MultipleParentClassLoader`) with also the classloader of superclass the mocked type (`features.mockedType`). | [
"src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java"
] | [] | 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 1985e80863..75b13fcfd9 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
@@ -28,7 +28,9 @@
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;
@@ -79,7 +81,7 @@ protected SubclassBytecodeGenerator(SubclassLoader loader, Implementation readRe
@Override
public <T> Class<? extends T> mockClass(MockFeatures<T> features) {
ClassLoader classLoader = new MultipleParentClassLoader.Builder()
- .appendMostSpecific(features.mockedType)
+ .appendMostSpecific(getAllTypes(features.mockedType))
.appendMostSpecific(features.interfaces)
.appendMostSpecific(currentThread().getContextClassLoader())
.appendMostSpecific(MockAccess.class)
@@ -173,6 +175,17 @@ public <T> Class<? extends T> mockClass(MockFeatures<T> features) {
.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;
+ }
+
private static ElementMatcher<MethodDescription> isGroovyMethod() {
return isDeclaredBy(named("groovy.lang.GroovyObjectSupport"));
}
| null | train | train | 2019-01-14T22:54:07 | "2019-01-09T11:37:11Z" | nfalco79 | train |
mockito/mockito/1587_1588 | mockito/mockito | mockito/mockito/1587 | mockito/mockito/1588 | [
"timestamp(timedelta=0.0, similarity=0.9093045693735561)",
"keyword_pr_to_issue"
] | be2faef4195d55484cbc58c27951849eebd9fc35 | 03432660ffd186bc04e53f62ca53178fa60b62ea | [] | [] | "2019-01-10T12:19:16Z" | [
"injection"
] | InjectingAnnotationEngine does an unnecessary loop. | processInjectMocks method of InjectingAnnotationEngine does unnecessary work. It might call injectMocks several times while it is sufficient to call injectMocks once.
private void processInjectMocks(final Class<?> clazz, final Object testInstance) {
Class<?> classContext = clazz;
while (classContext != Object.class) {
injectMocks(testInstance);
classContext = classContext.getSuperclass();
}
}
Inside, injectMocks loops classes by himself.
public void injectMocks(final Object testClassInstance) {
Class<?> clazz = testClassInstance.getClass();
Set<Field> mockDependentFields = new HashSet<Field>();
Set<Object> mocks = newMockSafeHashSet();
while (clazz != Object.class) {
new InjectMocksScanner(clazz).addTo(mockDependentFields);
new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks);
onInjection(testClassInstance, clazz, mockDependentFields, mocks);
clazz = clazz.getSuperclass();
}
new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance);
}
Why not delete the unnecessary loop? | [
"src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java"
] | [
"src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java"
] | [] | diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
index 6cb5fb123b..20d967d07e 100644
--- a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
+++ b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
@@ -39,15 +39,7 @@ public class InjectingAnnotationEngine implements AnnotationEngine, org.mockito.
*/
public void process(Class<?> clazz, Object testInstance) {
processIndependentAnnotations(testInstance.getClass(), 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();
- }
+ injectMocks(testInstance);
}
private void processIndependentAnnotations(final Class<?> clazz, final Object testInstance) {
| null | train | train | 2019-01-10T00:02:00 | "2019-01-10T12:16:12Z" | LihMeh | train |
mockito/mockito/1595_1602 | mockito/mockito | mockito/mockito/1595 | mockito/mockito/1602 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8999167219580725)"
] | 467a1bfb75b03a7ec526b5256629639cd990a7e0 | 1ae82bc15462b933573d932ed554662e78cdebfa | [
"My machine is still on JVM 11.0.1. Going to have to go through Travis this time around to debug this issue..."
] | [] | "2019-01-28T17:25:20Z" | [
"java-11",
"build"
] | Gradle javadoc plugin fails with latest JDK 11 release | The javadoc plugin fails with a status code 1 on current JVM 11.0.2 releases. | [
"build.gradle"
] | [
"build.gradle"
] | [] | diff --git a/build.gradle b/build.gradle
index a047ced6a9..0dac0c72f3 100644
--- a/build.gradle
+++ b/build.gradle
@@ -59,6 +59,12 @@ allprojects { proj ->
options.warnings = false
options.encoding = 'UTF-8'
}
+ tasks.withType(Javadoc) {
+ options.addStringOption('Xdoclint:none', '-quiet')
+ options.addStringOption('encoding', 'UTF-8')
+ options.addStringOption('charSet', 'UTF-8')
+ options.setSource('8')
+ }
apply plugin: 'checkstyle'
checkstyle {
configFile = rootProject.file('config/checkstyle/checkstyle.xml')
| null | test | train | 2019-01-14T22:54:07 | "2019-01-19T14:46:33Z" | raphw | train |
mockito/mockito/1615_1617 | mockito/mockito | mockito/mockito/1615 | mockito/mockito/1617 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8977929713305419)"
] | f11705be91ee3545bc006908b34425f1fc359898 | faeae6ac604e0103229a2ef23e35f88e10e026dd | [
"Suspiciously, the type is again in the `java.util` package. That leads me to believe any type definitive in there can't be mocked.",
"> That leads me to believe any type definitive in there can't be mocked.\r\n\r\nUsing `2.24.0`. It works with the older version.",
"The package should not be an issue, but I'll check. ",
"There is a dot missing after the package name....",
"Haha well spotted! Might be a simple String concatenation typo.",
"This is probably the mistake: https://github.com/mockito/mockito/blob/00cc06b387c3af8aaaed3a14fcb38df7d69db6c1/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java#L101\r\n\r\nShould be:\r\n\r\n```java\r\n typeName = InjectionBase.class.getPackage().getName() +\".\" + features.mockedType.getSimpleName();\r\n```",
"Yes, very much.\r\n\r\nCan it be that we don't have a test case for mocking a 'java.' type?\r\n\r\nAre yoilu on your machine? I'll fix it next week otherwise. ",
"Sadly not. I can work on it tomorrow as well. Luckily we have a test suite now 🎉 ",
"Or if @sormuras is available to make that PR, that would be amazing as well 😄 Our tests are specified in https://github.com/mockito/mockito/blob/f11705be91ee3545bc006908b34425f1fc359898/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java",
"Great, Tim!\r\n\r\nAny plans to sync current release to Maven Central, soon? 2.24.0 is the latest one that was uploaded: http://central.maven.org/maven2/org/mockito/mockito-core/maven-metadata.xml",
"I wanted to do so, but I first wanted to get some other issues resolved with @raphw Hopefully we can get to that next week. (but seems like we hit a JDK bug 🎉 )",
"Mockito 2.24.5 should be available on Maven central later today.",
"Looks good on 12: https://travis-ci.org/junit-team/junit5/jobs/495011557"
] | [] | "2019-02-11T15:27:29Z" | [
"java-12"
] | Issue with mocking type in "java.util.*", Java 12 | After upgrading Mockito from `2.23.4` to `2.24.0` we can't run JUnit 5's tests anymore. The error message reads:
```
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: interface java.util.concurrent.locks.Lock.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
```
Find the complete stacktrace here: https://travis-ci.org/junit-team/junit5/jobs/488684907
Note, that using Mockito `2.24.0` using Java 11 (and 13 locally) did work out! See this build matrix: https://travis-ci.org/junit-team/junit5/builds/488684905
Workaround: revert to Mockito `2.23.4` for the time being via https://github.com/junit-team/junit5/commit/754f1eb0f106ab043d79de546d49769690a731b6
| [
"src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java"
] | [
"src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java",
"subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java"
] | 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 8968b9e8e4..093978dd22 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/SubclassBytecodeGenerator.java
@@ -98,7 +98,7 @@ public <T> Class<? extends T> mockClass(MockFeatures<T> features) {
if (localMock || loader instanceof MultipleParentClassLoader && !isComingFromJDK(features.mockedType)) {
typeName = features.mockedType.getName();
} else {
- typeName = InjectionBase.class.getPackage().getName() + features.mockedType.getSimpleName();
+ typeName = InjectionBase.class.getPackage().getName() + "." + features.mockedType.getSimpleName();
}
String name = String.format("%s$%s$%d", typeName, "MockitoMock", Math.abs(random.nextInt()));
| diff --git a/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java b/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java
index 240cf7d027..f8a262d15d 100644
--- a/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java
+++ b/src/test/java/org/mockitousage/serialization/AcrossClassLoaderSerializationTest.java
@@ -33,7 +33,7 @@ public void check_that_mock_can_be_serialized_in_a_classloader_and_deserialized_
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.codegenAClassToBeMockedInThisTestOnlyAndInCallablesOnly");
+ 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/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java
index 6ec32893a6..ed732c8089 100644
--- a/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java
+++ b/subprojects/module-test/src/test/java/org/mockito/moduletest/ModuleHandlingTest.java
@@ -4,6 +4,7 @@
*/
package org.mockito.moduletest;
+import java.util.concurrent.locks.Lock;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.loading.ClassInjector;
@@ -91,6 +92,34 @@ public void can_define_class_in_open_reading_module() throws Exception {
}
}
+ @Test
+ public void can_define_class_in_open_java_util_module() throws Exception {
+ assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(false));
+
+ Path jar = modularJar(true, true, true);
+ ModuleLayer layer = layer(jar, true);
+
+ ClassLoader loader = layer.findLoader("mockito.test");
+ Class<?> type = loader.loadClass("java.util.concurrent.locks.Lock");
+
+ ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader(loader);
+ try {
+ Class<?> mockito = loader.loadClass(Mockito.class.getName());
+ @SuppressWarnings("unchecked")
+ Lock mock = (Lock) mockito.getMethod("mock", Class.class).invoke(null, type);
+ Object stubbing = mockito.getMethod("when", Object.class).invoke(null, mock.tryLock());
+ loader.loadClass(OngoingStubbing.class.getName()).getMethod("thenReturn", Object.class).invoke(stubbing, true);
+
+ boolean relocated = !Boolean.getBoolean("org.mockito.internal.noUnsafeInjection") && ClassInjector.UsingReflection.isAvailable();
+ String prefix = relocated ? "org.mockito.codegen.Lock$MockitoMock$" : "java.util.concurrent.locks.Lock$MockitoMock$";
+ assertThat(mock.getClass().getName()).startsWith(prefix);
+ assertThat(mock.tryLock()).isEqualTo(true);
+ } finally {
+ Thread.currentThread().setContextClassLoader(contextLoader);
+ }
+ }
+
@Test
public void inline_mock_maker_can_mock_closed_modules() throws Exception {
assumeThat(Plugins.getMockMaker() instanceof InlineByteBuddyMockMaker, is(true));
| train | val | 2019-02-05T00:24:14 | "2019-02-10T16:09:00Z" | sormuras | train |
mockito/mockito/1618_1620 | mockito/mockito | mockito/mockito/1618 | mockito/mockito/1620 | [
"keyword_pr_to_issue"
] | 34ebca1a8cd88465dd6e8ba395f78a6593522958 | d9cbe3e8ec9cafa521e61371d9e9600b7262cda7 | [
"We have observed similar things before. It seems like a mock is something keeping a hard reference to a listener. @TimvdLippe Do you remember me mentioning to having observed this some times? Were you working with the listener parts originally?",
"Yes I recall that discussion. The listener parts were introduced by @mockitoguy. I have run into this problem myself from time to time and have not figured out where it goes wrong. These listeners should not even be considered when serializing mocks."
] | [] | "2019-02-12T23:00:27Z" | [] | Serializable flag doesn't make mock serializable | I have a simple example test like this (I'm using junit5 with mockito-junit-jupiter extension)
```
@ExtendWith(MockitoExtension.class)
class ExampleTest {
@Mock(serializable = true) private Iterable<?> it;
@Test
void shouldSerializeAndDeserializeIt() throws IOException, ClassNotFoundException {
// when
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(it);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Iterable<?> deserializedIt = (Iterable<?>) new ObjectInputStream(in).readObject();
// then
assertThat(deserializedIt).isEqualToComparingFieldByFieldRecursively(it);
}
}
```
And I'm getting this error on during instance serialization:
```
java.io.NotSerializableException: org.mockito.internal.junit.DefaultStubbingLookupListener
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
at java.base/java.util.ArrayList.writeObject(ArrayList.java:896)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1130)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1497)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1553)
at java.base/java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1510)
at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1433)
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
```
| [
"src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java"
] | [
"src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java"
] | [
"src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java"
] | diff --git a/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java b/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java
index 21212a6754..b6a80c64a3 100644
--- a/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java
+++ b/src/main/java/org/mockito/internal/junit/DefaultStubbingLookupListener.java
@@ -12,6 +12,7 @@
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;
@@ -22,7 +23,9 @@
* 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 {
+class DefaultStubbingLookupListener implements StubbingLookupListener, Serializable {
+
+ private static final long serialVersionUID = -6789800638070123629L;
private Strictness currentStrictness;
private boolean mismatchesReported;
| diff --git a/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java b/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java
new file mode 100644
index 0000000000..9d786695fc
--- /dev/null
+++ b/src/test/java/org/mockitousage/serialization/StrictStubsSerializableTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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;
+ }
+ }
+}
| train | val | 2019-02-12T14:20:41 | "2019-02-12T21:47:14Z" | SimY4 | train |
mockito/mockito/1638_1639 | mockito/mockito | mockito/mockito/1638 | mockito/mockito/1639 | [
"timestamp(timedelta=6.0, similarity=0.853894488049074)"
] | d41ad6cb1c1018b334769ae595214c6c025f67a4 | 1df5e49043fb032106f5c0fc0eec97ca9251241f | [] | [] | "2019-02-28T02:45:54Z" | [] | Mockito.java contains inaccessible links to articles. | The monkeyisland.pl domain is no longer available.
List of inaccessible articles:
http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring
http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected
http://monkeyisland.pl/2008/04/26/asking-and-telling
http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index e2a0ade374..afbe082d9e 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -207,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. Not convinced? See <a href="http://monkeyisland.pl/2008/04/26/asking-and-telling">here</a>.
+ * //If your code doesn't care what get(0) returns, then it should not be stubbed.
* verify(mockedList).get(0);
* </code></pre>
*
@@ -426,8 +426,7 @@
* 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. You can find further reading
- * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
+ * Abusing it leads to <strong>overspecified</strong>, <strong>less maintainable</strong> tests.
*
* <p>
* See also {@link Mockito#never()} - it is more explicit and
@@ -598,8 +597,7 @@
* <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, the full article is
- * <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>)
+ * (3rd party interfaces, interim refactoring of legacy code).
* <p>
*
* <pre class="code"><code class="java">
@@ -708,8 +706,7 @@
* <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 - more reading:
- * <a href="http://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring">here</a>
+ * Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
* <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.
@@ -2070,7 +2067,6 @@ public static <T> T spy(Class<T> classToSpy) {
* 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
@@ -2102,7 +2098,6 @@ public static <T> OngoingStubbing<T> when(T methodCall) {
* 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
@@ -2204,8 +2199,7 @@ public static <T> void clearInvocations(T ... mocks) {
* 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. You can find further reading
- * <a href="http://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/">here</a>.
+ * Abusing it leads to overspecified, less maintainable tests.
* <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.
| null | train | val | 2019-02-28T02:19:18 | "2019-02-28T02:35:41Z" | PawelPamula | train |
mockito/mockito/1642_1644 | mockito/mockito | mockito/mockito/1642 | mockito/mockito/1644 | [
"keyword_pr_to_issue",
"timestamp(timedelta=8.0, similarity=0.9119012286113053)"
] | b745b5d48e9c110fa419fd007b3159ff612b8643 | 73f1d17e5b0ec1410e54a72334639da077e984f4 | [
"Update: I found that the lazy verification works properly when you use `VerificationCollector` directly. However, if you try and use it as a JUnit rule that's when this bug manifests.\r\n\r\nI have updated `VerificationCollectorImplTest` to properly test for this situation and fail as appropriate. I will have a quick look and see if it is an easy fix; otherwise I may submit a PR with the test only and leave a more experienced hand to fix it.",
"Another update: I have gotten to the root of this problem.\r\n\r\n>I found that the lazy verification works properly when you use VerificationCollector directly. However, if you try and use it as a JUnit rule that's when this bug manifests.\r\n\r\nThis wasn't quite correct. The distinguishing feature wasn't the JUnit rule, but if you do a verification for an invocation that tries to match on an argument while running under JUnit.\r\n\r\nThere is code in `org.mockito.internal.junit.ExceptionFactory` that checks to see if JUnit is on the classpath - if so, then it will throw `org.mockito.exceptions.verification.junit.ArgumentsAreDifferent` rather than `org.mockito.exceptions.verification.ArgumentsAreDifferent`. The JUnit version inherits from `junit.framework.ComparisonFailure` whereas the basic version inherits from `org.mockito.exceptions.base.MockitoAssertionError`.\r\n\r\nIt seems that the purpose of this is to help JUnit-aware GUIs to produce more helpful diagnostic output. This makes sense (although it would make more sense to derive from a more-up-to-date version of `ComparisonFailure` if it is available, like `org.junit.ComparisonFailure` - perhaps this could be the subject of a different issue/PR). However, because it is not a subclass of `MockitoAssertionError`, it skips out of the try/catch in `VerificationCollectorImpl` (see https://github.com/mockito/mockito/blob/b745b5d48e9c110fa419fd007b3159ff612b8643/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java#L92).\r\n\r\nThere are two possible solutions:\r\n\r\n1. Add another `catch()` to catch `ComparisonFailure` as well.\r\n2. Broaden the catch for `MockitoAssertionError` to a common superclass (like `AssertionError`).\r\n\r\nThe second probably has more generic appeal and would future-proof the solution if other types of argument comparison were used (eg, a custom argument matcher). I will submit a PR for this shortly."
] | [] | "2019-03-04T03:52:22Z" | [] | VerificationCollector doesn't work for invocations with non-matching args | I found the incubating `VerificationCollector` (#287), which is similar to AssertJ `SoftAssertion`s in that it collects multiple verifications and then asserts on the whole, rather than throwing an exception on the first one and skipping the rest of the verifications. Very useful for complicated testing.
However, I found that the verification collector doesn't work for verifications on method invocations with parameters. I had a quick check of the source code of the test, and I noticed that all of the tests in `VerificationCollectorImplTest` use no-arg invocations.
Hopefully this would be an easy fix, because this looks like an extremely useful feature for my application but I need to verify invocations with arguments. At the moment, my workaround is to wrap each verification call in an AssertJ soft assertion, but this makes writing the tests a bit more tedious and less readable.
| [
"src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java"
] | [
"src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java"
] | [
"src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java"
] | diff --git a/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java b/src/main/java/org/mockito/internal/junit/VerificationCollectorImpl.java
index 7c19d35652..e54d47864e 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 @@ private void append(String message) {
this.numberOfFailures++;
this.builder.append('\n')
.append(this.numberOfFailures).append(". ")
- .append(message.substring(1, message.length()));
+ .append(message.trim()).append('\n');
}
private class VerificationWrapper implements VerificationMode {
@@ -89,7 +89,7 @@ private VerificationWrapper(VerificationMode delegate) {
public void verify(VerificationData data) {
try {
this.delegate.verify(data);
- } catch (MockitoAssertionError error) {
+ } catch (AssertionError error) {
VerificationCollectorImpl.this.append(error.getMessage());
}
}
| diff --git a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
index 8f4c420eca..9b4cc1ec1c 100644
--- a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
+++ b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java
@@ -8,13 +8,14 @@
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.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.Mockito.*;
public class VerificationCollectorImplTest {
@@ -46,14 +47,54 @@ public void should_collect_multiple_verification_failures() {
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();
- fail();
+ failBecauseExceptionWasNotThrown(MockitoAssertionError.class);
} 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:");
}
}
@@ -66,7 +107,7 @@ public void should_only_collect_failures_ignore_successful_verifications() {
verify(methods, never()).simpleMethod();
verify(methods).byteReturningMethod();
- this.assertAtLeastOneFailure(collector);
+ this.assertExactlyOneFailure(collector);
}
@Test
@@ -79,13 +120,13 @@ public void should_continue_collecting_after_failing_verification() {
verify(methods).byteReturningMethod();
verify(methods).simpleMethod();
- this.assertAtLeastOneFailure(collector);
+ this.assertExactlyOneFailure(collector);
}
- private void assertAtLeastOneFailure(VerificationCollector collector) {
+ private void assertExactlyOneFailure(VerificationCollector collector) {
try {
collector.collectAndReport();
- fail();
+ failBecauseExceptionWasNotThrown(MockitoAssertionError.class);
} catch (MockitoAssertionError error) {
assertThat(error).hasMessageContaining("1. Wanted but not invoked:");
assertThat(error.getMessage()).doesNotContain("2.");
@@ -97,8 +138,11 @@ public void should_invoke_collector_rule_after_test() {
JUnitCore runner = new JUnitCore();
Result result = runner.run(VerificationCollectorRuleInner.class);
- assertThat(result.getFailureCount()).isEqualTo(1);
- assertThat(result.getFailures().get(0).getMessage()).contains("1. Wanted but not invoked:");
+ 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:");
}
// This class is picked up when running a test suite using an IDE. It fails on purpose.
@@ -121,5 +165,14 @@ public void should_not_fail() {
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();
+ }
}
}
| train | val | 2019-03-01T14:13:09 | "2019-03-03T23:45:20Z" | kriegfrj | train |
mockito/mockito/1609_1646 | mockito/mockito | mockito/mockito/1609 | mockito/mockito/1646 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8876214866028436)"
] | ab645dd40bf7152743c6a0ee45b8c9cd692e7639 | 2a7489d316b2a733aa6306b3a829d2e8fedb46ae | [
"For more information see the error-prone bugpattern: https://errorprone.info/bugpattern/TypeParameterUnusedInFormals",
"@mockitoguy WDYT? I think it makes sense to have a simple API for local assignments or in return statements, but we would still need the Class to be explicit.",
"Looking...",
"Good idea! Few suggestions:\r\n - document clearly the use case in the new method (compact, readable tests / one-liner invocations).\r\n - add NotExtensible annotation to InvocationOnMock\r\n\r\nNice catch.\r\n",
"Awesome, thanks for the quick response! Will open a PR today :smile: ",
"Instead of using the reintroduced `getArgument<T>(int, Class<T>)`, IIUC the issue described above can also be solved as follows:\r\n```java\r\ninvocation.<Runnable>getArgument(0).run()\r\n```\r\nThat's admittedly less obvious, but does keep the API smaller. Has this been considered?",
"While that does work as well, I think consistency with the old API as well as the readability of the former vs the latter would still lead me to conclude that reintroducing is the appropriate solution."
] | [] | "2019-03-04T15:13:15Z" | [] | Add back InvocationOnMock.getArgument<T>(int, Class<T>) | In https://github.com/mockito/mockito/issues/365 we replaced the existing `getArgumentAt<T>(int, Class<T>)` API with the current `getArgument(int)` API. However, when integrating this change within Google, we ran into numerous issues.
An example:
```java
invocation.getArgumentAt(0, Runnable.class).run()
```
gets rewritten to
```java
invocation.getArgument(0).run()
```
This does not compile, as the generic parameter is erasured to `Object` and thus does not have the `run` method.
Therefore, I would propose adding back an overload to `getArgument` that allows you to specify the `Class`. In general, users would not need this inside a variable assignment, but do need it in all other cases. | [
"src/main/java/org/mockito/MockSettings.java",
"src/main/java/org/mockito/MockitoFramework.java",
"src/main/java/org/mockito/MockitoSession.java",
"src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java",
"src/main/java/org/mockito/invocation/InvocationOnMock.java",
"src/main/java/org/mockito/session/MockitoSessionBuilder.java",
"src/main/java/org/mockito/session/MockitoSessionLogger.java"
] | [
"src/main/java/org/mockito/MockSettings.java",
"src/main/java/org/mockito/MockitoFramework.java",
"src/main/java/org/mockito/MockitoSession.java",
"src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java",
"src/main/java/org/mockito/invocation/InvocationOnMock.java",
"src/main/java/org/mockito/session/MockitoSessionBuilder.java",
"src/main/java/org/mockito/session/MockitoSessionLogger.java"
] | [] | diff --git a/src/main/java/org/mockito/MockSettings.java b/src/main/java/org/mockito/MockSettings.java
index 95fcfe3236..07af55e377 100644
--- a/src/main/java/org/mockito/MockSettings.java
+++ b/src/main/java/org/mockito/MockSettings.java
@@ -44,6 +44,7 @@
* 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 {
/**
diff --git a/src/main/java/org/mockito/MockitoFramework.java b/src/main/java/org/mockito/MockitoFramework.java
index 58cd4b67ea..da03ef4d80 100644
--- a/src/main/java/org/mockito/MockitoFramework.java
+++ b/src/main/java/org/mockito/MockitoFramework.java
@@ -20,6 +20,7 @@
* @since 2.1.0
*/
@Incubating
+@NotExtensible
public interface MockitoFramework {
/**
diff --git a/src/main/java/org/mockito/MockitoSession.java b/src/main/java/org/mockito/MockitoSession.java
index 9e820f269b..6a529fde43 100644
--- a/src/main/java/org/mockito/MockitoSession.java
+++ b/src/main/java/org/mockito/MockitoSession.java
@@ -88,6 +88,7 @@
* @since 2.7.0
*/
@Incubating
+@NotExtensible
public interface MockitoSession {
/**
diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
index b9cf0721f4..37cc451829 100644
--- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
+++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
@@ -119,6 +119,11 @@ public <T> T getArgument(int index) {
return (T) arguments[index];
}
+ @Override
+ public <T> T getArgument(int index, Class<T> clazz) {
+ return clazz.cast(arguments[index]);
+ }
+
@Override
public Object callRealMethod() throws Throwable {
if (!realMethod.isInvokable()) {
diff --git a/src/main/java/org/mockito/invocation/InvocationOnMock.java b/src/main/java/org/mockito/invocation/InvocationOnMock.java
index 345ddb9d45..8fabfa0e2d 100644
--- a/src/main/java/org/mockito/invocation/InvocationOnMock.java
+++ b/src/main/java/org/mockito/invocation/InvocationOnMock.java
@@ -7,6 +7,7 @@
import java.io.Serializable;
import java.lang.reflect.Method;
+import org.mockito.NotExtensible;
/**
* An invocation on a mock.
@@ -14,6 +15,7 @@
* <p>
* A placeholder for mock, the method that was called and the arguments that were passed.
*/
+@NotExtensible
public interface InvocationOnMock extends Serializable {
/**
@@ -44,12 +46,35 @@ public interface InvocationOnMock extends Serializable {
*
* 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
*/
<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>
diff --git a/src/main/java/org/mockito/session/MockitoSessionBuilder.java b/src/main/java/org/mockito/session/MockitoSessionBuilder.java
index b3a758bac0..b17cfe77d6 100644
--- a/src/main/java/org/mockito/session/MockitoSessionBuilder.java
+++ b/src/main/java/org/mockito/session/MockitoSessionBuilder.java
@@ -7,6 +7,7 @@
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;
@@ -17,6 +18,7 @@
* @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 e5f40ad565..f876433c57 100644
--- a/src/main/java/org/mockito/session/MockitoSessionLogger.java
+++ b/src/main/java/org/mockito/session/MockitoSessionLogger.java
@@ -6,6 +6,7 @@
import org.mockito.Incubating;
import org.mockito.MockitoSession;
+import org.mockito.NotExtensible;
/**
* Logger for {@linkplain org.mockito.quality.MockitoHint hints} emitted when
@@ -17,6 +18,7 @@
* @since 2.15.0
*/
@Incubating
+@NotExtensible
public interface MockitoSessionLogger {
/**
| null | test | val | 2019-03-08T17:48:53 | "2019-02-05T16:53:30Z" | TimvdLippe | train |
mockito/mockito/1645_1647 | mockito/mockito | mockito/mockito/1645 | mockito/mockito/1647 | [
"keyword_pr_to_issue"
] | 19adbf3dea958acbbdcb078b550a6797e3e7557d | 3701597af7fcf306684c5e86d18e613f618b5d77 | [
"@TimvdLippe it looks like we fixed this one in https://github.com/mockito/shipkit/pull/782.\r\nI can do some local testing and provide a PR for this one soon (shipkit version update).",
"Thanks for that @epeee Looking forward to that PR.",
"Thank you guys!"
] | [] | "2019-03-04T17:36:20Z" | [] | Release build is failing | After the latest Shipkit update, our Travis is failing: https://travis-ci.org/mockito/mockito/jobs/501397895#L1693 It fails with
```
[commit] 2 files changed, 11 insertions(+), 2 deletions(-)
[performRelease] External process [commit] completed.
[performRelease] [tag] fatal: tag 'v2.24.8' already exists
```
@mstachniuk could you take a look? | [
"build.gradle",
"version.properties"
] | [
"build.gradle",
"version.properties"
] | [] | diff --git a/build.gradle b/build.gradle
index c8142db658..4285ff16ff 100644
--- a/build.gradle
+++ b/build.gradle
@@ -11,7 +11,7 @@ buildscript {
classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.6'
//Using buildscript.classpath so that we can resolve shipkit from maven local, during local testing
- classpath 'org.shipkit:shipkit:2.1.3'
+ classpath 'org.shipkit:shipkit:2.1.6'
}
}
diff --git a/version.properties b/version.properties
index 5c5d37b0ac..19b0042628 100644
--- a/version.properties
+++ b/version.properties
@@ -1,5 +1,5 @@
#Currently building Mockito version
-version=2.24.8
+version=2.24.9
#Previous version used to generate release notes delta
previousVersion=2.24.7
| null | train | val | 2019-03-04T16:20:43 | "2019-03-04T15:12:41Z" | TimvdLippe | train |
mockito/mockito/1664_1665 | mockito/mockito | mockito/mockito/1664 | mockito/mockito/1665 | [
"keyword_pr_to_issue"
] | d6098a6bbdfbafd966a2078627a90d9ffbedc7ea | ac5bd58ab33e7d8a5b4a38fa4cf2fe10c78a5d22 | [] | [
"What is the reasoning for making this protected? It is an internal class, so it should not be subclassed.",
"I don't see these being used anywhere else. Moreover, they are not on the interface `Invocation`. If we were to add them, they have to be on the interface.",
"I currently need to extend it to replace the InvocationMatcher, so I made it protected just in case, but I'm happy to leave it private if you prefer so",
"I'm calling it from mockito-scala, should I add it to the interface then?",
"We cannot do it. It's leaking internal API via a public API.",
">should I add it to the interface then?\r\n\r\nPlease no. MockReference is an internal type and we should not leak it from a public interface.",
"@TimvdLippe, I'm ok with changing private method to protected on an internal type so that mockito-scala integration is easier in the short term. @bbonanno is aware that we don't guarantee compatibility for internal API in the long term.",
"This is good! We can add this method to the public API because it returns a public type.",
"Can you add \"since\" tag because it's a new public API?",
"Can you add a note that the method converts each argument using ArgumentMatchers.eq() or AdditionalMatchers.arryEq() and that it is used internally for the purposes of human-readable invocation printing.\r\n\r\nI don't want users to confuse this new method with the MatchableInvocation.getMatchers() method.",
":)",
"Can you use Javadoc link? Thank you :)",
"Ups, sorry about that"
] | "2019-03-16T20:12:52Z" | [] | Make invocation to drive its printing | Right now the `toString()` of an `Invocation` is ignored when it's being printed for a verification error, this prevents mockito-scala from providing a custom representation of the arguments via the implicit context.
With a simple change to drive the printing from within the `Invocation` the problem can be solved | [
"src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java",
"src/main/java/org/mockito/internal/reporting/PrintSettings.java",
"src/main/java/org/mockito/invocation/Invocation.java"
] | [
"src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java",
"src/main/java/org/mockito/internal/invocation/InvocationMatcher.java",
"src/main/java/org/mockito/internal/reporting/PrintSettings.java",
"src/main/java/org/mockito/invocation/Invocation.java"
] | [
"src/test/java/org/mockito/internal/invocation/InvocationBuilder.java",
"src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
index 37cc451829..ec1fcba173 100644
--- a/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
+++ b/src/main/java/org/mockito/internal/invocation/InterceptedInvocation.java
@@ -4,6 +4,7 @@
*/
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;
@@ -13,8 +14,10 @@
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 {
@@ -119,6 +122,23 @@ public <T> T getArgument(int index) {
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]);
@@ -154,7 +174,7 @@ private boolean equalArguments(Object[] arguments) {
}
public String toString() {
- return new PrintSettings().print(ArgumentsProcessor.argumentsToMatchers(getArguments()), this);
+ return new PrintSettings().print(getArgumentsAsMatchers(), 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 83a28ff9de..bc14300a3e 100644
--- a/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
+++ b/src/main/java/org/mockito/internal/invocation/InvocationMatcher.java
@@ -5,7 +5,6 @@
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;
@@ -36,7 +35,7 @@ public class InvocationMatcher implements MatchableInvocation, DescribedInvocati
public InvocationMatcher(Invocation invocation, List<ArgumentMatcher> matchers) {
this.invocation = invocation;
if (matchers.isEmpty()) {
- this.matchers = (List) argumentsToMatchers(invocation.getArguments());
+ this.matchers = (List) invocation.getArgumentsAsMatchers();
} else {
this.matchers = (List) matchers;
}
diff --git a/src/main/java/org/mockito/internal/reporting/PrintSettings.java b/src/main/java/org/mockito/internal/reporting/PrintSettings.java
index 7986c35cec..4fc59926ea 100644
--- a/src/main/java/org/mockito/internal/reporting/PrintSettings.java
+++ b/src/main/java/org/mockito/internal/reporting/PrintSettings.java
@@ -5,7 +5,6 @@
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;
@@ -55,7 +54,7 @@ public String print(List<ArgumentMatcher> matchers, Invocation invocation) {
}
public String print(Invocation invocation) {
- return print(ArgumentsProcessor.argumentsToMatchers(invocation.getArguments()), invocation);
+ return print(invocation.getArgumentsAsMatchers(), invocation);
}
public String print(MatchableInvocation invocation) {
diff --git a/src/main/java/org/mockito/invocation/Invocation.java b/src/main/java/org/mockito/invocation/Invocation.java
index 131db8441f..fa2e324114 100644
--- a/src/main/java/org/mockito/invocation/Invocation.java
+++ b/src/main/java/org/mockito/invocation/Invocation.java
@@ -4,8 +4,11 @@
*/
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.
@@ -47,6 +50,16 @@ public interface Invocation extends InvocationOnMock, DescribedInvocation {
*/
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/test/java/org/mockito/internal/invocation/InvocationBuilder.java b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
index 4fc5cb1c1c..4e01535027 100644
--- a/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
+++ b/src/test/java/org/mockito/internal/invocation/InvocationBuilder.java
@@ -6,6 +6,7 @@
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;
@@ -61,7 +62,7 @@ public Invocation toInvocation() {
}
}
- Invocation i = new InterceptedInvocation(new MockStrongReference<Object>(mock, false),
+ Invocation i = createInvocation(new MockStrongReference<Object>(mock, false),
new SerializableMethod(method),
args,
NO_OP,
@@ -73,6 +74,11 @@ public Invocation toInvocation() {
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;
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 15a57b96d6..107f5ce8f8 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
@@ -5,78 +5,125 @@
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.WantedButNotInvoked;
import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
-import org.mockito.internal.invocation.InvocationBuilder;
-import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.exceptions.verification.WantedButNotInvoked;
+import org.mockito.internal.invocation.*;
+import org.mockito.internal.invocation.mockref.MockReference;
import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
-public class MissingInvocationCheckerTest extends TestBase {
-
- private InvocationMatcher wanted;
- private List<Invocation> invocations;
-
- @Mock
- private IMethods mock;
-
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
- @Test
- public void shouldPassBecauseActualInvocationFound() {
- wanted = buildSimpleMethod().toInvocationMatcher();
- invocations = asList(buildSimpleMethod().toInvocation());
-
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
-
- @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();");
-
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
-
- @Test
- public void shouldReportWantedInvocationDiffersFromActual() {
- wanted = buildIntArgMethod().arg(2222).toInvocationMatcher();
- invocations = asList(buildIntArgMethod().arg(1111).toInvocation());
-
- 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);");
-
- MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
- }
+import java.util.ArrayList;
+import java.util.List;
- private InvocationBuilder buildIntArgMethod() {
- return new InvocationBuilder().mock(mock).method("intArgumentMethod").argTypes(int.class);
- }
+import static java.util.Arrays.asList;
+import static java.util.Collections.singletonList;
- private InvocationBuilder buildSimpleMethod() {
- return new InvocationBuilder().mock(mock).simpleMethod();
- }
+public class MissingInvocationCheckerTest extends TestBase {
- private InvocationBuilder buildDifferentMethod() {
- return new InvocationBuilder().mock(mock).differentMethod();
- }
+ private InvocationMatcher wanted;
+ private List<Invocation> invocations;
+
+ @Mock
+ private IMethods mock;
+
+ @Rule
+ public ExpectedException exception = ExpectedException.none();
+
+ @Test
+ public void shouldPassBecauseActualInvocationFound() {
+ wanted = buildSimpleMethod().toInvocationMatcher();
+ invocations = asList(buildSimpleMethod().toInvocation());
+
+ MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
+ }
+
+ @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();");
+
+ MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
+ }
+
+ @Test
+ public void shouldReportWantedInvocationDiffersFromActual() {
+ wanted = buildIntArgMethod(new InvocationBuilder()).arg(2222).toInvocationMatcher();
+ invocations = asList(buildIntArgMethod(new InvocationBuilder()).arg(1111).toInvocation());
+
+ 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);");
+
+ MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
+ }
+
+ @Test
+ public void shouldReportUsingInvocationDescription() {
+ wanted = buildIntArgMethod(new CustomInvocationBuilder()).arg(2222).toInvocationMatcher();
+ invocations = singletonList(buildIntArgMethod(new CustomInvocationBuilder()).arg(1111).toInvocation());
+
+ exception.expect(ArgumentsAreDifferent.class);
+
+ 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;
+ }
+ };
+ }
+ }
}
| train | val | 2019-03-23T15:50:20 | "2019-03-16T20:11:36Z" | ultrasecreth | train |
mockito/mockito/1663_1667 | mockito/mockito | mockito/mockito/1663 | mockito/mockito/1667 | [
"timestamp(timedelta=0.0, similarity=0.9492359482839157)"
] | a323b8132de6f6e1c29d738de245469f8ce009b0 | 56a30b31a00060a4a952c87d49c53f871ade4d75 | [
"Changing the exception type is an incompatible change in a strict sense. However, we need to be able to improve the framework by tweaking the exceptions if needed. We always strive to be compatible. There are no known legit use cases why our users would want to catch & handle specific Mockito exceptions. It's OK to change the type of ArgumentsAreDifferent exception.",
"I'm happy to take this on, per your request. The hardest part was the question of whether/how to handle backward compatibility. Should have a PR submitted by Monday.",
"> The hardest part was the question of whether/how to handle backward compatibility\r\n\r\nWe are OK with this incompatible change (see my other comment). Thanks for taking this on!!!\r\n\r\n"
] | [
"We will get to that when we switch to Java 1.8. Let's remove these comments for now.",
"Done.",
"Great! \"compileOnly\" is exactly the way to go!",
"Let's just say \"JUnit\", instead of \"JUnit 3\" in the javadocs. It will be less confusing.",
"Let's change \"JUnit 3\" -> \"Junit\" in all new javadoc",
"Can you confirm one thing for me? This import needs to change because test runtime classpath inherits opentest4j from \"compileOnly\"?",
"Yes. This was the \"imperfect\" behaviour I was referring to. Even though it's only using the JUnit 4 runner, it finds OpenTest4J on the classpath and uses it.",
"Will do. This is a hangover from the earlier prototype which also supported `org.junit.ComparisonFailure` as well as `junit.framework.ComparisonFailure`.",
"As above.",
"I started to implement this change and had a rethink. Merely saying \"...if JUnit is on the class path...\" is inaccurate. Specifically, `junit.framework.ComparisonFailure` must be on the classpath, which is included in JUnit 3 & 4 but not 5. So the current implementation will not throw a ComparisonFailure if JUnit 5 is on the classpath but JUnit 3/4 is not.",
"Thanks!",
"Thanks!",
"OK"
] | "2019-03-18T09:19:25Z" | [] | Improve IDE UX comparison failure for JUnit5 | When JUnit4 is used and the test is invoked from IDE (IDEA or Eclipse), and we are getting "arguments are different" MockitoVerificationError, the IDE gets nice "click to see the difference" link in the test failure, providing neat comparison pop-up.
We want to provide this feature for JUnit5, too. We do not want to add a new dependency on mockito (e.g. OpenTest4J). Rather, we can use reflection just like we do it now for JUnit4 or how AssertJ integrates with JUnit5.
Spin-off from #1656 | [
"build.gradle",
"gradle/dependencies.gradle",
"gradle/mockito-core/osgi.gradle",
"src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java",
"src/main/java/org/mockito/exceptions/verification/junit/package-info.java",
"src/main/java/org/mockito/internal/junit/ExceptionFactory.java"
] | [
"build.gradle",
"gradle/dependencies.gradle",
"gradle/mockito-core/osgi.gradle",
"src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java",
"src/main/java/org/mockito/exceptions/verification/junit/package-info.java",
"src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java",
"src/main/java/org/mockito/exceptions/verification/opentest4j/package-info.java",
"src/main/java/org/mockito/internal/junit/ExceptionFactory.java"
] | [
"src/test/java/org/mockito/StaticMockingExperimentTest.java",
"src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java",
"src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java",
"src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java",
"src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java",
"src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java",
"src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java",
"src/test/java/org/mockitousage/matchers/HamcrestMatchersTest.java",
"src/test/java/org/mockitousage/matchers/MatchersTest.java",
"src/test/java/org/mockitousage/matchers/MoreMatchersTest.java",
"src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java",
"src/test/java/org/mockitousage/matchers/VarargsTest.java",
"src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java",
"src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java",
"src/test/java/org/mockitousage/verification/BasicVerificationTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java",
"src/test/java/org/mockitousage/verification/PrintingVerboseTypesWithArgumentsTest.java",
"src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java"
] | diff --git a/build.gradle b/build.gradle
index 4285ff16ff..daee5a92b5 100644
--- a/build.gradle
+++ b/build.gradle
@@ -78,7 +78,7 @@ configurations {
dependencies {
compile libraries.bytebuddy, libraries.bytebuddyagent
- compileOnly libraries.junit4, libraries.hamcrest
+ compileOnly libraries.junit4, libraries.hamcrest, libraries.opentest4j
compile libraries.objenesis
testCompile libraries.asm
diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index f164631907..91592b3de6 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -13,6 +13,7 @@ libraries.junitPlatformLauncher = 'org.junit.platform:junit-platform-launcher:1.
libraries.junitJupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${versions.junitJupiter}"
libraries.assertj = 'org.assertj:assertj-core:2.9.0'
libraries.hamcrest = 'org.hamcrest:hamcrest-core:1.3'
+libraries.opentest4j = 'org.opentest4j:opentest4j:1.1.1'
libraries.bytebuddy = "net.bytebuddy:byte-buddy:${versions.bytebuddy}"
libraries.bytebuddyagent = "net.bytebuddy:byte-buddy-agent:${versions.bytebuddy}"
diff --git a/gradle/mockito-core/osgi.gradle b/gradle/mockito-core/osgi.gradle
index 90a32eb6f8..1e942f6569 100644
--- a/gradle/mockito-core/osgi.gradle
+++ b/gradle/mockito-core/osgi.gradle
@@ -21,6 +21,7 @@ afterEvaluate {
'org.junit.*;resolution:=optional',
'org.hamcrest;resolution:=optional',
'org.objenesis;version="[2.5,3.0)"',
+ 'org.opentest4j.*;resolution:=optional',
'org.mockito.*'
instruction 'Private-Package',
diff --git a/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java b/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
index a44cc6fdb4..5a72f20f48 100644
--- a/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
+++ b/src/main/java/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
@@ -17,6 +17,19 @@ public ArgumentsAreDifferent(String message) {
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 4542d34b48..ad4ab7751f 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,6 +4,9 @@
*/
/**
- * JUnit integration to provide better support for junit runners in IDEs.
+ * JUnit integration to provide better support for JUnit 4 and
+ * earlier in IDEs.
+ *
+ * @see org.mockito.exceptions.verification.opentest4j
*/
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
new file mode 100644
index 0000000000..8f50d00a70
--- /dev/null
+++ b/src/main/java/org/mockito/exceptions/verification/opentest4j/ArgumentsAreDifferent.java
@@ -0,0 +1,42 @@
+/*
+ * 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
new file mode 100644
index 0000000000..2e84ddd662
--- /dev/null
+++ b/src/main/java/org/mockito/exceptions/verification/opentest4j/package-info.java
@@ -0,0 +1,12 @@
+/*
+ * 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/junit/ExceptionFactory.java b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
index ee288d614a..5db296ef5c 100644
--- a/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
+++ b/src/main/java/org/mockito/internal/junit/ExceptionFactory.java
@@ -4,49 +4,58 @@
*/
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() {
}
- /**
- * 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 static interface ExceptionFactoryImpl {
+ AssertionError create(String message, String wanted, String actual);
}
- private static AssertionError createJUnitArgumentsAreDifferent(String message, String wanted, String actual) {
- return JUnitArgsAreDifferent.create(message, wanted, actual);
- }
+ private final static ExceptionFactoryImpl factory;
+
+ static {
+ ExceptionFactoryImpl theFactory = null;
- private static boolean canLoadJunitClass() {
try {
- JUnitArgsAreDifferent.create("message", "wanted", "actual");
- } catch (Throwable onlyIfJUnitIsNotAvailable) {
- return false;
+ 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) {
+ }
}
- return true;
+ factory = (theFactory == null) ? new ExceptionFactoryImpl() {
+ @Override
+ public AssertionError create(String message, String wanted, String actual) {
+ return new ArgumentsAreDifferent(message, wanted, actual);
+ }
+ } : theFactory;
}
/**
- * 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.
+ * 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}.
*/
- private static class JUnitArgsAreDifferent {
- static AssertionError create(String message, String wanted, String actual) {
- return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual);
- }
+ public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
+ return factory.create(message, wanted, actual);
}
}
| diff --git a/src/test/java/org/mockito/StaticMockingExperimentTest.java b/src/test/java/org/mockito/StaticMockingExperimentTest.java
index cc8a5988e4..c6312e75e0 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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/junit/ExceptionFactoryTest.java b/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
index a1e2564c5d..2c1037bae2 100644
--- a/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
+++ b/src/test/java/org/mockito/internal/junit/ExceptionFactoryTest.java
@@ -8,51 +8,95 @@
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 classLoaderWithoutJUnit = excludingClassLoader().withCodeSourceUrlOf(ExceptionFactory.class).without("org.junit", "junit").build();
+ private static ClassLoader classLoaderWithoutJUnitOrOpenTest = excludingClassLoader().withCodeSourceUrlOf(ExceptionFactory.class).without("org.junit", "junit", "org.opentest4j").build();
+ private static ClassLoader classLoaderWithoutOpenTest = excludingClassLoader().withCodeSourceUrlOf(ExceptionFactory.class, org.junit.ComparisonFailure.class).without("org.opentest4j").build();
+ private static ClassLoader currentClassLoader = ExceptionFactoryTest.class.getClassLoader();
+
+ /** loaded by the current classloader */
+ private static Class<?> opentestComparisonFailure;
+ private static Class<?> opentestArgumentsAreDifferent;
- /** loaded by the 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 #classLoaderWithoutJUnit}, which excludes junit-classes */
+ /** loaded by the custom classloader {@value #classLoaderWithoutJUnitOrOpenTest}, which excludes JUnit and OpenTest4J classes */
private static Class<?> nonJunitArgumentsAreDifferent;
@BeforeClass
public static void init() throws ClassNotFoundException {
- nonJunitArgumentsAreDifferent = classLoaderWithoutJUnit.loadClass(ArgumentsAreDifferent.class.getName());
- junitArgumentsAreDifferent = org.mockito.exceptions.verification.junit.ArgumentsAreDifferent.class;
+ 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;
}
@Test
- public void createArgumentsAreDifferentException_withoutJUnit() throws Exception {
- Class<?> exceptionFactory = classLoaderWithoutJUnit.loadClass(ExceptionFactory.class.getName());
+ public void createArgumentsAreDifferentException_withoutJUnitOrOpenTest() throws Exception {
+ AssertionError e = invokeFactoryThroughLoader(classLoaderWithoutJUnitOrOpenTest);
- Method m = exceptionFactory.getDeclaredMethod("createArgumentsAreDifferentException", String.class, String.class, String.class);
- Object e = m.invoke(null, "message", "wanted", "actual");
+ 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_withJUnit() throws Exception {
- AssertionError e = ExceptionFactory.createArgumentsAreDifferentException("message", "wanted", "actual");
+ public void createArgumentsAreDifferentException_withJUnit3_2x() throws Exception {
+ AssertionError e;
+
+ e = invokeFactoryThroughLoader(classLoaderWithoutOpenTest);
+ assertThat(e).isExactlyInstanceOf(junit3ArgumentsAreDifferent);
- assertThat(e).isExactlyInstanceOf(junitArgumentsAreDifferent);
+ e = invokeFactoryThroughLoader(classLoaderWithoutOpenTest);
+ assertThat(e).isExactlyInstanceOf(junit3ArgumentsAreDifferent);
}
@Test
- public void createArgumentsAreDifferentException_withJUnit2x() throws Exception {
+ public void createArgumentsAreDifferentException_withOpenTest_2x() throws Exception {
AssertionError e;
- e = ExceptionFactory.createArgumentsAreDifferentException("message", "wanted", "actual");
- assertThat(e).isExactlyInstanceOf(junitArgumentsAreDifferent);
+ 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());
- e = ExceptionFactory.createArgumentsAreDifferentException("message", "wanted", "actual");
- assertThat(e).isExactlyInstanceOf(junitArgumentsAreDifferent);
+ Method m = exceptionFactory.getDeclaredMethod("createArgumentsAreDifferentException", String.class, String.class, String.class);
+ return (AssertionError) m.invoke(null, "message", "wanted", "actual");
}
}
diff --git a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
index e846216cbf..2e567427a2 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 4ce557ec66..15a57b96d6 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
@@ -13,7 +13,7 @@
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.exceptions.verification.WantedButNotInvoked;
-import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.Invocation;
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 7f37b12d44..51cbc02c70 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 90569a8117..85e0113589 100644
--- a/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
+++ b/src/test/java/org/mockitointegration/NoJUnitDependenciesTest.java
@@ -33,10 +33,10 @@ public void pure_mockito_should_not_depend_JUnit___ByteBuddy() throws Exception
Objenesis.class
)
.withCodeSourceUrlOf(coverageTool())
- .without("junit", "org.junit")
+ .without("junit", "org.junit", "org.opentest4j")
.build();
- Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit").listOwnedClasses();
+ Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit", "opentest4j").listOwnedClasses();
// The later class is required to be initialized before any inline mock maker classes can be loaded.
checkDependency(classLoader_without_JUnit, "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker");
diff --git a/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java b/src/test/java/org/mockitousage/basicapi/UsingVarargsTest.java
index 3e4faaf923..c8f3dd5bdc 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockitoutil.TestBase;
import java.util.ArrayList;
diff --git a/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java b/src/test/java/org/mockitousage/matchers/CustomMatcherDoesYieldCCETest.java
index 3114834182..8c94d3d1f6 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 bee9569bf5..4d6b868cf8 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 51a227d215..d38e676e96 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
index f446f57f5c..6c0f9c2dc3 100644
--- a/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
+++ b/src/test/java/org/mockitousage/matchers/MoreMatchersTest.java
@@ -9,7 +9,7 @@
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java
index 84ad482103..a972d0fbbb 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 685c918a12..1433919d72 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockitousage.IMethods;
diff --git a/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java b/src/test/java/org/mockitousage/stacktrace/ClickableStackTracesTest.java
index 92e1e85ca9..029ea2fa99 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java
index b0e31798e9..af422619d6 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 d9a74fff6e..3ede48b407 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 8e1bf06322..e920ad8f4e 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
@@ -96,7 +96,7 @@ public void shouldPrintVerificationInOrderErrorAndShowWantedAndActual() {
try {
inOrder.verify(one).simpleMethod(999);
fail();
- } catch (org.mockito.exceptions.verification.junit.ArgumentsAreDifferent e) {
+ } catch (org.mockito.exceptions.verification.opentest4j.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 43729f3107..729343471f 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.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 954b99f16c..8456c46c52 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
diff --git a/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java b/src/test/java/org/mockitousage/verification/VerificationUsingMatchersTest.java
index 027eb2cdbf..bfc2e2225f 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.junit.ArgumentsAreDifferent;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
| test | val | 2019-03-15T18:25:52 | "2019-03-15T19:15:17Z" | mockitoguy | train |
mockito/mockito/1668_1669 | mockito/mockito | mockito/mockito/1668 | mockito/mockito/1669 | [
"keyword_pr_to_issue",
"timestamp(timedelta=0.0, similarity=0.8940422539486178)"
] | a323b8132de6f6e1c29d738de245469f8ce009b0 | 2a95f86c49ac35e6364bdacae86e98e4a3c3aa07 | [] | [
"I think the JUnit dependency should be kept at 4.12, we should avoid depending on a beta version.",
"Shall we keep a lower target, to allow benefit for older platforms ?",
"ErrorProne must run on Java 8: https://errorprone.info/docs/installation\r\n\r\nEdit: Although we could bump the target compatibility, I would rather not deal with that.",
"The checker API requires 4.13 sadly. However, I will revert it to just run 4.13 for the tests on this project. 4.13 will be released next week.",
"OK that makes sense ;)",
"OK waiting for junit 4.13 then",
"I'm OK shipping with 4.13 beta because this new jar is completely decoupled from other jars. Hope that helps!"
] | "2019-03-18T15:13:04Z" | [
"enhancement",
"new feature"
] | Add subproject for errorprone Mockito plugins | We heavily rely on ErrorProne plugins to prohibit certain usage of Mockito. Examples include disallowing the usages of Mockito internals or extending interfaces annotated by `@NotExtensible`.
These plugins are beneficial to the Java community and we would like to open source them to the project. The extra subproject would contain several checkers (and tests) that implement several safeguards. Users can add the checkers to their project to their benefit.
For example for Gradle, the configuration would be as follows (using https://github.com/tbroyer/gradle-errorprone-plugin#custom-error-prone-checks):
```gradle
dependencies {
errorprone("org.mockito:mockito-errorprone:$mockitoVersion")
}
```
This would allow us to make issues like #1616 and #1613 compiler errors rather than runtime failures. | [
"gradle/dependencies.gradle",
"gradle/root/java-compatibility-check.gradle",
"settings.gradle"
] | [
"gradle/dependencies.gradle",
"gradle/root/java-compatibility-check.gradle",
"settings.gradle",
"subprojects/errorprone/errorprone.gradle",
"subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensible.java"
] | [
"subprojects/errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensibleTest.java"
] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index f164631907..ed5f763cbe 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -6,6 +6,7 @@ def versions = [:]
versions.bytebuddy = '1.9.7'
versions.junitJupiter = '5.1.1'
+versions.errorprone = '2.3.2'
libraries.junit4 = 'junit:junit:4.12'
libraries.junitJupiterApi = "org.junit.jupiter:junit-jupiter-api:${versions.junitJupiter}"
@@ -18,7 +19,8 @@ libraries.bytebuddy = "net.bytebuddy:byte-buddy:${versions.bytebuddy}"
libraries.bytebuddyagent = "net.bytebuddy:byte-buddy-agent:${versions.bytebuddy}"
libraries.bytebuddyandroid = "net.bytebuddy:byte-buddy-android:${versions.bytebuddy}"
-libraries.errorprone = 'com.google.errorprone:error_prone_core:2.3.2'
+libraries.errorprone = "com.google.errorprone:error_prone_core:${versions.errorprone}"
+libraries.errorproneTestApi = "com.google.errorprone:error_prone_test_helpers:${versions.errorprone}"
// objenesis 3.x with full Java 11 support requires Java 8, bump version when Java 7 support is dropped
libraries.objenesis = 'org.objenesis:objenesis:2.6'
diff --git a/gradle/root/java-compatibility-check.gradle b/gradle/root/java-compatibility-check.gradle
index c7ad1f602a..fb2a1ca002 100644
--- a/gradle/root/java-compatibility-check.gradle
+++ b/gradle/root/java-compatibility-check.gradle
@@ -2,10 +2,11 @@
//if we're skipping release, let's also skip checking compatibility (faster builds)
if (project.hasProperty('checkJavaCompatibility') && !System.getenv("SKIP_RELEASE")) {
allprojects { p ->
+ def isJava8 = p.name != 'junit-jupiter' && p.name != 'errorprone'
plugins.withId('java') {
p.apply plugin: 'ru.vyarus.animalsniffer'
p.dependencies {
- signature "org.codehaus.mojo.signature:java1${p.name != 'junit-jupiter' ? '6' : '8'}:1.0@signature"
+ signature "org.codehaus.mojo.signature:java1${isJava8 ? '6' : '8'}:1.0@signature"
}
}
}
diff --git a/settings.gradle b/settings.gradle
index 34ffa162a1..37f0a5d799 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -7,6 +7,7 @@ include 'android'
include 'junit-jupiter'
include 'junitJupiterExtensionTest'
include 'module-test'
+include 'errorprone'
rootProject.name = 'mockito'
diff --git a/subprojects/errorprone/errorprone.gradle b/subprojects/errorprone/errorprone.gradle
new file mode 100644
index 0000000000..5f97da1c22
--- /dev/null
+++ b/subprojects/errorprone/errorprone.gradle
@@ -0,0 +1,23 @@
+description = "ErrorProne plugins for Mockito"
+
+apply from: "$rootDir/gradle/java-library.gradle"
+apply from: "$rootDir/gradle/dependencies.gradle"
+
+dependencies {
+ compile project.rootProject
+ compile libraries.errorprone
+
+ testCompile 'junit:junit:4.13-beta-1'
+ testCompile libraries.errorproneTestApi
+}
+
+sourceCompatibility = 1.8
+targetCompatibility = 1.8
+
+test {
+ inputs.files(configurations.errorproneJavac).withNormalizer(ClasspathNormalizer)
+ jvmArgs += "-Xbootclasspath/p:${configurations.errorproneJavac.asPath}"
+
+ // ErrorProne can only run on JDK 8
+ it.enabled = !JavaVersion.current().isJava9Compatible()
+}
diff --git a/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensible.java b/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensible.java
new file mode 100644
index 0000000000..95f18dc296
--- /dev/null
+++ b/subprojects/errorprone/src/main/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensible.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.errorprone.bugpatterns;
+
+import static com.google.errorprone.matchers.Description.NO_MATCH;
+
+import com.google.errorprone.BugPattern;
+import com.google.errorprone.BugPattern.SeverityLevel;
+import com.google.errorprone.VisitorState;
+import com.google.errorprone.bugpatterns.BugChecker;
+import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
+import com.google.errorprone.matchers.Description;
+import com.google.errorprone.util.ASTHelpers;
+import com.sun.source.tree.ClassTree;
+
+/** Finds subclasses of @NotExtensible interfaces. */
+@BugPattern(
+ name = "MockitoNotExtensible",
+ summary = "Some types that are a part of Mockito public API are not intended to be extended.",
+ explanation =
+ "Some types that are a part of Mockito public API are not intended to be extended."
+ + " It's because Mockito team needs to be able to add new methods to some types"
+ + " without breaking compatibility contract. Any type that is not intended"
+ + " to be extended is annotated with @NotExtensible.",
+ severity = SeverityLevel.ERROR)
+public class MockitoNotExtensible extends BugChecker implements ClassTreeMatcher {
+
+ @Override
+ public Description matchClass(ClassTree tree, VisitorState state) {
+ if (tree.getImplementsClause().stream()
+ .anyMatch(
+ implementing ->
+ ASTHelpers.hasAnnotation(
+ ASTHelpers.getSymbol(implementing), "org.mockito.NotExtensible", state))) {
+ return describeMatch(tree);
+ }
+
+ return NO_MATCH;
+ }
+}
| diff --git a/subprojects/errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensibleTest.java b/subprojects/errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensibleTest.java
new file mode 100644
index 0000000000..4e0f3f7152
--- /dev/null
+++ b/subprojects/errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoNotExtensibleTest.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2017 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.errorprone.bugpatterns;
+
+import com.google.errorprone.CompilationTestHelper;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/** Verifies that there are no subclasses of {@link org.mockito.NotExtensible} Mockito types. */
+@RunWith(JUnit4.class)
+public class MockitoNotExtensibleTest {
+
+ private CompilationTestHelper compilationTestHelper;
+
+ @Before
+ public void setup() {
+ compilationTestHelper =
+ CompilationTestHelper.newInstance(MockitoNotExtensible.class, getClass());
+ }
+
+ @Test
+ public void notExtensibleSubclass_shouldWarn() {
+ compilationTestHelper
+ .addSourceLines(
+ "input.java",
+ "import org.mockito.invocation.InvocationOnMock;",
+ "// BUG: Diagnostic contains:",
+ "abstract class Invocation implements InvocationOnMock { }")
+ .doTest();
+ }
+
+ @Test
+ public void anonymousClassImplementingNotExtensible_shouldWarn() {
+ compilationTestHelper
+ .addSourceLines(
+ "input.java",
+ "import org.mockito.NotExtensible;",
+ "class Test {",
+ " public void test() {",
+ " // BUG: Diagnostic contains:",
+ " new Anonymous() { };",
+ " }",
+ " @NotExtensible",
+ " interface Anonymous {}",
+ "}")
+ .doTest();
+ }
+
+ @Test
+ public void anonymousClassImplementingOtherAnnotation_shouldNotWarn() {
+ compilationTestHelper
+ .addSourceLines(
+ "input.java",
+ "import org.mockito.NotExtensible;",
+ "class Test {",
+ " public void test() {",
+ " new Anonymous() { };",
+ " }",
+ " @OtherAnnotation",
+ " interface Anonymous {}",
+ " @interface OtherAnnotation {}",
+ "}")
+ .doTest();
+ }
+}
| test | val | 2019-03-15T18:25:52 | "2019-03-18T14:47:55Z" | TimvdLippe | train |
mockito/mockito/1606_1673 | mockito/mockito | mockito/mockito/1606 | mockito/mockito/1673 | [
"keyword_pr_to_issue"
] | d6098a6bbdfbafd966a2078627a90d9ffbedc7ea | 43f737632647ed429233f0d9a96742de765a4412 | [
"I am also getting the same error. Reverting back to `2.23.+` fixes the issue.",
"Seems like you are loading the wrong version of ByteBuddy. What version are\nyou using?\n\nOn Mon, 4 Feb 2019, 10:49 Taher, <notifications@github.com> wrote:\n\n> I am also getting the same error. Reverting back to 2.23.+ fixes the\n> issue.\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/mockito/mockito/issues/1606#issuecomment-460203942>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AFrDb00_6nD1ZzQkmmEe6lbYHNFnz_8Yks5vKBBTgaJpZM4ag8uJ>\n> .\n>\n",
"Hi Tim,\r\n\r\nThe ByteBuddy version I use is 1.9.3",
"That version is too low. Mockito depends on ByteBuddy 1.9.7: https://github.com/mockito/mockito/blob/aacacb156166b54b7eba3dfe03dd7bacda54c8d8/gradle/dependencies.gradle#L7 Also shown in the pom: http://central.maven.org/maven2/org/mockito/mockito-core/2.24.0/mockito-core-2.24.0.pom It seems like your project setup does not correctly resolve dependency mismatches.",
"Had the same issue even though we never set bytebuddy as dependency somewhere.\r\nSetting bytebuddy dependency explicitly at gradle fixed it for me.",
"Adding bytebuddy as a dependency did fix the problem. I would think Gradle manages this dependency himself.\r\n\r\nAnyway, thanks for the help! ",
"I had to add byte-buddy as well as an explicit dependency to our project. Is it valid behaviour to use byte-buddy during runtime, even though it's specified as just a compile-time dependency of mockito?",
"Same error with the same versions of mockito and byte-buddy, but adding it explicitly doesn't solve the issue. The only difference is that I use Maven instead of Gradle.",
"I would reopen this as an actual bug since 2.23.0 version doesn't have this issue and the lib should handle gracefully its own dependencies like this one.",
"Since quite some people have the same issue, i've reopened the issue.",
"Same issue here. Same goes for 2.25.0.\r\n\r\nReverting to 2.23.0 solves the problem.",
"Could anyone produce a repository that shows the issue?",
"I am preparing a repo that shows the issue (it may take a couple of days), but if both mockito and selenium are used in a single pom.xml, selenium 3.141.59's dependency on byte-buddy 1.8.15 causes that version of byte-buddy to be used instead of the version required by mockito.",
"I am not sure what we on the Mockito team can do about that. If Maven resolves to a dependency that does not satisfy the constraints we declare in our pom, that seems like an issue of Maven. We need at least ByteBuddy 1.9.7. If a different dependency requires a lower version, I think you need to resolve that in your `pom.xml` by explicitly declaring the version of ByteBuddy.\r\n\r\nPer https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope I am not sure what other scope is more appropriate over `compile`. We need ByteBuddy during compilation to define our MockMaker and therefore we also need to use it when running any test.",
"As explained in my issue #1671 we have the same problem (sorry for the duplicate, I hadn't seen this one).\r\nAfter investigation, it seems that we have 2 ByteBuddy.\r\nThe first one is from hibernate-core-5.4.1 and is released byte-buddy 1.9.5\r\nThe second one is from mockito-core-2.25.1 and is released byte-buddy 1.9.7\r\n\r\nFor some reasons, it's the byte-buddy 1.9.5 from hibernate dependency that is used by mockito.\r\n\r\nBy exluding byte-buddy from hibernate dependency, we can fix the problem, but I'm not sure that we will not have any side effect on hibernate :-/\r\n\r\n```\r\n<dependency>\r\n\t<groupId>org.hibernate</groupId>\r\n\t<artifactId>hibernate-core</artifactId>\r\n\t<version>5.4.1</version>\r\n\t<exclusions>\r\n\t\t<exclusion>\r\n\t\t\t<artifactId>byte-buddy</artifactId>\r\n\t\t\t<groupId>net.bytebuddy</groupId>\r\n\t\t</exclusion>\r\n\t</exclusions>\r\n</dependency>\r\n```\r\n\r\n",
"Good catch, @marcam. If you go to https://mvnrepository.com/artifact/org.hibernate/hibernate-core/5.4.1.Final you can check that Hibernate will work well with any version until 1.9.10 (see update column in the dependencies table). So you can safely add the exclusion or include a new dependency in Maven to make clear what version you really want to use (my approach)",
"Thank you @borjapenman \r\nHibernate 5.4.2 is just released this morning with bytebuddy 1.9.10 and solves the problem without doing any exeption :-)\r\nmockito uses now the 1.9.10 instead of 1.9.7\r\n\r\n![image](https://user-images.githubusercontent.com/854436/54822157-a77f5c00-4ca4-11e9-82f1-b3d000b75541.png)\r\n",
"@TimvdLippe, @raphw, shall we bump bytebuddy in Mockito? I'm curious: if it is a good time to start shadowing bytebuddy just like had in the past with cglib. This ticket is an evidence of the impact to our users when bytebuddy versions don't agree.",
"I dont bumping the version is going to help. The dependency mechanisms in Maven and Gradle are fundamentally working against us.\r\n\r\nI think shadowing is a good alternative. We should carefully evaluate the downsides, but to me it seems like the best option we have available.",
"I don't think shadowing is a good alternative as this forces Mockito updates when updating to a new Java version rather the polling the newest Byte Buddy. \r\n\r\nThose resolution breakages are unfortunate but should be rare as we do not often require new APIs in Mockito. ",
"I also don't like the idea with shadowing, especially as bute-buddy is (usually ;) ) backward compatible withing sane versioning scheme.\r\nGradle should use the higher version by default. Maven seems to use a different approach.\r\n\r\nRegarding dependency bumping, @mockitoguy could you please consider adding a Dependabot app from the GitHub [marketplace](https://github.com/marketplace/dependabot/) (just for the mockito repository) to do it for us automatically (via PRs)? See the sample generated [PRs](https://github.com/szpak/mockito/pulls) in my fork. The configuration itself was merged in #1600.",
"OK, thank you for consideration! Let's avoid shadowing.\r\n\r\n@szpak, I'll check dependabot!",
"Based on the Twitter discussion we had with Maven + Gradle, I will perform an investigation in all possible options. Hopefully I can finish that next week, but not sure when.\r\n\r\nThe TLDR is that the \"closest wins\" mechanism by Maven results in the usage of a version of ByteBuddy that is too old. We can specify our ByteBuddy version differently with `[1.2.3,)`, but I am not sure if that has unexpected side-effects. That's what I want to investigate.",
"> Based on the Twitter discussion we had with Maven + Gradle, I will perform an investigation in all possible options\r\n\r\nIf Hibernate wants 1.9.10 and mockito-core wants 1.9.7, and those versions are not compatible, then I'm not sure what you want the build system to do. It won't be resolved automatically. Our options:\r\n\r\n a) shadowing\r\n b) mockito-core bumps to 1.9.10\r\n c) hibernate downgrades to 1.9.7\r\n d) we tell customers to downgrade/force to 1.9.7 and _hope_ that hibernate will work\r\n\r\nSome of those options are clearly not viable.",
"Opened https://github.com/mockito/mockito/pull/1673",
"> If Hibernate wants 1.9.10 and mockito-core wants 1.9.7, and those versions are not compatible, then I'm not sure what you want the build system to do. It won't be resolved automatically.\r\n\r\nBut the versions are compatible. We can simple use 1.9.10 and make them both work. That's because ByteBuddy follows semver (afaik).",
"Yes, Byte Buddy follows semver. I had some hickups in the past, but given the libraries spread, I think the amount of incidents was minimal.\r\n\r\nThe reason I dislike the shadowing approach is that this would mean that any library should shadow all dependencies to avoid any possible conflict. This is a problem that should be solved in dependency resolution.",
"I keep getting the same error i.e \r\n\"Mockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\"\r\n\r\nI have updated my gradle dependencies to match :\r\n\r\nhttps://mvnrepository.com/artifact/org.mockito/mockito-core/2.25.0\r\n\r\nmockito : \"2.25.0\"\r\nmockito-core : \"2.25.0\"\r\n\r\nI dont need bytebuddy dependency but added it to override any old dependencies\r\nbyte-buddy : 1.9.11\r\nbyte-buddy-agent : 1.9.11\r\n\r\nCan someone suggest , what am I doing wrong ?",
"> But the versions are compatible\r\n\r\nOh, then I misread this ticket. So I don't know what the problem is :)",
"We are getting this when attempting to upgrade Spring Boot 2.0.x to 2.1.x.\r\n\r\nspring-boot-dependencies specifies the version for ByteBuddy and Mockito:\r\n\r\nSpring Boot 2.0:\r\n```xml\r\n<byte-buddy.version>1.7.11</byte-buddy.version>\r\n<mockito.version>2.15.0</mockito.version>\r\n```\r\n\r\nSpring Boot 2.1:\r\n```xml\r\n<byte-buddy.version>1.9.10</byte-buddy.version>\r\n<mockito.version>2.23.4</mockito.version>\r\n```\r\n\r\nWe are using ``spy`` on a real class and it is fully public and non-final.\r\n\r\nAny version of Mockito newer than 2.15.0 seems to cause this. 2.16.0 uses byte-buddy 1.9.10. Any idea on what I can look for?",
"@efenderbosch Are you sure ByteBuddy is not loaded transitively through a different dependency?",
"Yes, running ``mvn dependency:tree`` only shows 1.7.11 or 1.9.10 and only through Mockito.\r\n\r\nWe are still running Java 8, if that matters. Need Pact to update (4.x is currently in beta) so we can upgrade to 11. Was there a change in Mockito 2.16+ or ByteBuddy 1.8+ that doesn't work w/ Java 8?",
"> 1.7.11\r\n\r\nThat version is too low and probably leads to the tests loading the wrong version of ByteBuddy. Could you specify ByteBuddy as a dependency in your root pom to use the correct version?\r\n\r\n> Was there a change in Mockito 2.16+ or ByteBuddy 1.8+ that doesn't work w/ Java 8?\r\n\r\nNo, Mockito should work just fine on Java 8",
"ByteBuddy 1.7.11 and Mockito 2.15.0 *work*, though. Anything after that uses ByteBuddy 1.9.10+ and fails.\r\n\r\nedit:\r\nok specified\r\n```xml\r\n<mockito.version>2.15.0</mockito.version>\r\n<byte-buddy.version>1.7.11</byte-buddy.version>\r\n```\r\nin our parent pom and it still fails. I'm very confused now.\r\n\r\n``mvn dependency:tree`` shows this:\r\n\r\n```\r\n[INFO] | +- org.mockito:mockito-core:jar:2.15.0:test\r\n[INFO] | | +- net.bytebuddy:byte-buddy:jar:1.7.11:provided\r\n[INFO] | | \\- net.bytebuddy:byte-buddy-agent:jar:1.7.11:test\r\n```\r\n\r\nwith no other versions of Mockito or ByteBuddy. ",
"Ok, I think I figured it out. The problem seems to be ``default`` methods on interfaces.\r\n\r\nThe class I'm spying implements ``com.github.benmanes.caffeine.cache.CacheLoader``\r\n\r\nIf my concrete class overrides the ``default`` methods, then my test runs successfully.",
"@efenderbosch Please open a new issue (or PR if you can :smile: ) to triage your problem there.",
"@efenderbosch This was strange. Can you create a small reproduction of the issue?",
"I tried w/ a clean project and can't reproduce it. Gave up on Spring Boot 2.1 for now. Tried 2.0.9 (from 2.0.8) and got the same issue. So I'm pretty stumped as to what is going on. At this point, we are fine w/ just overriding default methods on the couple classes that we need to mock/spy.",
"My colleague run into the same issue after recent upgrade to\r\n'mockito-core', version: '2.25.0'\r\n'powermock-api-mockito2', version: '2.0.0'\r\n'powermock-module-junit4', version: '2.0.0'. \r\n\r\nDowngrading mockito-core to 2.23.0 helped to solve it. Strangely, it happens only running tests individually from IDEA, but they work fine running via Gradle script. Also, I was not able to reproduce it on my machine, though we have very similar environment setups.\r\n\r\nError message:\r\n\r\norg.mockito.exceptions.base.MockitoException:\r\nMockito cannot mock this class: class com.fasterxml.jackson.databind.ObjectMapper.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\nJava : 1.8\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 25.191-b12\r\nJVM name : Java HotSpot(TM) 64-Bit Server VM\r\nJVM version : 1.8.0_191-b12\r\nJVM info : mixed mode\r\nOS name : Windows 10\r\nOS version : 10.0\r\n\r\nUnderlying exception : java.lang.IllegalArgumentException: Could not create type",
"Hi I have the same problem. I am migrating from java 8 to java 11. I have updated Mockito to 2.23.0 \r\n\r\n`[INFO] +- org.mockito:mockito-core:jar:2.23.0:compile`\r\n\r\nI have also included byte-buddy as a dependency \r\n```\r\n[INFO] +- net.bytebuddy:byte-buddy:jar:1.9.7:compile\r\n[INFO] +- net.bytebuddy:byte-buddy-agent:jar:1.9.7:compile\r\n\r\n```\r\nI have checked that byte-buddy is not loaded transitively through a different dependency. I can't understand what the issue is.",
"Do you have a stack trace? There can be other errors causing this message.",
"@raphw The stack trace is almost the same as others. Here you go\r\n```\r\norg.mockito.exceptions.base.MockitoException: \r\n\r\nMockito cannot mock this class: class javax.ws.rs.core.Response.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 11\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 11.0.2+9-LTS\r\nJVM name : Java HotSpot(TM) 64-Bit Server VM\r\nJVM version : 11.0.2+9-LTS\r\nJVM info : mixed mode\r\nOS name : Linux\r\nOS version : 4.9.125-linuxkit\r\n\r\nUnderlying exception : java.lang.IllegalStateException: Error invoking java.lang.reflect.Method#getAnnotatedReturnType\r\n```",
"@MoodyMudit It's unlikely that is the full stacktrace. Could you post the full stacktrace please?",
"It still shows the error with *Error invoking java.lang.reflect.Method#getAnnotatedReturnType*. Seems like a problem with your mocked class.",
"@TimvdLippe @raphw I was able to solve this issue. I noticed that java 11 does not contain the JAXB APIs. So I included them as dependencies in pom.\r\n\r\n```\r\n<dependency>\r\n <groupId>javax.xml.bind</groupId>\r\n <artifactId>jaxb-api</artifactId>\r\n <version>2.2.11</version>\r\n</dependency>\r\n<dependency>\r\n <groupId>com.sun.xml.bind</groupId>\r\n <artifactId>jaxb-core</artifactId>\r\n <version>2.2.11</version>\r\n</dependency>\r\n<dependency>\r\n <groupId>com.sun.xml.bind</groupId>\r\n <artifactId>jaxb-impl</artifactId>\r\n <version>2.2.11</version>\r\n</dependency>\r\n<dependency>\r\n <groupId>javax.activation</groupId>\r\n <artifactId>activation</artifactId>\r\n <version>1.1.1</version>\r\n</dependency>\r\n```\r\nThanks for your help.",
"> 嗨,\r\n> \r\n> 从版本2.24.0开始,我收到错误“Mockito只能模拟非私有和非最终类。”。回到Mockito 2.23.4解决了这个问题。\r\n> \r\n> **堆栈跟踪**\r\n> `Underlying exception : java.lang.IllegalArgumentException: Could not create type at nl.tkp.ddw.pensioenaangifte.test.model.unittesten.AanleveringFilteringStepDefinitions.setup(AanleveringFilteringStepDefinitions.java:43) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at cucumber.runtime.Utils$1.call(Utils.java:26) at cucumber.runtime.Timeout.timeout(Timeout.java:16) at cucumber.runtime.Utils.invoke(Utils.java:20) at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60) at cucumber.runner.HookDefinitionMatch.runStep(HookDefinitionMatch.java:16) at cucumber.runner.TestStep.executeStep(TestStep.java:63) at cucumber.runner.TestStep.run(TestStep.java:49) at cucumber.runner.TestCase.run(TestCase.java:40) at cucumber.runner.Runner.runPickle(Runner.java:40) at cucumber.runtime.junit.PickleRunners$NoStepDescriptions.run(PickleRunners.java:146) at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:68) at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:23) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:73) at cucumber.api.junit.Cucumber.runChild(Cucumber.java:124) at cucumber.api.junit.Cucumber.runChild(Cucumber.java:65) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at cucumber.api.junit.Cucumber$1.evaluate(Cucumber.java:133) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38) at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157) at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.IllegalArgumentException: Could not create type at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154) at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365) at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174) at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376) at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32) at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71) at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42) at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25) at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35) at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62) at org.mockito.Mockito.mock(Mockito.java:1896) at org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44) at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19) at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16) at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38) at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62) at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49) at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41) at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69) ... 63 more Caused by: java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.MultipleParentClassLoader$Builder.appendMostSpecific(Ljava/util/Collection;)Lnet/bytebuddy/dynamic/loading/MultipleParentClassLoader$Builder; at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:83) at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37) at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34) at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152) ... 81 more`\r\n> \r\n> **Versioninfo**\r\n> Java:1.8 \r\n> JVM供应商名称:Oracle Corporation \r\n> JVM供应商版本:25.191-b12 \r\n> JVM名称:Java HotSpot(TM)64位服务器VM \r\n> JVM版本:1.8.0_191-b12 \r\n> JVM信息:混合模式\r\n> 操作系统名称:Mac OS X \r\n> OS版本:10.13.6 \r\n> Mockito-core:2.24.0\r\n\r\n我也遇到了 快点修复",
"I have the same problem with 2.27.0, reverting back to 2.23.4 works.\r\n\r\n> Interface that Mockito is unable to mock\r\n\r\n```java\r\n\r\nimport java.util.Set;\r\n\r\nimport br.com.senior.platform.authorization.UserNotificationPriority;\r\nimport br.com.senior.platform.authorization.model.ResourceIntegration;\r\n\r\npublic interface NotifyResourceIntegration {\r\n\r\n boolean notifyOnError(Set<ResourceIntegration> allResources, Throwable ex, String tenant);\r\n\r\n void notifyUser(UserNotificationPriority priority, String content, String tenant);\r\n}\r\n```\r\n\r\n> Full stack trace\r\n\r\n\r\n```\r\norg.mockito.exceptions.base.MockitoException: \r\nMockito cannot mock this class: interface br.com.senior.platform.authorization.service.notification.NotifyResourceIntegration.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 11\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 11.0.2+9\r\nJVM name : OpenJDK 64-Bit Server VM\r\nJVM version : 11.0.2+9\r\nJVM info : mixed mode\r\nOS name : Windows 10\r\nOS version : 10.0\r\n\r\n\r\nUnderlying exception : java.lang.IllegalArgumentException: Could not create type\r\n\r\n\tat br.com.senior.platform.authorization.service.notification.NotifyServiceImplTest.setUp(NotifyServiceImplTest.java:38)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\r\n\tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n\tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\r\n\tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)\r\n\tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)\r\n\tat com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)\r\nCaused by: java.lang.IllegalArgumentException: Could not create type\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n\tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n\tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n\tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:62)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1907)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)\r\n\tat org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)\r\n\tat org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)\r\n\tat org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49)\r\n\tat org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)\r\n\tat org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)\r\n\t... 23 more\r\nCaused by: java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.MultipleParentClassLoader$Builder.appendMostSpecific(Ljava/util/Collection;)Lnet/bytebuddy/dynamic/loading/MultipleParentClassLoader$Builder;\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:83)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n\t... 41 more\r\n\r\n```",
"@luankevinferreira You are loading a too-old version of ByteBuddy. Check the version you are using and upgrade it to the one compatible with the version specified in the Mockito pom.",
"> My colleague run into the same issue after recent upgrade to\r\n> 'mockito-core', version: '2.25.0'\r\n> 'powermock-api-mockito2', version: '2.0.0'\r\n> 'powermock-module-junit4', version: '2.0.0'.\r\n> \r\n> Downgrading mockito-core to 2.23.0 helped to solve it. Strangely, it happens only running tests individually from IDEA, but they work fine running via Gradle script. Also, I was not able to reproduce it on my machine, though we have very similar environment setups.\r\n> \r\n> Error message:\r\n> \r\n> org.mockito.exceptions.base.MockitoException:\r\n> Mockito cannot mock this class: class com.fasterxml.jackson.databind.ObjectMapper.\r\n> \r\n> Mockito can only mock non-private & non-final classes.\r\n> If you're not sure why you're getting this error, please report to the mailing list.\r\n> \r\n> Java : 1.8\r\n> JVM vendor name : Oracle Corporation\r\n> JVM vendor version : 25.191-b12\r\n> JVM name : Java HotSpot(TM) 64-Bit Server VM\r\n> JVM version : 1.8.0_191-b12\r\n> JVM info : mixed mode\r\n> OS name : Windows 10\r\n> OS version : 10.0\r\n> \r\n> Underlying exception : java.lang.IllegalArgumentException: Could not create type\r\n\r\nI actually encountered this same issue today. What caused the problem for me was a dependency combination misconfiguration: I have a config \"compile\" that takes Hibernate-osgi 2.5.17Final, which depends on byte-buddy 1.6.14. I have a config \"test\" that takes mockito 2.27.0, which depends on byte-buddy 1.9.10. When running my unittests from my IDE, it properly combined those dependencies including version management, but when I ran it from an Ant script, I had to manually merge these 2 configurations into a class Path. I put the compile config first, which meant the Byte-Buddy of Hibernate was used by Mockito instead of the one Mockito had to use. We considered putting the test config first, but that would actually mean we would test with a different version of ByteBuddy than we use in the main configuration.\r\n\r\nupgrading Hibernate would currently be too involved, but we are planning to do so later for Java 11 support. For now, we're downgrading Mockito.",
"\r\nI am getting the below error when using Mockito. Is it related to this issue?\r\n\r\n```\r\nCaused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/adapters/XmlAdapter\r\n [junit] \tat java.base/java.lang.Class.getDeclaringClass0(Native Method)\r\n [junit] \tat java.base/java.lang.Class.getEnclosingClass(Class.java:1518)\r\n [junit] \tat java.base/java.lang.reflect.Executable.getAnnotatedReturnType0(Executable.java:642)\r\n [junit] \tat java.base/java.lang.reflect.Method.getAnnotatedReturnType(Method.java:721)\r\n [junit] \tat java.base/jdk.internal.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)\r\n [junit] \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n [junit] \tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedReturnType.resolve(TypeDescription.java:2928)\r\n```",
"@karthickpdy Unrelated. Is javax.xml.bind on the classpath? If you're on jdk >= 11 JAXB is removed from the JDK.",
"Seems like an annotation is loaded during instrumentation that is indeed missing on the class path.\r\n\r\nIf you just try to load this class where the mock is created, is the same exception thrown?",
"Seeing following with 2.23.0 / OpenJDK Runtime Environment 18.9 (build 11.0.2+9), works fine with Java 8.\r\norg.mockito:mockito-core:2.23.0\r\n net.bytebuddy:byte-buddy:1.9.0\r\n net.bytebuddy:byte-buddy-agent:1.9.0\r\n org.objenesis:objenesis:2.6\r\n\r\n> \r\n\r\n> org.mockito.exceptions.base.MockitoException: \r\n> Mockito cannot mock this class: class javax.ws.rs.core.Response.\r\n> \r\n> Mockito can only mock non-private & non-final classes.\r\n> If you're not sure why you're getting this error, please report to the mailing list.\r\n> \r\n> \r\n> Java : 11\r\n> JVM vendor name : Oracle Corporation\r\n> JVM vendor version : 11.0.2+9\r\n> JVM name : OpenJDK 64-Bit Server VM\r\n> JVM version : 11.0.2+9\r\n> JVM info : mixed mode\r\n> OS name : Windows 10\r\n> OS version : 10.0\r\n> \r\n> \r\n> Underlying exception : java.lang.IllegalStateException: Error invoking java.lang.reflect.Method#getAnnotatedReturnType\r\n> \tat com.MyTest.setup(MyTest.java:72)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n> \tat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\r\n> \tat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\n> \tat org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)\r\n> \tat org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)\r\n> \tat org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)\r\n> \tat org.junit.rules.RunRules.evaluate(RunRules.java:20)\r\n> \tat org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)\r\n> \tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\n> \tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\n> \tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\n> \tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\n> \tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\n> \tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\n> \tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\n> \tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\n> \tat org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)\r\n> \tat org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)\r\n> \tat org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)\r\n> \tat org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)\r\n> \tat org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n> \tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)\r\n> \tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\r\n> \tat org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)\r\n> \tat org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)\r\n> \tat com.sun.proxy.$Proxy2.processTestClass(Unknown Source)\r\n> \tat org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n> \tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n> \tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)\r\n> \tat org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)\r\n> \tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175)\r\n> \tat org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157)\r\n> \tat org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)\r\n> \tat org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)\r\n> \tat org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)\r\n> \tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\r\n> \tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\r\n> \tat org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)\r\n> \tat java.base/java.lang.Thread.run(Thread.java:834)\r\n> Caused by: java.lang.IllegalStateException: Error invoking java.lang.reflect.Method#getAnnotatedReturnType\r\n> \tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedReturnType.resolve(TypeDescription.java:2932)\r\n> \tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3186)\r\n> \tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:3872)\r\n> \tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.apply(AnnotationAppender.java:669)\r\n> \tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onNonGenericType(AnnotationAppender.java:650)\r\n> \tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onNonGenericType(AnnotationAppender.java:353)\r\n> \tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.accept(TypeDescription.java:3662)\r\n> \tat net.bytebuddy.implementation.attribute.MethodAttributeAppender$ForInstrumentedMethod.apply(MethodAttributeAppender.java:181)\r\n> \tat net.bytebuddy.implementation.attribute.MethodAttributeAppender$Compound.apply(MethodAttributeAppender.java:449)\r\n> \tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyAttributes(TypeWriter.java:691)\r\n> \tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:681)\r\n> \tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:590)\r\n> \tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:5114)\r\n> \tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1915)\r\n> \tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:197)\r\n> \tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:174)\r\n> \tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3376)\r\n> \tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3565)\r\n> \tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:128)\r\n> \tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n> \tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n> \tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)\r\n> \tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:350)\r\n> \tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)\r\n> \tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:361)\r\n> \tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n> \tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n> \tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n> \tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n> \tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n> \tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)\r\n> \tat org.mockito.Mockito.mock(Mockito.java:1895)\r\n> \tat org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:41)\r\n> \tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)\r\n> \tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)\r\n> \tat org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)\r\n> \tat org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)\r\n> \tat org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)\r\n> \tat org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)\r\n> \tat org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)\r\n> \t... 50 more\r\n> Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/adapters/XmlAdapter\r\n> \tat java.base/java.lang.Class.getDeclaringClass0(Native Method)\r\n> \tat java.base/java.lang.Class.getEnclosingClass(Class.java:1518)\r\n> \tat java.base/sun.reflect.annotation.AnnotatedTypeFactory.nestingForType(AnnotatedTypeFactory.java:96)\r\n> \tat java.base/sun.reflect.annotation.TypeAnnotationParser.buildAnnotatedType(TypeAnnotationParser.java:79)\r\n> \tat java.base/java.lang.reflect.Executable.getAnnotatedReturnType0(Executable.java:642)\r\n> \tat java.base/java.lang.reflect.Method.getAnnotatedReturnType(Method.java:721)\r\n> \tat java.base/jdk.internal.reflect.GeneratedMethodAccessor23.invoke(Unknown Source)\r\n> \tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n> \tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n> \tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedReturnType.resolve(TypeDescription.java:2928)\r\n> \t... 89 more\r\n> `",
"> As explained in my issue #1671 we have the same problem (sorry for the duplicate, I hadn't seen this one).\r\n> After investigation, it seems that we have 2 ByteBuddy.\r\n> The first one is from hibernate-core-5.4.1 and is released byte-buddy 1.9.5\r\n> The second one is from mockito-core-2.25.1 and is released byte-buddy 1.9.7\r\n> \r\n> For some reasons, it's the byte-buddy 1.9.5 from hibernate dependency that is used by mockito.\r\n> \r\n> By exluding byte-buddy from hibernate dependency, we can fix the problem, but I'm not sure that we will not have any side effect on hibernate :-/\r\n> \r\n> ```\r\n> <dependency>\r\n> \t<groupId>org.hibernate</groupId>\r\n> \t<artifactId>hibernate-core</artifactId>\r\n> \t<version>5.4.1</version>\r\n> \t<exclusions>\r\n> \t\t<exclusion>\r\n> \t\t\t<artifactId>byte-buddy</artifactId>\r\n> \t\t\t<groupId>net.bytebuddy</groupId>\r\n> \t\t</exclusion>\r\n> \t</exclusions>\r\n> </dependency>\r\n> ```\r\n\r\nThis worked for me. I added `byte-buddy` and `byte-buddy-agent` dependencies to my pom file in the version **1.9.7**.\r\n\r\nIt was like the following:\r\n\r\n```\r\n <dependency>\r\n\t\t\t<groupId>net.bytebuddy</groupId>\r\n\t\t\t<artifactId>byte-buddy</artifactId>\r\n\t\t\t<version>1.9.7</version>\r\n\t\t\t<scope>test</scope>\r\n\t\t</dependency>\r\n\t\t<dependency>\r\n\t\t\t<groupId>net.bytebuddy</groupId>\r\n\t\t\t<artifactId>byte-buddy-agent</artifactId>\r\n\t\t\t<version>1.9.7</version>\r\n\t\t\t<scope>test</scope>\r\n\t\t</dependency>\r\n```\r\n\r\nAlso, I excluded those dependencies in `hibernate-core` and `hibernate-entitymanager` because those dependencies contains the `byte-buddy` and `byte-buddy-agent` in a prior version.",
"In **Eclipse** make sure to add as external library byte buddy. Ctrl + right click on project > Java Build Path > Libraries > Add external JARS > byte-buddy-1.**.*.jar\r\nThis worked for me if you want to debug your Junit tests in Eclipse",
"I am still getting this issue with Mockito `3.0.0` (and `mockito-android`) when running Android instrumentation tests:\r\n\r\n```\r\norg.mockito.exceptions.base.MockitoException:\r\nMockito cannot mock this class: class com.(...)._MyClass_.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\nIMPORTANT INFORMATION FOR ANDROID USERS:\r\n\r\nThe regular Byte Buddy mock makers cannot generate code on an Android VM!\r\nTo resolve this, please use the 'mockito-android' dependency for your application:\r\nhttp://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22\r\n\r\nJava : 0.9\r\nJVM vendor name : The Android Project\r\nJVM vendor version : 2.1.0\r\nJVM name : Dalvik\r\nJVM version : 0.9\r\nJVM info : null\r\nOS name : Linux\r\nOS version : 3.18.71-g7dfaee7f928\r\n\r\n\r\nUnderlying exception : java.lang.IllegalArgumentException: Could not create type\r\nat _com.(...).MyTest_.setUp(MyTest.java:44)\r\nat java.lang.reflect.Method.invoke(Native Method)\r\nat org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\r\n(...)\r\nat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\nat androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)\r\nat androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)\r\nat android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)\r\nCaused by: java.lang.IllegalArgumentException: Could not create type\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)\r\nat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\nat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\nat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\nat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\nat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\nat org.mockito.android.internal.creation.AndroidByteBuddyMockMaker.createMock(AndroidByteBuddyMockMaker.java:39)\r\nat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\nat org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)\r\nat org.mockito.Mockito.mock(Mockito.java:1908)\r\nat org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)\r\nat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)\r\nat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)\r\nat org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)\r\nat org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)\r\nat org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49)\r\nat org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)\r\nat org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)\r\n... 30 more\r\nCaused by: java.lang.NoSuchFieldError: No instance field targetApiLevel of type I in class Lcom/android/dx/dex/DexOptions; or its superclasses (declaration of 'com.android.dx.dex.DexOptions' appears in /data/app/com.teamwork.projects.data.test-WeFv56g4F9J4rFDV8asMpg==/base.apk)\r\nat net.bytebuddy.android.AndroidClassLoadingStrategy$DexProcessor$ForSdkCompiler.makeDefault(AndroidClassLoadingStrategy.java:216)\r\nat net.bytebuddy.android.AndroidClassLoadingStrategy$Injecting.<init>(AndroidClassLoadingStrategy.java:387)\r\nat org.mockito.android.internal.creation.AndroidLoadingStrategy.resolveStrategy(AndroidLoadingStrategy.java:39)\r\nat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:173)\r\nat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\nat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n... 48 more\r\n```",
"What dex compiler did you bundle with Android here? Seems like the API is not compatible.",
"I'm using Studio 3.5 and Gradle build tools 3.5.0, so it's using D8 by default I guess.",
"Getting this on `mockito-android:3.1.0` (instrumented tests) especially on `release` build, on `debug` it works fine.\r\n```\r\n classpath 'com.android.tools.build:gradle:3.5.0'\r\n\r\nandroid {\r\n buildTypes {\r\n buildToolsVersion \"28.0.3\"\r\n release {\r\n minifyEnabled false\r\n``` ",
"I'm seeing a similar error running Mockito 3.10.0 or 2.23.4, it doesn't make a difference. I've tried running on an Android 10 phone, as well as on a emulator sdk 27\r\n\r\n```\r\norg.mockito.exceptions.base.MockitoException:\r\nMockito cannot mock this class: class android.content.Context.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\n\r\nIMPORTANT INFORMATION FOR ANDROID USERS:\r\n\r\nThe regular Byte Buddy mock makers cannot generate code on an Android VM!\r\nTo resolve this, please use the 'mockito-android' dependency for your application:\r\nhttp://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22\r\n\r\nJava : 0.9\r\nJVM vendor name : The Android Project\r\nJVM vendor version : 2.1.0\r\nJVM name : Dalvik\r\nJVM version : 0.9\r\nJVM info : null\r\nOS name : Linux\r\nOS version : 3.18.91+\r\n\r\n\r\nUnderlying exception : java.lang.IllegalArgumentException: Could not create type\r\nat com.mycomp.android.sdk.core.driver.ble.nordic.MyTest.<init>(MyTest.kt:301)\r\nat java.lang.reflect.Constructor.newInstance0(Native Method)\r\nat java.lang.reflect.Constructor.newInstance(Constructor.java:334)\r\nat org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)\r\nat org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)\r\nat org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\r\nat org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)\r\nat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\nat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\nat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\nat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\nat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\nat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\nat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\nat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\nat androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)\r\nat org.junit.runners.Suite.runChild(Suite.java:128)\r\nat org.junit.runners.Suite.runChild(Suite.java:27)\r\nat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\nat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\nat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\nat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\nat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\nat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\nat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\nat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\nat androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)\r\nat androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:388)\r\nat android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2075)\r\nCaused by: java.lang.IllegalArgumentException: Could not create type\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)\r\nat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\nat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\nat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\nat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\nat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\nat org.mockito.android.internal.creation.AndroidByteBuddyMockMaker.createMock(AndroidByteBuddyMockMaker.java:39)\r\nat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\nat org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)\r\nat org.mockito.Mockito.mock(Mockito.java:1908)\r\n... 29 more\r\nCaused by: java.lang.NoSuchFieldError: No instance field targetApiLevel of type I in class Lcom/android/dx/dex/DexOptions; or its superclasses (declaration of 'com.android.dx.dex.DexOptions' appears in /data/app/com.mycomp.android.sdk.test-akjnnaFvI2s0R5IuilGDvg==/base.apk)\r\nat net.bytebuddy.android.AndroidClassLoadingStrategy$DexProcessor$ForSdkCompiler.makeDefault(AndroidClassLoadingStrategy.java:216)\r\nat net.bytebuddy.android.AndroidClassLoadingStrategy$Injecting.<init>(AndroidClassLoadingStrategy.java:387)\r\nat org.mockito.android.internal.creation.AndroidLoadingStrategy.resolveStrategy(AndroidLoadingStrategy.java:39)\r\nat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:173)\r\nat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\nat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\nat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n... 39 more\r\n```\r\n\r\nTo provide more context, this happens after adding MockK Android (https://mockk.io/ANDROID.html). The only suspicious dependency I see is `dexmaker:2.21.0`. I've forced it to use dexmaker:2.25.0, which upgrades to mockito 2.25.0, but still no luck\r\n\r\n",
"Android has been changing its APIs in a non-compatible manner again, this causes these problems. I would have to look into supporting newer API versions in the DEX compiler. If you are also using MOCKK, I assume that the problem is the dexmaker version, you are very likely on the right track.",
"if anyone is still getting the error in spring-boot project, it could be because spring provides its version of byte-buddy. \r\nadding `<byte-buddy.version>1.9.7</byte-buddy.version>` will tell maven to use the newer version.",
"> I am still getting this issue with Mockito `3.0.0` (and `mockito-android`) when running Android instrumentation tests:\r\n> \r\n> ```\r\n> org.mockito.exceptions.base.MockitoException:\r\n> Mockito cannot mock this class: class com.(...)._MyClass_.\r\n> \r\n> Mockito can only mock non-private & non-final classes.\r\n> If you're not sure why you're getting this error, please report to the mailing list.\r\n> \r\n> IMPORTANT INFORMATION FOR ANDROID USERS:\r\n> \r\n> The regular Byte Buddy mock makers cannot generate code on an Android VM!\r\n> To resolve this, please use the 'mockito-android' dependency for your application:\r\n> http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22mockito-android%22%20g%3A%22org.mockito%22\r\n> \r\n> Java : 0.9\r\n> JVM vendor name : The Android Project\r\n> JVM vendor version : 2.1.0\r\n> JVM name : Dalvik\r\n> JVM version : 0.9\r\n> JVM info : null\r\n> OS name : Linux\r\n> OS version : 3.18.71-g7dfaee7f928\r\n> \r\n> \r\n> Underlying exception : java.lang.IllegalArgumentException: Could not create type\r\n> at _com.(...).MyTest_.setUp(MyTest.java:44)\r\n> at java.lang.reflect.Method.invoke(Native Method)\r\n> at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)\r\n> (...)\r\n> at org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n> at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)\r\n> at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)\r\n> at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2074)\r\n> Caused by: java.lang.IllegalArgumentException: Could not create type\r\n> at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)\r\n> at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\n> at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\n> at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\n> at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n> at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n> at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n> at org.mockito.android.internal.creation.AndroidByteBuddyMockMaker.createMock(AndroidByteBuddyMockMaker.java:39)\r\n> at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n> at org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)\r\n> at org.mockito.Mockito.mock(Mockito.java:1908)\r\n> at org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)\r\n> at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)\r\n> at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)\r\n> at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)\r\n> at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)\r\n> at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49)\r\n> at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)\r\n> at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)\r\n> ... 30 more\r\n> Caused by: java.lang.NoSuchFieldError: No instance field targetApiLevel of type I in class Lcom/android/dx/dex/DexOptions; or its superclasses (declaration of 'com.android.dx.dex.DexOptions' appears in /data/app/com.teamwork.projects.data.test-WeFv56g4F9J4rFDV8asMpg==/base.apk)\r\n> at net.bytebuddy.android.AndroidClassLoadingStrategy$DexProcessor$ForSdkCompiler.makeDefault(AndroidClassLoadingStrategy.java:216)\r\n> at net.bytebuddy.android.AndroidClassLoadingStrategy$Injecting.<init>(AndroidClassLoadingStrategy.java:387)\r\n> at org.mockito.android.internal.creation.AndroidLoadingStrategy.resolveStrategy(AndroidLoadingStrategy.java:39)\r\n> at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:173)\r\n> at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n> at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n> at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n> ... 48 more\r\n> ```\r\n\r\nGetting same exception for Unit test cases.\r\nMockito - 3.1.0\r\nPowermock - 2.0.4\r\n\r\nYou are able to solve this issue. if yes please give us the solution.",
"Try using the newest version of Byte Buddy explicitly. I recently adjusted the code to work with Android's newer API versions.",
"> Try using the newest version of Byte Buddy explicitly. I recently adjusted the code to work with Android's newer API versions.\r\n\r\nTried but no luck\r\n\r\nHere is the log\r\n\r\n\r\n```\r\norg.mockito.exceptions.base.MockitoException: \r\nMockito cannot mock this class: class android.content.Context.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 1.8\r\nJVM vendor name : JetBrains s.r.o\r\nJVM vendor version : 25.202-b49-5587405\r\nJVM name : OpenJDK 64-Bit Server VM\r\nJVM version : 1.8.0_202-release-1483-b49-5587405\r\nJVM info : mixed mode\r\nOS name : Mac OS X\r\nOS version : 10.14.6\r\n\r\n\r\nUnderlying exception : java.lang.IllegalStateException: Error invoking java.lang.reflect.Executable#getAnnotatedExceptionTypes\r\n\r\n\tat org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)\r\n\tat org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)\r\n\tat org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)\r\n\tat org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)\r\n\tat org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)\r\n\tat org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)\r\n\tat org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)\r\n\tat com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)\r\nCaused by: java.lang.IllegalStateException: Error invoking java.lang.reflect.Executable#getAnnotatedExceptionTypes\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedExceptionType.resolve(TypeDescription.java:3029)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3201)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:3887)\r\n\tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.apply(AnnotationAppender.java:690)\r\n\tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onNonGenericType(AnnotationAppender.java:671)\r\n\tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onNonGenericType(AnnotationAppender.java:374)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.accept(TypeDescription.java:3677)\r\n\tat net.bytebuddy.implementation.attribute.MethodAttributeAppender$ForInstrumentedMethod.apply(MethodAttributeAppender.java:218)\r\n\tat net.bytebuddy.implementation.attribute.MethodAttributeAppender$Compound.apply(MethodAttributeAppender.java:484)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyAttributes(TypeWriter.java:706)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:696)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:605)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:5133)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1933)\r\n\tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:225)\r\n\tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:198)\r\n\tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3404)\r\n\tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3600)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:172)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n\tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n\tat org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:41)\r\n\tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n\tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:63)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1908)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1817)\r\n\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)\r\n\tat org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)\r\n\tat org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)\r\n\tat org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)\r\n\tat org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)\r\n\tat org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)\r\n\tat org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)\r\n\tat org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)\r\n\tat org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)\r\n\tat org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)\r\n\t... 5 more\r\nCaused by: java.lang.NoClassDefFoundError: android/content/IntentSender$FinishedDispatcher\r\n\tat java.lang.Class.getDeclaringClass0(Native Method)\r\n\tat java.lang.Class.getDeclaringClass(Class.java:1235)\r\n\tat java.lang.Class.getEnclosingClass(Class.java:1277)\r\n\tat sun.reflect.annotation.AnnotatedTypeFactory.addNesting(AnnotatedTypeFactory.java:96)\r\n\tat sun.reflect.annotation.AnnotatedTypeFactory.buildAnnotatedType(AnnotatedTypeFactory.java:65)\r\n\tat sun.reflect.annotation.TypeAnnotationParser.buildAnnotatedTypes(TypeAnnotationParser.java:158)\r\n\tat java.lang.reflect.Executable.getAnnotatedExceptionTypes(Executable.java:718)\r\n\tat sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedExceptionType.resolve(TypeDescription.java:3025)\r\n\t... 65 more\r\n```",
"Are there any updates on this?\r\nI've tried with Mockito `3.2.4`, any possible combination of Byte Buddy versions and excluding it from other testing libraries that use it, no luck.\r\nStill can't run instrumentation tests if I'm using MockK > `1.9` in the same module.",
"I think I may have found the culprit: the newer Dexmaker version MockK is using.\r\nI've managed to get rid of the issue in my project with the latest version of the two libs by doing this:\r\n\r\n```\r\nandroidTestImplementation(\"org.mockito:mockito-android:3.2.4\")\r\nandroidTestImplementation(\"io.mockk:mockk-android:1.9.3\") {\r\n exclude module: 'dexmaker'\r\n}\r\nandroidTestImplementation \"com.linkedin.dexmaker:dexmaker:2.12.1\" // newer versions break Mockito\r\n```",
"Hi all, I have a similar problem. I have the error around trying to mock an interface that utilizes JDBI 2. I've tried various combinations of mockito-core around 2.23.* and 2.24.* and manually setting the byte-buddy version. I currently have 2.23.4 and byte buddy 1.9.11\r\n\r\nI'll include the error and some of the dependency tree. Any ideas?\r\n```\r\norg.mockito.exceptions.base.MockitoException: \r\nMockito cannot mock this class: interface com.groupon.da.aesservice.jdbi.CustomerDbi.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 1.8\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 25.172-b11\r\nJVM name : Java HotSpot(TM) 64-Bit Server VM\r\nJVM version : 1.8.0_172-b11\r\nJVM info : mixed mode\r\nOS name : Mac OS X\r\nOS version : 10.14.6\r\n\r\n\r\nUnderlying exception : java.lang.IllegalArgumentException: Could not create type\r\n\r\n\tat org.mockito.internal.runners.DefaultInternalRunner$1.withBefores(DefaultInternalRunner.java:39)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)\r\n\tat org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)\r\n\tat org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)\r\n\tat org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)\r\n\tat org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)\r\n\tat org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)\r\n\tat org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)\r\n\tat org.junit.runners.ParentRunner.run(ParentRunner.java:363)\r\n\tat org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)\r\n\tat org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)\r\n\tat org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)\r\n\tat org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)\r\n\tat com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)\r\n\tat com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)\r\nCaused by: java.lang.IllegalArgumentException: Could not create type\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n\tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n\tat org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:41)\r\n\tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n\tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1896)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)\r\n\tat org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)\r\n\tat org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)\r\n\tat org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)\r\n\tat org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)\r\n\tat org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)\r\n\tat org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)\r\n\t... 19 more\r\nCaused by: java.lang.annotation.AnnotationFormatError: Invalid default: public abstract java.lang.Class org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator.errorListener()\r\n\tat java.lang.reflect.Method.getDefaultValue(Method.java:612)\r\n\tat sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:132)\r\n\tat sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:85)\r\n\tat sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:266)\r\n\tat sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)\r\n\tat sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)\r\n\tat java.lang.Class.createAnnotationData(Class.java:3521)\r\n\tat java.lang.Class.annotationData(Class.java:3510)\r\n\tat java.lang.Class.getAnnotations(Class.java:3446)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:85)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n\t... 38 more\r\n```\r\n\r\nPartial Dependency tree (lines with *byte* and *mock*)\r\n```\r\n[INFO] {myProject}\r\n[INFO] +- net.bytebuddy:byte-buddy-agent:jar:1.9.11:test\r\n[INFO] +- net.bytebuddy:byte-buddy:jar:1.9.11:test\r\n[INFO] +- org.mockito:mockito-core:jar:2.23.4:test\r\n[INFO] | \\- org.objenesis:objenesis:jar:3.0.1:test\r\n[INFO] +- org.powermock:powermock-module-junit4:jar:2.0.2:test\r\n[INFO] | +- org.powermock:powermock-module-junit4-common:jar:2.0.2:test\r\n[INFO] | \\- org.hamcrest:hamcrest-core:jar:1.3:test\r\n[INFO] +- org.powermock:powermock-api-mockito2:jar:2.0.2:test\r\n[INFO] | \\- org.powermock:powermock-api-support:jar:2.0.2:test\r\n[INFO] +- org.powermock:powermock-core:jar:2.0.2:test\r\n[INFO] | +- org.powermock:powermock-reflect:jar:2.0.2:test\r\n[INFO] | \\- org.javassist:javassist:jar:3.24.1-GA:compile\r\n```",
"\r\n\r\n\r\n> I think I may have found the culprit: the newer Dexmaker version MockK is using.\r\n> I've managed to get rid of the issue in my project with the latest version of the two libs by doing this:\r\n> \r\n> ```\r\n> androidTestImplementation(\"org.mockito:mockito-android:3.2.4\")\r\n> androidTestImplementation(\"io.mockk:mockk-android:1.9.3\") {\r\n> exclude module: 'dexmaker'\r\n> }\r\n> androidTestImplementation \"com.linkedin.dexmaker:dexmaker:2.12.1\" // newer versions break Mockito\r\n> ```\r\n\r\nThank you very much.\r\n\r\nresolutionStrategy {\r\n force(\"com.linkedin.dexmaker:dexmaker:2.12.1\")\r\n}",
"You don't need to exclude or declare the dexmaker dependency. The resolutionStrategy part works just fine",
"Started getting this on Android after updating to Kotlin 1.4.0 with Mockito 3.5.2:\r\n\r\n```\r\nMockito cannot mock this class: class android.content.Context.\r\n\r\nJava : 11\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 11.0.8+10\r\nJVM name : OpenJDK 64-Bit Server VM\r\nJVM version : 11.0.8+10\r\nJVM info : mixed mode\r\nOS name : Linux\r\nOS version : 4.15.0-1077-aws\r\n``` \r\n\r\nI'm not using Mockk anywhere, dexmaker isn't part of my dependencies tree and everything was working perfectly fine before updating the language. All tests are running against Android API 28, so pretty sure this isn't \"Android changing its APIs in a non-compatible manner\" as was previously mentioned.",
"Is there no stack trace or anything? We had some quick bug fixes right after release. Could you try out the version just released?\r\n\r\nAlso, can you try to downgrade the implicit Objenesis dependency? It seems to break a lot of Android things due to its use of `MethodHandle`s.",
"Thanks @raphw. I managed to isolate the issue. It seems CircleCI updated their JVM version to 11.0.8 without letting anyone know, and that caused several issues including this. Upgrading to Mockito's latest version and then instructing CircleCI to use JVM 8 fixes it.",
"Hey @raphw, I am having the same issue. Can you please let me know how you instruct CircleCI to use JVM 8? I can't seem to find how to do it.",
"I don't use CircleCI but @mradzinski can maybe help you out.",
"Oh I am sorry @raphw, I tagged the wrong person. I meant to tag @mradzinski. However I updated the `mockito` libraries (we use `mockito-android` and `mockito-kotlin`) to the latest versions and our tests worked fine once again, I didn't have to mess with the CircleCI configuration. Thank you!",
"Hi All,\r\n\r\nI'm also seeing this error while mocking \r\n@Mock\r\nprivate KafkaFactory mockKafkaFactory;\r\n\r\njava.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler@770f8c86 failed.\r\n\r\n\tat org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:84)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:308)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)\r\n\tat org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)\r\n\tat org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)\r\n\tat org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)\r\n\tat org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)\r\n\tat org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)\r\n\tat org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)\r\n\tat org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:137)\r\n\tat org.junit.runner.JUnitCore.run(JUnitCore.java:115)\r\n\tat org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)\r\n\tat java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)\r\n\tat java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)\r\n\tat java.util.Iterator.forEachRemaining(Iterator.java:116)\r\n\tat java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)\r\n\tat java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)\r\n\tat java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)\r\n\tat java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)\r\n\tat java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)\r\n\tat java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)\r\n\tat java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)\r\n\tat org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)\r\n\tat org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)\r\n\tat org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)\r\n\tat com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)\r\n\tat com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)\r\n\tat com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)\r\n\tat com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)\r\nCaused by: org.mockito.exceptions.base.MockitoException: \r\nMockito cannot mock this class: class com.vlocity.xom.kafka.KafkaFactory.\r\n\r\nMockito can only mock non-private & non-final classes.\r\nIf you're not sure why you're getting this error, please report to the mailing list.\r\n\r\n\r\nJava : 1.8\r\nJVM vendor name : Oracle Corporation\r\nJVM vendor version : 25.251-b08\r\nJVM name : Java HotSpot(TM) 64-Bit Server VM\r\nJVM version : 1.8.0_251-b08\r\nJVM info : mixed mode\r\nOS name : Windows 10\r\nOS version : 10.0\r\n\r\n\r\nUnderlying exception : java.lang.IllegalStateException: Error invoking java.lang.reflect.Executable#getAnnotatedParameterTypes\r\n\tat org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)\r\n\tat org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)\r\n\tat org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)\r\n\tat org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)\r\n\t... 24 more\r\nCaused by: java.lang.IllegalStateException: Error invoking java.lang.reflect.Executable#getAnnotatedParameterTypes\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedParameterizedType.resolve(TypeDescription.java:3025)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:3238)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:3987)\r\n\tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.apply(AnnotationAppender.java:725)\r\n\tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onNonGenericType(AnnotationAppender.java:706)\r\n\tat net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onNonGenericType(AnnotationAppender.java:409)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$OfNonGenericType.accept(TypeDescription.java:3769)\r\n\tat net.bytebuddy.implementation.attribute.MethodAttributeAppender$ForInstrumentedMethod.apply(MethodAttributeAppender.java:208)\r\n\tat net.bytebuddy.implementation.attribute.MethodAttributeAppender$Compound.apply(MethodAttributeAppender.java:484)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyAttributes(TypeWriter.java:701)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:691)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:600)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:5660)\r\n\tat net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:2166)\r\n\tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:232)\r\n\tat net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:204)\r\n\tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3595)\r\n\tat net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:3819)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:128)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)\r\n\tat net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)\r\n\tat net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)\r\n\tat org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)\r\n\tat org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)\r\n\tat org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)\r\n\tat org.powermock.api.mockito.mockmaker.PowerMockMaker.createMock(PowerMockMaker.java:41)\r\n\tat org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)\r\n\tat org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)\r\n\tat org.mockito.Mockito.mock(Mockito.java:1895)\r\n\tat org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:108)\r\n\tat org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.doCreateMock(DefaultMockCreator.java:61)\r\n\tat org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:53)\r\n\tat org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:40)\r\n\tat org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:181)\r\n\tat org.powermock.api.extension.listener.AnnotationEnabler.standardInject(AnnotationEnabler.java:98)\r\n\tat org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:55)\r\n\tat org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:308)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)\r\n\tat org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)\r\n\tat org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)\r\n\tat org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)\r\n\tat org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)\r\n\tat org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)\r\n\tat org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)\r\n\tat org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)\r\n\tat org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)\r\n\t... 24 more\r\nCaused by: java.lang.NullPointerException\r\n\tat sun.reflect.annotation.TypeAnnotationParser.mapTypeAnnotations(TypeAnnotationParser.java:356)\r\n\tat sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl.<init>(AnnotatedTypeFactory.java:139)\r\n\tat sun.reflect.annotation.AnnotatedTypeFactory.buildAnnotatedType(AnnotatedTypeFactory.java:65)\r\n\tat sun.reflect.annotation.TypeAnnotationParser.buildAnnotatedTypes(TypeAnnotationParser.java:137)\r\n\tat java.lang.reflect.Executable.getAnnotatedParameterTypes(Executable.java:688)\r\n\tat sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Dispatcher$ForJava8CapableVm$AnnotatedParameterizedType.resolve(TypeDescription.java:3021)\r\n\t... 82 more\r\n\r\n\r\n\r\nDependency tree:\r\n+- org.springframework.boot:spring-boot-starter-test:jar:2.3.2.RELEASE:test\r\n[INFO] | +- org.springframework.boot:spring-boot-test:jar:2.3.2.RELEASE:test\r\n[INFO] | +- org.springframework.boot:spring-boot-test-autoconfigure:jar:2.3.2.RELEASE:test\r\n[INFO] | +- org.junit.jupiter:junit-jupiter:jar:5.6.2:test\r\n[INFO] | | +- org.junit.jupiter:junit-jupiter-api:jar:5.6.2:test\r\n[INFO] | | | +- org.opentest4j:opentest4j:jar:1.2.0:test\r\n[INFO] | | | \\- org.junit.platform:junit-platform-commons:jar:1.6.2:test\r\n[INFO] | | +- org.junit.jupiter:junit-jupiter-params:jar:5.6.2:test\r\n[INFO] | | \\- org.junit.jupiter:junit-jupiter-engine:jar:5.6.2:test\r\n[INFO] | +- org.junit.vintage:junit-vintage-engine:jar:5.6.2:test\r\n[INFO] | | +- org.apiguardian:apiguardian-api:jar:1.1.0:test\r\n[INFO] | | \\- org.junit.platform:junit-platform-engine:jar:1.6.2:test\r\n[INFO] | +- org.mockito:mockito-junit-jupiter:jar:3.3.3:test\r\n[INFO] | +- org.skyscreamer:jsonassert:jar:1.5.0:test\r\n[INFO] | | \\- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test\r\n[INFO] | +- org.springframework:spring-test:jar:5.2.8.RELEASE:test\r\n[INFO] | \\- org.xmlunit:xmlunit-core:jar:2.7.0:test\r\n[INFO] +- org.powermock:powermock-module-junit4:jar:2.0.7:test\r\n[INFO] | +- org.powermock:powermock-module-junit4-common:jar:2.0.7:test\r\n[INFO] | | +- org.powermock:powermock-reflect:jar:2.0.7:test\r\n[INFO] | | \\- org.powermock:powermock-core:jar:2.0.7:test\r\n[INFO] | | \\- org.javassist:javassist:jar:3.27.0-GA:test\r\n[INFO] | +- junit:junit:jar:4.13:compile\r\n[INFO] | \\- org.hamcrest:hamcrest-core:jar:2.2:test\r\n[INFO] +- org.powermock:powermock-api-mockito2:jar:2.0.7:test\r\n[INFO] | \\- org.powermock:powermock-api-support:jar:2.0.7:test\r\n[INFO] +- org.mockito:mockito-core:jar:2.23.0:test\r\n[INFO] | +- net.bytebuddy:byte-buddy:jar:1.10.13:test\r\n[INFO] | +- net.bytebuddy:byte-buddy-agent:jar:1.10.13:test\r\n[INFO] | \\- org.objenesis:objenesis:jar:2.6:test",
"Seems like you are using a version of PowerMock that is not compatible with the particular version of Mockito. Please check the PowerMock documentation to see what version to use and see if there's a compatible update.",
"for my case, after i added dependencies of spring-test, spring-tx, assertj-core. error does not appear any more.",
"It is work for me.\r\n\r\n```\r\nandroidTestImplementation(\"org.mockito:mockito-android:3.6.28\")\r\nandroidTestImplementation(\"io.mockk:mockk-android:1.10.3\") {\r\n exclude module: 'dexmaker'\r\n}\r\n// newer versions break Mockito\r\nandroidTestImplementation \"com.linkedin.dexmaker:dexmaker:2.28.0\"\r\n```",
"We haven't received any new reports for almost a year, so I am closing this issue now. Thanks everyone for your contributions! If anybody else runs into this issue in the future, please double-check the version of ByteBuddy you are using and make sure it adheres to the dependency requirements that Mockito has."
] | [
"I don't think this warrants a new minor release. I think this should be just 2.25.5",
"No probs. I generally like to publish new minor every few weeks. It's arbitrary what we warrant a new minor release, and that's OK.\r\n\r\nI need to finally set up the automation that automatically pushes to MavenCentral if the version is next minor."
] | "2019-03-23T17:08:56Z" | [] | Unexpected error (Mockito can only mock non-private & non-final classes.) in version 2.24.0 | Hi,
Since version 2.24.0 I got the error "Mockito can only mock non-private & non-final classes.". Reverting back to Mockito 2.23.4 resolves the problem.
**Stacktrace**
`Underlying exception : java.lang.IllegalArgumentException: Could not create type
at nl.tkp.ddw.pensioenaangifte.test.model.unittesten.AanleveringFilteringStepDefinitions.setup(AanleveringFilteringStepDefinitions.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:26)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:20)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runner.HookDefinitionMatch.runStep(HookDefinitionMatch.java:16)
at cucumber.runner.TestStep.executeStep(TestStep.java:63)
at cucumber.runner.TestStep.run(TestStep.java:49)
at cucumber.runner.TestCase.run(TestCase.java:40)
at cucumber.runner.Runner.runPickle(Runner.java:40)
at cucumber.runtime.junit.PickleRunners$NoStepDescriptions.run(PickleRunners.java:146)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:68)
at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:23)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:73)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:124)
at cucumber.api.junit.Cucumber.runChild(Cucumber.java:65)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at cucumber.api.junit.Cucumber$1.evaluate(Cucumber.java:133)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Could not create type
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62)
at org.mockito.Mockito.mock(Mockito.java:1896)
at org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:44)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:49)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
... 63 more
Caused by: java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.MultipleParentClassLoader$Builder.appendMostSpecific(Ljava/util/Collection;)Lnet/bytebuddy/dynamic/loading/MultipleParentClassLoader$Builder;
at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:83)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
... 81 more`
**Versioninfo**
Java: 1.8
JVM vendor name: Oracle Corporation
JVM vendor version: 25.191-b12
JVM name: Java HotSpot(TM) 64-Bit Server VM
JVM version: 1.8.0_191-b12
JVM info: mixed mode
OS name: Mac OS X
OS version: 10.13.6
Mockito-core: 2.24.0 | [
"gradle/dependencies.gradle"
] | [
"gradle/dependencies.gradle"
] | [] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index fe5509e557..c6462ed7e3 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -4,7 +4,7 @@ ext {
def versions = [:]
-versions.bytebuddy = '1.9.7'
+versions.bytebuddy = '1.9.11'
versions.junitJupiter = '5.1.1'
versions.errorprone = '2.3.2'
| null | test | val | 2019-03-23T15:50:20 | "2019-02-04T10:48:15Z" | frankvanderkuur | train |
mockito/mockito/1542_1701 | mockito/mockito | mockito/mockito/1542 | mockito/mockito/1701 | [
"keyword_pr_to_issue"
] | a1a78ef7539a6b7527acbec6e2323413d0c2dfa3 | 1ae32bda7ea485f94374c74c085fcdbd8b000e53 | [
"Nice report, thank you! Do you want to take a stub at fixing it? I suspect that we need to tweak the reporting, so that we print other interactions, too. We do something like that for regular verification failures (as opposed to verification failures due to mismatched arguments)",
"I can try and take a look at this.",
"hi @mockitoguy\r\nsorry my email is bleeding with spam and I've been caught up with some deadlines\r\nit would be an interesting piece of work that I'd like to take but I don't have the time right now for\r\nit's going into my todo list, though",
"Just started working on this today. Doesn't seem like too bad of a change. I should have something to show later today or tomorrow."
] | [] | "2019-05-02T17:27:15Z" | [
"please contribute"
] | when mock is called multiple times, and verify fails, the error message reports only the first invocation | AS A diligent dev,
I WANT TO verify that a mock will eventually get called with the specified parameters,
SO THAT I can properly test my builder class
SCENARIO
I have a builder class exposing a .with(String key, String value) method.
I created a test for testing that at a certain point the method gets called with 'foo', 'valueFoo'
I'd like to follow a test pattern where 1 test case has only 1 assertion
```
builderMock.with('bar','valueBar');
builderMock.with('foo','notValueFoo');
verify(builderMock).with('foo','valueFoo');
```
WHAT'S WRONG
Verify reports only the first invocation in the test failed logs.
```
Arguments are different! Wanted:
builderMock.with('foo','valueFoo');
at ...
Actual invocation has different arguments:
builderMock.with('bar','valueBar');
at ...
```
IMO should be a list of invocation for that methods, something like:
```
// Actual invocations have different arguments:
// builderMock.with('bar','valueBar');
// at ...
// builderMock.with('foo','notValueFoo');
// at ...
```
NOTE
For anybody else having this problem, I'm rethrowing the exception raised with something like this:
```
public static ArgumentsAreDifferent createExceptionWithEnhancedVerifyLogsFor(
Object mockedObject,
String invokedMethod,
ArgumentsAreDifferent ex
) {
String newline = System.getProperty("line.separator");
String wanted = ex.getExpected();
String actualTitle = MessageFormat.format(
"Interactions of {0}.{1}():",
mockedObject.getClass().getCanonicalName(), invokedMethod
);
String actual = mockingDetails(mockedObject).getInvocations().stream()
.filter(invocation -> invocation.getMethod().getName().equals(invokedMethod))
.map(Object::toString)
.collect(Collectors.joining( newline ));
String message = String.join(newline,
ex.getClass().getCanonicalName(),
"Wanted: " + wanted,
actualTitle, actual
);
ArgumentsAreDifferent enhancedEx = new ArgumentsAreDifferent(message, wanted, actual);
enhancedEx.setStackTrace(ex.getStackTrace());
return enhancedEx;
}
``` | [
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/reporting/SmartPrinter.java",
"src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java"
] | [
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/reporting/SmartPrinter.java",
"src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java"
] | [
"src/test/java/org/mockito/internal/verification/SmartPrinterTest.java",
"src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java",
"src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java"
] | diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 1b68fbb657..30513525f4 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -299,17 +299,33 @@ private static Object locationsOf(Collection<LocalizedMatcher> matchers) {
return join(description.toArray());
}
- public static AssertionError argumentsAreDifferent(String wanted, String actual, Location actualLocation) {
- String message = join("Argument(s) are different! Wanted:",
- wanted,
- new LocationImpl(),
- "Actual invocation has different arguments:",
- actual,
- actualLocation,
- ""
- );
+ public static AssertionError argumentsAreDifferent(String wanted, List<String> actualCalls, List<Location> actualLocations) {
+ if (actualCalls == null || actualLocations == null || actualCalls.size() != actualLocations.size()) {
+ throw new IllegalArgumentException("actualCalls and actualLocations list must match");
+ }
+
+
+ StringBuilder actualBuilder = new StringBuilder();
+ StringBuilder messageBuilder = new StringBuilder();
+ messageBuilder.append("\n")
+ .append("Argument(s) are different! Wanted:\n")
+ .append(wanted)
+ .append("\n")
+ .append(new LocationImpl())
+ .append("\n")
+ .append("Actual invocations have different arguments:\n");
+
+ for (int i = 0; i < actualCalls.size(); i++) {
+ actualBuilder.append(actualCalls.get(i))
+ .append("\n");
+
+ messageBuilder.append(actualCalls.get(i))
+ .append("\n")
+ .append(actualLocations.get(i))
+ .append("\n");
+ }
- return ExceptionFactory.createArgumentsAreDifferentException(message, wanted, actual);
+ return ExceptionFactory.createArgumentsAreDifferentException(messageBuilder.toString(), wanted, actualBuilder.toString());
}
public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted) {
diff --git a/src/main/java/org/mockito/internal/reporting/SmartPrinter.java b/src/main/java/org/mockito/internal/reporting/SmartPrinter.java
index 8da053ddf1..24d8367b00 100644
--- a/src/main/java/org/mockito/internal/reporting/SmartPrinter.java
+++ b/src/main/java/org/mockito/internal/reporting/SmartPrinter.java
@@ -8,6 +8,10 @@
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MatchableInvocation;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
/**
* Makes sure both wanted and actual are printed consistently (single line or multiline)
* <p>
@@ -16,22 +20,40 @@
public class SmartPrinter {
private final String wanted;
- private final String actual;
+ private final List<String> actuals;
public SmartPrinter(MatchableInvocation wanted, Invocation actual, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) {
+ this(wanted, Collections.singletonList(actual), indexesOfMatchersToBeDescribedWithExtraTypeInfo);
+ }
+
+ public SmartPrinter(MatchableInvocation wanted, List<Invocation> allActualInvocations, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) {
PrintSettings printSettings = new PrintSettings();
- printSettings.setMultiline(wanted.toString().contains("\n") || actual.toString().contains("\n"));
+ printSettings.setMultiline(isMultiLine(wanted, allActualInvocations));
printSettings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchersToBeDescribedWithExtraTypeInfo);
this.wanted = printSettings.print(wanted);
- this.actual = printSettings.print(actual);
+
+ List<String> actuals = new ArrayList<String>();
+ for (Invocation actual : allActualInvocations) {
+ actuals.add(printSettings.print(actual));
+ }
+ this.actuals = Collections.unmodifiableList(actuals);
}
public String getWanted() {
return wanted;
}
- public String getActual() {
- return actual;
+ public List<String> getActuals() {
+ return actuals;
+ }
+
+ private static boolean isMultiLine(MatchableInvocation wanted, List<Invocation> allActualInvocations) {
+ boolean isWantedMultiline = wanted.toString().contains("\n");
+ boolean isAnyActualMultiline = false;
+ for (Invocation invocation : allActualInvocations) {
+ isAnyActualMultiline |= invocation.toString().contains("\n");
+ }
+ return isWantedMultiline || isAnyActualMultiline;
}
}
diff --git a/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java b/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java
index 3f89c77787..c13aa0098c 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/MissingInvocationChecker.java
@@ -17,8 +17,10 @@
import java.util.List;
import org.mockito.internal.reporting.SmartPrinter;
+import org.mockito.internal.util.collections.ListUtil;
import org.mockito.internal.verification.api.InOrderContext;
import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
import org.mockito.invocation.MatchableInvocation;
public class MissingInvocationChecker {
@@ -39,8 +41,15 @@ public static void checkMissingInvocation(List<Invocation> invocations, Matchabl
}
Integer[] indexesOfSuspiciousArgs = getSuspiciouslyNotMatchingArgsIndexes(wanted.getMatchers(), similar.getArguments());
- SmartPrinter smartPrinter = new SmartPrinter(wanted, similar, indexesOfSuspiciousArgs);
- throw argumentsAreDifferent(smartPrinter.getWanted(), smartPrinter.getActual(), similar.getLocation());
+ SmartPrinter smartPrinter = new SmartPrinter(wanted, invocations, indexesOfSuspiciousArgs);
+ List<Location> actualLocations = ListUtil.convert(invocations, new ListUtil.Converter<Invocation, Location>() {
+ @Override
+ public Location convert(Invocation invocation) {
+ return invocation.getLocation();
+ }
+ });
+
+ throw argumentsAreDifferent(smartPrinter.getWanted(), smartPrinter.getActuals(), actualLocations);
}
| diff --git a/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java b/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java
index 4918991d3d..d786762a8d 100644
--- a/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java
+++ b/src/test/java/org/mockito/internal/verification/SmartPrinterTest.java
@@ -36,7 +36,9 @@ public void shouldPrintBothInMultilinesWhenFirstIsMulti() {
//then
assertThat(printer.getWanted()).contains("\n");
- assertThat(printer.getActual()).contains("\n");
+ for (String actual : printer.getActuals()) {
+ assertThat(actual).contains("\n");
+ }
}
@Test
@@ -46,7 +48,9 @@ public void shouldPrintBothInMultilinesWhenSecondIsMulti() {
//then
assertThat(printer.getWanted()).contains("\n");
- assertThat(printer.getActual()).contains("\n");
+ for (String actual : printer.getActuals()) {
+ assertThat(actual).contains("\n");
+ }
}
@Test
@@ -56,7 +60,9 @@ public void shouldPrintBothInMultilinesWhenBothAreMulti() {
//then
assertThat(printer.getWanted()).contains("\n");
- assertThat(printer.getActual()).contains("\n");
+ for (String actual : printer.getActuals()) {
+ assertThat(actual).contains("\n");
+ }
}
@Test
@@ -66,6 +72,8 @@ public void shouldPrintBothInSingleLineWhenBothAreShort() {
//then
assertThat(printer.getWanted()).doesNotContain("\n");
- assertThat(printer.getActual()).doesNotContain("\n");
+ for (String actual : printer.getActuals()) {
+ assertThat(actual).doesNotContain("\n");
+ }
}
}
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 107f5ce8f8..c71404ac3e 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java
@@ -67,7 +67,7 @@ public void shouldReportWantedInvocationDiffersFromActual() {
exception.expectMessage("Argument(s) are different! Wanted:");
exception.expectMessage("mock.intArgumentMethod(2222);");
- exception.expectMessage("Actual invocation has different arguments:");
+ exception.expectMessage("Actual invocations have different arguments:");
exception.expectMessage("mock.intArgumentMethod(1111);");
MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
@@ -82,7 +82,7 @@ public void shouldReportUsingInvocationDescription() {
exception.expectMessage("Argument(s) are different! Wanted:");
exception.expectMessage("mock.intArgumentMethod(MyCoolPrint(2222));");
- exception.expectMessage("Actual invocation has different arguments:");
+ exception.expectMessage("Actual invocations have different arguments:");
exception.expectMessage("mock.intArgumentMethod(MyCoolPrint(1111));");
MissingInvocationChecker.checkMissingInvocation(invocations, wanted);
@@ -103,7 +103,7 @@ private InvocationBuilder buildDifferentMethod() {
static class CustomInvocationBuilder extends InvocationBuilder {
@Override
protected Invocation createInvocation(MockReference<Object> mockRef, MockitoMethod mockitoMethod, final Object[] arguments,
- RealMethod realMethod, Location location, int sequenceNumber) {
+ RealMethod realMethod, Location location, int sequenceNumber) {
return new InterceptedInvocation(mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber) {
@Override
public List<ArgumentMatcher> getArgumentsAsMatchers() {
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 51cbc02c70..398e3b1b38 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationInOrderCheckerTest.java
@@ -77,7 +77,7 @@ public void shouldReportArgumentsAreDifferent() throws Exception {
exception.expectMessage("Argument(s) are different! Wanted:");
exception.expectMessage("mock.intArgumentMethod(2222);");
- exception.expectMessage("Actual invocation has different arguments:");
+ exception.expectMessage("Actual invocations have different arguments:");
exception.expectMessage("mock.intArgumentMethod(1111);");
checkMissingInvocation(invocations, wanted, context);
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
index e920ad8f4e..ef7770542f 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
@@ -97,7 +97,7 @@ public void shouldPrintVerificationInOrderErrorAndShowWantedAndActual() {
inOrder.verify(one).simpleMethod(999);
fail();
} catch (org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent e) {
- assertThat(e).hasMessageContaining("has different arguments");
+ assertThat(e).hasMessageContaining("have different arguments");
}
}
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
index 729343471f..305e8ac112 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenVerificationFailsTest.java
@@ -82,7 +82,7 @@ public void should_print_actual_and_wanted_in_line() {
String actual =
"\n" +
- "Actual invocation has different arguments:" +
+ "Actual invocations have different arguments:" +
"\n" +
"iMethods.varargs(1, 2);";
@@ -116,7 +116,7 @@ public void should_print_actual_and_wanted_in_multiple_lines() {
String actual =
"\n" +
- "Actual invocation has different arguments:" +
+ "Actual invocations have different arguments:" +
"\n" +
"iMethods.varargs(" +
"\n" +
diff --git a/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java b/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java
new file mode 100644
index 0000000000..96f4c442b1
--- /dev/null
+++ b/src/test/java/org/mockitousage/verification/VerifyPrintsAllInvocationsOnErrorTest.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitousage.verification;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.fail;
+
+
+public class VerifyPrintsAllInvocationsOnErrorTest {
+
+ @Test
+ public void shouldPrintAllInvocationsOnError() {
+ ExampleBuilder mockBuilder = Mockito.mock(ExampleBuilder.class);
+ mockBuilder.with("key1", "val1");
+ mockBuilder.with("key2", "val2");
+ try {
+ Mockito.verify(mockBuilder).with("key1", "wrongValue");
+ fail();
+ }
+ catch (ArgumentsAreDifferent e) {
+ assertThat(e).hasMessageContaining("exampleBuilder.with(\"key1\", \"val1\")");
+ assertThat(e).hasMessageContaining("exampleBuilder.with(\"key2\", \"val2\"");
+ }
+ }
+
+
+ private static class ExampleBuilder {
+ public ExampleBuilder with(String key, String val) {
+ return this;
+ }
+ }
+}
| val | val | 2019-05-01T17:33:47 | "2018-11-23T15:17:22Z" | erikologic | train |
mockito/mockito/1623_1708 | mockito/mockito | mockito/mockito/1623 | mockito/mockito/1708 | [
"timestamp(timedelta=4.0, similarity=0.9213547190073447)",
"keyword_pr_to_issue"
] | 237e915e76a42292965dbc737c61790c32cf7735 | 53e8a93141e1f8c41d6b6d4fd72c20488826269a | [
"I would welcome a PR for this :smile: "
] | [] | "2019-05-06T15:05:32Z" | [
"enhancement"
] | Consider renaming TooLittleActualInvocations | I agree with the commenter [here](https://github.com/mockito/mockito/issues/1088#issuecomment-303374289) that the exception name `TooLittleActualInvocations` is not ideal.
The correct English would be `TooFewActualInvocations` (where "few" is the opposite of "many" - as used in `TooManyActualInvocations`).
I appreciate this isn't the most critical issue ever raised, but it would make this assertion failure more readable!
As the existing class is non-final, I imagine it could be changed without breaking existing client code via subclassing and deprecating the original. Please let me know if it would be helpful for me to pick this up (or instead if the change wouldn't be desirable, or I'm otherwise missing something).
Thanks
| [
"src/main/java/org/mockito/exceptions/verification/TooLittleActualInvocations.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/main/java/org/mockito/exceptions/verification/TooFewActualInvocations.java",
"src/main/java/org/mockito/exceptions/verification/TooLittleActualInvocations.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java",
"src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java"
] | [
"src/test/java/org/mockito/internal/exceptions/ReporterTest.java",
"src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java",
"src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java",
"src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java",
"src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java",
"src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java",
"src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java",
"src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java",
"src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java",
"src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java",
"src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java",
"src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java"
] | diff --git a/src/main/java/org/mockito/exceptions/verification/TooFewActualInvocations.java b/src/main/java/org/mockito/exceptions/verification/TooFewActualInvocations.java
new file mode 100644
index 0000000000..5ffbb2f83b
--- /dev/null
+++ b/src/main/java/org/mockito/exceptions/verification/TooFewActualInvocations.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2019 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.exceptions.verification;
+
+/**
+ * @since 2.27.5
+ */
+public class TooFewActualInvocations extends TooLittleActualInvocations {
+
+ private static final long serialVersionUID = 1L;
+
+ public TooFewActualInvocations(String message) {
+ super(message);
+ }
+}
diff --git a/src/main/java/org/mockito/exceptions/verification/TooLittleActualInvocations.java b/src/main/java/org/mockito/exceptions/verification/TooLittleActualInvocations.java
index d47a4409d9..eb857fb1ef 100644
--- a/src/main/java/org/mockito/exceptions/verification/TooLittleActualInvocations.java
+++ b/src/main/java/org/mockito/exceptions/verification/TooLittleActualInvocations.java
@@ -7,6 +7,11 @@
import org.mockito.exceptions.base.MockitoAssertionError;
+/**
+ * @deprecated as of 2.27.5. Please use {@link TooFewActualInvocations} instead.
+ * @see TooFewActualInvocations
+ */
+@Deprecated
public class TooLittleActualInvocations extends MockitoAssertionError {
private static final long serialVersionUID = 1L;
diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index 30513525f4..d903d9041d 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -12,7 +12,7 @@
import org.mockito.exceptions.verification.NeverWantedButInvoked;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.exceptions.verification.SmartNullPointerException;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.exceptions.verification.TooManyActualInvocations;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockito.exceptions.verification.WantedButNotInvoked;
@@ -419,9 +419,9 @@ private static String createAllLocationsMessage(List<Location> locations) {
return sb.toString();
}
- private static String createTooLittleInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy,
- DescribedInvocation wanted,
- List<Location> locations) {
+ private static String createTooFewInvocationsMessage(org.mockito.internal.reporting.Discrepancy discrepancy,
+ DescribedInvocation wanted,
+ List<Location> locations) {
return join(
wanted.toString(),
"Wanted " + discrepancy.getPluralizedWantedCount() + (discrepancy.getWantedCount() == 0 ? "." : ":"),
@@ -431,14 +431,14 @@ private static String createTooLittleInvocationsMessage(org.mockito.internal.rep
);
}
- public static MockitoAssertionError tooLittleActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> allLocations) {
- String message = createTooLittleInvocationsMessage(discrepancy, wanted, allLocations);
+ public static MockitoAssertionError tooFewActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> allLocations) {
+ String message = createTooFewInvocationsMessage(discrepancy, wanted, allLocations);
- return new TooLittleActualInvocations(message);
+ return new TooFewActualInvocations(message);
}
- public static MockitoAssertionError tooLittleActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> locations) {
- String message = createTooLittleInvocationsMessage(discrepancy, wanted, locations);
+ public static MockitoAssertionError tooFewActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, List<Location> locations) {
+ String message = createTooFewInvocationsMessage(discrepancy, wanted, locations);
return new VerificationInOrderFailure(join(
"Verification in order failure:" + message
diff --git a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
index d0eb0b5eb8..21493b558e 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
@@ -11,8 +11,8 @@
import org.mockito.invocation.Location;
import org.mockito.invocation.MatchableInvocation;
-import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocations;
-import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocationsInOrder;
+import static org.mockito.internal.exceptions.Reporter.tooFewActualInvocations;
+import static org.mockito.internal.exceptions.Reporter.tooFewActualInvocationsInOrder;
import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import static org.mockito.internal.invocation.InvocationMarker.markVerifiedInOrder;
import static org.mockito.internal.invocation.InvocationsFinder.findAllMatchingUnverifiedChunks;
@@ -27,7 +27,7 @@ public static void checkAtLeastNumberOfInvocations(List<Invocation> invocations,
int actualCount = actualInvocations.size();
if (wantedCount > actualCount) {
List<Location> allLocations = getAllLocations(actualInvocations);
- throw tooLittleActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations);
+ throw tooFewActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations);
}
markVerified(actualInvocations, wanted);
@@ -40,7 +40,7 @@ public static void checkAtLeastNumberOfInvocations(List<Invocation> invocations,
if (wantedCount > actualCount) {
List<Location> allLocations = getAllLocations(chunk);
- throw tooLittleActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations);
+ throw tooFewActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, allLocations);
}
markVerifiedInOrder(chunk, wanted, orderingContext);
diff --git a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
index 1dfc2f1f25..bc31064379 100644
--- a/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
+++ b/src/main/java/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
@@ -14,8 +14,8 @@
import org.mockito.invocation.MatchableInvocation;
import static org.mockito.internal.exceptions.Reporter.neverWantedButInvoked;
-import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocations;
-import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocationsInOrder;
+import static org.mockito.internal.exceptions.Reporter.tooFewActualInvocations;
+import static org.mockito.internal.exceptions.Reporter.tooFewActualInvocationsInOrder;
import static org.mockito.internal.exceptions.Reporter.tooManyActualInvocations;
import static org.mockito.internal.exceptions.Reporter.tooManyActualInvocationsInOrder;
import static org.mockito.internal.invocation.InvocationMarker.markVerified;
@@ -36,7 +36,7 @@ public static void checkNumberOfInvocations(List<Invocation> invocations, Matcha
int actualCount = actualInvocations.size();
if (wantedCount > actualCount) {
List<Location> allLocations = getAllLocations(actualInvocations);
- throw tooLittleActualInvocations(new Discrepancy(wantedCount, actualCount), wanted, allLocations);
+ throw tooFewActualInvocations(new Discrepancy(wantedCount, actualCount), wanted, allLocations);
}
if (wantedCount == 0 && actualCount > 0) {
throw neverWantedButInvoked(wanted, getAllLocations(actualInvocations));
@@ -55,7 +55,7 @@ public static void checkNumberOfInvocations(List<Invocation> invocations, Matcha
if (wantedCount > actualCount) {
List<Location> allLocations = getAllLocations(chunk);
- throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, allLocations);
+ throw tooFewActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, allLocations);
}
if (wantedCount < actualCount) {
throw tooManyActualInvocationsInOrder(wantedCount, actualCount, wanted, getAllLocations(chunk));
@@ -70,7 +70,7 @@ public static void checkNumberOfInvocationsNonGreedy(List<Invocation> invocation
while( actualCount < wantedCount ){
Invocation next = findFirstMatchingUnverifiedInvocation(invocations, wanted, context );
if( next == null ){
- throw tooLittleActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, Arrays.asList(lastLocation));
+ throw tooFewActualInvocationsInOrder(new Discrepancy(wantedCount, actualCount), wanted, Arrays.asList(lastLocation));
}
markVerified( next, wanted );
context.markVerified( next );
| diff --git a/src/test/java/org/mockito/internal/exceptions/ReporterTest.java b/src/test/java/org/mockito/internal/exceptions/ReporterTest.java
index c0bb512df2..e7c92bc92c 100644
--- a/src/test/java/org/mockito/internal/exceptions/ReporterTest.java
+++ b/src/test/java/org/mockito/internal/exceptions/ReporterTest.java
@@ -9,7 +9,7 @@
import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.NoInteractionsWanted;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.stubbing.answers.Returns;
@@ -24,9 +24,9 @@
public class ReporterTest extends TestBase {
- @Test(expected = TooLittleActualInvocations.class)
+ @Test(expected = TooFewActualInvocations.class)
public void should_let_passing_null_last_actual_stack_trace() throws Exception {
- throw Reporter.tooLittleActualInvocations(new org.mockito.internal.reporting.Discrepancy(1, 2), new InvocationBuilder().toInvocation(), null);
+ throw Reporter.tooFewActualInvocations(new org.mockito.internal.reporting.Discrepancy(1, 2), new InvocationBuilder().toInvocation(), null);
}
@Test(expected = MockitoException.class)
diff --git a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
index c4a54c45e3..9befa7f850 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java
@@ -7,7 +7,7 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.invocation.InvocationMatcher;
@@ -39,7 +39,7 @@ public void shouldMarkActualInvocationsAsVerifiedInOrder() {
}
@Test
- public void shouldReportTooLittleInvocationsInOrder() {
+ public void shouldReportTooFewInvocationsInOrder() {
InOrderContext context = new InOrderContextImpl();
//given
Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation();
@@ -70,12 +70,12 @@ public void shouldMarkActualInvocationsAsVerified() {
}
@Test
- public void shouldReportTooLittleInvocations() {
+ public void shouldReportTooFewInvocations() {
//given
Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation();
Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation();
- exception.expect(TooLittleActualInvocations.class);
+ exception.expect(TooFewActualInvocations.class);
exception.expectMessage("iMethods.simpleMethod()");
exception.expectMessage("Wanted *at least* 2 times");
exception.expectMessage("But was 1 time");
diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
index 61b2f2e7b4..9b44bf2286 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java
@@ -16,7 +16,7 @@
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.exceptions.verification.NeverWantedButInvoked;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.exceptions.verification.TooManyActualInvocations;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.invocation.InvocationMatcher;
@@ -45,11 +45,11 @@ public class NumberOfInvocationsCheckerTest {
public TestName testName = new TestName();
@Test
- public void shouldReportTooLittleActual() throws Exception {
+ public void shouldReportTooFewActual() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation());
- exception.expect(TooLittleActualInvocations.class);
+ exception.expect(TooFewActualInvocations.class);
exception.expectMessage("mock.simpleMethod()");
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 2 times");
@@ -62,7 +62,7 @@ public void shouldReportAllInvocationsStackTrace() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation());
- exception.expect(TooLittleActualInvocations.class);
+ exception.expect(TooFewActualInvocations.class);
exception.expectMessage("mock.simpleMethod()");
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 2 times");
@@ -76,7 +76,7 @@ public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() th
invocations = emptyList();
wanted = buildSimpleMethod().toInvocationMatcher();
- exception.expect(TooLittleActualInvocations.class);
+ exception.expect(TooFewActualInvocations.class);
exception.expectMessage("mock.simpleMethod()");
exception.expectMessage("Wanted 100 times");
exception.expectMessage("But was 0 times");
diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
index bc031ac904..573300c3c6 100644
--- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
+++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java
@@ -61,7 +61,7 @@ public void shouldPassIfChunkMatches() throws Exception {
}
@Test
- public void shouldReportTooLittleInvocations() throws Exception {
+ public void shouldReportTooFewInvocations() throws Exception {
Invocation first = buildSimpleMethod().toInvocation();
Invocation second = buildSimpleMethod().toInvocation();
@@ -89,7 +89,7 @@ public void shouldMarkAsVerifiedInOrder() throws Exception {
}
@Test
- public void shouldReportTooLittleActual() throws Exception {
+ public void shouldReportTooFewActual() throws Exception {
wanted = buildSimpleMethod().toInvocationMatcher();
invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation());
diff --git a/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java b/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java
index f22d7ac256..7b1f7968b9 100644
--- a/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java
+++ b/src/test/java/org/mockitousage/junitrunner/SilentRunnerTest.java
@@ -11,7 +11,7 @@
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.UnfinishedStubbingException;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockitousage.IMethods;
import org.mockitoutil.JUnitResultAssert;
@@ -42,7 +42,7 @@ public class SilentRunnerTest extends TestBase {
SomeFailingFeature.class
);
//then
- JUnitResultAssert.assertThat(result).fails(1, TooLittleActualInvocations.class);
+ JUnitResultAssert.assertThat(result).fails(1, TooFewActualInvocations.class);
}
@Test public void failing_test_in_constructor() {
diff --git a/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java b/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java
index 8603ca0510..a6bbe04d99 100644
--- a/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java
+++ b/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java
@@ -10,7 +10,7 @@
import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.NoInteractionsWanted;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.exceptions.verification.VerificationInOrderFailure;
import org.mockitoutil.TestBase;
@@ -141,7 +141,7 @@ public void shouldVerifyNumberOfTimesAndFail() {
try {
verify(spy, times(3)).add("one");
fail();
- } catch (TooLittleActualInvocations e) {}
+ } catch (TooFewActualInvocations e) {}
}
@Test
diff --git a/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java b/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java
index e1bd9afeef..14a7f35f12 100644
--- a/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/ModellingDescriptiveMessagesTest.java
@@ -59,7 +59,7 @@ public void shouldShowActualAndExpected() {
}
@Test
- public void shouldSayTooLittleInvocations() {
+ public void shouldSayTooFewInvocations() {
mock.simpleMethod();
verify(mock, times(2)).simpleMethod();
}
@@ -81,7 +81,7 @@ public void shouldSayWantedButNotInvokedInOrder() {
}
@Test
- public void shouldSayTooLittleInvocationsInOrder() {
+ public void shouldSayTooFewInvocationsInOrder() {
mock.simpleMethod();
mock.otherMethod();
mock.otherMethod();
@@ -108,7 +108,7 @@ public void shouldSayNeverWantedButInvokedHere() {
}
@Test
- public void shouldSayTooLittleInvocationsInAtLeastModeInOrder() {
+ public void shouldSayTooFewInvocationsInAtLeastModeInOrder() {
mock.simpleMethod();
InOrder inOrder = inOrder(mock);
@@ -116,7 +116,7 @@ public void shouldSayTooLittleInvocationsInAtLeastModeInOrder() {
}
@Test
- public void shouldSayTooLittleInvocationsInAtLeastMode() {
+ public void shouldSayTooFewInvocationsInAtLeastMode() {
mock.simpleMethod();
verify(mock, atLeast(2)).simpleMethod();
diff --git a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java
index cbb8334c74..5e907e2df2 100644
--- a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationChunkInOrderTest.java
@@ -79,7 +79,7 @@ public void shouldPointToThirdInteractionBecauseAtLeastOnceUsed() {
}
@Test
- public void shouldPointToThirdChunkWhenTooLittleActualInvocations() {
+ public void shouldPointToThirdChunkWhenTooFewActualInvocations() {
inOrder.verify(mock, times(2)).simpleMethod(anyInt());
inOrder.verify(mockTwo, times(2)).simpleMethod(anyInt());
inOrder.verify(mock, atLeastOnce()).simpleMethod(anyInt());
diff --git a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java
index 6e051114f9..61d7d3380d 100644
--- a/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java
+++ b/src/test/java/org/mockitousage/stacktrace/PointingStackTraceToActualInvocationInOrderTest.java
@@ -111,7 +111,7 @@ public void shouldPointToSecondMethodBecauseOfTooManyActualInvocations() {
}
@Test
- public void shouldPointToFourthMethodBecauseOfTooLittleActualInvocations() {
+ public void shouldPointToFourthMethodBecauseOfTooFewActualInvocations() {
inOrder.verify(mock).simpleMethod(anyInt());
inOrder.verify(mockTwo).simpleMethod(anyInt());
inOrder.verify(mock).simpleMethod(anyInt());
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
index ef7770542f..0953c24cf3 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesOnVerificationInOrderErrorsTest.java
@@ -163,7 +163,7 @@ public void shouldPrintTooManyInvocations() {
}
@Test
- public void shouldPrintTooLittleInvocations() {
+ public void shouldPrintTooFewInvocations() {
two.simpleMethod(2);
inOrder.verify(one, atLeastOnce()).simpleMethod(anyInt());
diff --git a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java
index 1d5bed03f5..c9740f0174 100644
--- a/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java
+++ b/src/test/java/org/mockitousage/verification/DescriptiveMessagesWhenTimesXVerificationFailsTest.java
@@ -8,7 +8,7 @@
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.exceptions.verification.TooManyActualInvocations;
import org.mockitoutil.TestBase;
@@ -33,7 +33,7 @@ public void shouldVerifyActualNumberOfInvocationsSmallerThanWanted() throws Exce
try {
Mockito.verify(mock, times(100)).clear();
fail();
- } catch (TooLittleActualInvocations e) {
+ } catch (TooFewActualInvocations e) {
assertThat(e)
.hasMessageContaining("mock.clear();")
.hasMessageContaining("Wanted 100 times")
diff --git a/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java b/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java
index 40d22709a4..d55fa8f1b2 100644
--- a/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java
+++ b/src/test/java/org/mockitousage/verification/ExactNumberOfTimesVerificationTest.java
@@ -28,7 +28,7 @@ public void setup() {
}
@Test
- public void shouldDetectTooLittleActualInvocations() throws Exception {
+ public void shouldDetectTooFewActualInvocations() throws Exception {
mock.clear();
mock.clear();
@@ -36,7 +36,7 @@ public void shouldDetectTooLittleActualInvocations() throws Exception {
try {
verify(mock, times(100)).clear();
fail();
- } catch (TooLittleActualInvocations e) {
+ } catch (TooFewActualInvocations e) {
assertThat(e)
.hasMessageContaining("Wanted 100 times")
.hasMessageContaining("was 2");
diff --git a/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java b/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java
index f1673695f1..c382df4367 100644
--- a/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java
+++ b/src/test/java/org/mockitousage/verification/SelectedMocksInOrderVerificationTest.java
@@ -138,7 +138,7 @@ public void shouldThrowNoMoreInvocationsForMockTwo() {
}
@Test
- public void shouldThrowTooLittleInvocationsForMockTwo() {
+ public void shouldThrowTooFewInvocationsForMockTwo() {
InOrder inOrder = inOrder(mockTwo);
try {
diff --git a/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java b/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java
index 1a3b3457f9..e41000d698 100644
--- a/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java
@@ -13,7 +13,7 @@
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
-import org.mockito.exceptions.verification.TooLittleActualInvocations;
+import org.mockito.exceptions.verification.TooFewActualInvocations;
import org.mockito.junit.MockitoRule;
import org.mockitousage.IMethods;
import org.mockitoutil.Stopwatch;
@@ -116,7 +116,7 @@ public void should_verify_with_times_x_and_fail() {
public void call() {
verify(mock, timeout(100).times(2)).oneArg('c');
}
- }).isInstanceOf(TooLittleActualInvocations.class);
+ }).isInstanceOf(TooFewActualInvocations.class);
}
@Test
@@ -150,7 +150,7 @@ public void should_verify_with_at_least_and_fail() {
public void call() {
verify(mock, timeout(100).atLeast(3)).oneArg('c');
}
- }).isInstanceOf(TooLittleActualInvocations.class);
+ }).isInstanceOf(TooFewActualInvocations.class);
}
@Test
| train | val | 2019-05-05T22:06:05 | "2019-02-18T11:22:32Z" | hdpe | train |
mockito/mockito/1717_1718 | mockito/mockito | mockito/mockito/1717 | mockito/mockito/1718 | [
"keyword_pr_to_issue"
] | 71603d46ebd8d1e35a55e4d54651b77ae46ccb49 | d86b9a33ee95eb87c95f86e2002ee7631a57b4d9 | [
"For reference, the change was introduced in JaCoCo with jacoco/jacoco#845."
] | [] | "2019-05-24T12:45:41Z" | [] | Incompatibility between the inline mocks and JaCoCo 0.8.4 | # Versions
Mockito 2.27.0
JaCoCo 0.8.4
# Problem
JaCoCo 0.8.4 introduced the use of the Conditional Dynamic instruction when running with Java 11+, which triggers an exception in the [`MethodVisitor`](https://github.com/mockito/mockito/blob/v2.27.0/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java#L314) used to strip the parameters, because it's not configured for the correct ASM API version:
Mockito cannot mock this class: class com.ekino.mockito.B.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 11
JVM vendor name : AdoptOpenJDK
JVM vendor version : 11.0.3+7
JVM name : OpenJDK 64-Bit Server VM
JVM version : 11.0.3+7
JVM info : mixed mode
OS name : Mac OS X
OS version : 10.14.5
You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.
Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [class java.lang.Object, class com.ekino.mockito.B]
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.ekino.mockito.B.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 11
JVM vendor name : AdoptOpenJDK
JVM vendor version : 11.0.3+7
JVM name : OpenJDK 64-Bit Server VM
JVM version : 11.0.3+7
JVM info : mixed mode
OS name : Mac OS X
OS version : 10.14.5
You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.
Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [class java.lang.Object, class com.ekino.mockito.B]
at com.ekino.mockito.ATest.should_call_b(ATest.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:102)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:82)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:78)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy5.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [class java.lang.Object, class com.ekino.mockito.B]
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
... 77 more
Caused by: java.lang.IllegalStateException:
Byte Buddy could not instrument all classes within the mock's type hierarchy
This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:
- Compiled by older versions of scalac
- Classes that are part of the Android distribution
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:177)
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.mockClass(InlineBytecodeGenerator.java:153)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMockType(InlineByteBuddyMockMaker.java:197)
at org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker.createMock(InlineByteBuddyMockMaker.java:178)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:62)
at org.mockito.Mockito.mock(Mockito.java:1907)
at org.mockito.Mockito.mock(Mockito.java:1816)
... 77 more
Caused by: java.lang.UnsupportedOperationException: This feature requires ASM7
at net.bytebuddy.jar.asm.MethodVisitor.visitLdcInsn(MethodVisitor.java:542)
at net.bytebuddy.jar.asm.ClassReader.readCode(ClassReader.java:2181)
at net.bytebuddy.jar.asm.ClassReader.readMethod(ClassReader.java:1275)
at net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:679)
at net.bytebuddy.jar.asm.ClassReader.accept(ClassReader.java:391)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForInlining.create(TypeWriter.java:3393)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1930)
at net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder.make(RedefinitionDynamicTypeBuilder.java:217)
at net.bytebuddy.dynamic.scaffold.inline.AbstractInliningDynamicTypeBuilder.make(AbstractInliningDynamicTypeBuilder.java:120)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:3396)
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.transform(InlineBytecodeGenerator.java:254)
at java.instrument/java.lang.instrument.ClassFileTransformer.transform(ClassFileTransformer.java:246)
at java.instrument/sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at java.instrument/sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:563)
at java.instrument/sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at java.instrument/sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:167)
at org.mockito.internal.creation.bytebuddy.InlineBytecodeGenerator.triggerRetransformation(InlineBytecodeGenerator.java:174)
... 91 more
# Example
I've pushed an [example](https://github.com/fpavageau/mockito-jacoco-condy) demonstrating the problem.
# Fix
I believe the fix is simply to configure the visitor with the ASM 7 API version, since that _is_ the version used by Mockito. | [
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java"
] | [
"src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java"
] | [
"src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java"
] | diff --git a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
index e160e3cb2d..34b1e89855 100644
--- a/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
+++ b/src/main/java/org/mockito/internal/creation/bytebuddy/InlineBytecodeGenerator.java
@@ -20,7 +20,6 @@
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.jar.asm.ClassVisitor;
import net.bytebuddy.jar.asm.MethodVisitor;
-import net.bytebuddy.jar.asm.Opcodes;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.pool.TypePool;
import net.bytebuddy.utility.OpenedClassReader;
@@ -311,7 +310,7 @@ public MethodVisitor visitMethod(int access, String name, String desc, String si
private static class MethodParameterStrippingMethodVisitor extends MethodVisitor {
public MethodParameterStrippingMethodVisitor(MethodVisitor mv) {
- super(Opcodes.ASM5, mv);
+ super(OpenedClassReader.ASM_API, mv);
}
@Override
| 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 eebdb962d7..7d3647e6e8 100644
--- a/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
+++ b/src/test/java/org/mockito/internal/creation/bytebuddy/InlineByteBuddyMockMakerTest.java
@@ -8,7 +8,9 @@
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.description.type.TypeDescription;
+import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.StubMethod;
+import net.bytebuddy.utility.JavaConstant;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.creation.MockSettingsImpl;
@@ -25,9 +27,11 @@
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
+import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import static net.bytebuddy.ClassFileVersion.JAVA_V8;
+import static net.bytebuddy.ClassFileVersion.JAVA_V11;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
@@ -291,6 +295,25 @@ public void test_parameters_retention() throws Exception {
.getOnly().getParameters().getOnly().getName()).isEqualTo("bar");
}
+ @Test
+ public void test_constant_dynamic_compatibility() throws Exception {
+ assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V11));
+
+ Class<?> typeWithCondy = new ByteBuddy()
+ .subclass(Callable.class)
+ .method(named("call"))
+ .intercept(FixedValue.value(JavaConstant.Dynamic.ofNullConstant()))
+ .make()
+ .load(null)
+ .getLoaded();
+
+ MockCreationSettings<?> settings = settingsFor(typeWithCondy);
+ @SuppressWarnings("unchecked")
+ Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
+
+ assertThat(proxy.getClass()).isEqualTo(typeWithCondy);
+ }
+
@Test
public void test_clear_mock_clears_handler() {
MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);
| train | val | 2019-05-24T21:17:40 | "2019-05-24T12:36:19Z" | fpavageau | train |
mockito/mockito/1655_1783 | mockito/mockito | mockito/mockito/1655 | mockito/mockito/1783 | [
"keyword_pr_to_issue"
] | 98e8743b6b5c0cca64cf3cb3c46a9b96b25fd9b6 | 28bce89b411ffb58387b3208acfae43a31022172 | [
"Any thoughts on this one? I'm just curious to know."
] | [] | "2019-09-25T00:53:55Z" | [] | Stubbing not stopped properly when running suite of tests | Hey,
I'm not sure the title describes the problem in the best way but I found the following.
Consider the two tests:
```java
public class MockitoMisusingUnitTest {
@Test
public void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
try {
List<String> list = new ArrayList<String>();
Mockito.doReturn(100, Mockito.withSettings().lenient())
.when(list)
.size();
fail("Should have thrown a NotAMockException because 'list' is not a mock!");
} catch (NotAMockException e) {
assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!"));
}
}
}
```
```java
@RunWith(MockitoJUnitRunner.class)
public class MockitoVoidMethodsUnitTest {
@Test
public void whenAddCalledValueCaptured() {
ArrayList<String> mockVoid = mock(ArrayList.class);
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture());
mockVoid.add(0, "captured");
assertEquals("captured", valueCapture.getValue());
}
}
```
When run independently pass. When run together from eclipse or mvn the second test `MockitoVoidMethodsUnitTest.whenAddCalledValueCaptured` fails but because of something detected in the other test:
```
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.baeldung.mockito.misusing.MockitoMisusingUnitTest.givenNotASpy_whenDoReturn_thenThrowNotAMock(MockitoMisusingUnitTest.java:28)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
-> at org.baeldung.mockito.MockitoVoidMethodsUnitTest.whenAddCalledValueCaptured(MockitoVoidMethodsUnitTest.java:30)
```
This is the call stack:
```
MockingProgressImpl.validateState() line: 109
MockingProgressImpl.stubbingStarted() line: 98
MockitoCore.stubber(Strictness) line: 179
MockitoCore.stubber() line: 174
Mockito.doNothing() line: 2421
MockitoVoidMethodsUnitTest.whenAddCalledValueCaptured() line: 30
```
And the method where it then fails inside `MockingProgress.java`:
```java
public void validateState() {
validateMostStuff();
//validate stubbing:
if (stubbingInProgress != null) {
Location temp = stubbingInProgress;
stubbingInProgress = null;
throw unfinishedStubbing(temp);
}
}
```
I think this is a bug, tests should be independent and not cause side affects on each other. Maybe something is not cleaned up properly between test runs.
If I add this tear down to `MockitoMisusingUnitTest` then it works ok:
```java
@After
public void tearDown() {
ThreadSafeMockingProgress.mockingProgress().reset();
}
```
I don't mind to have a go at fixing it, but I would need some help or hints. This was tested with the latest version 2.24.5.
Thanks | [
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java"
] | [
"src/main/java/org/mockito/internal/stubbing/StubberImpl.java"
] | [
"src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java"
] | diff --git a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
index 5a599c78aa..84f1e3c2e5 100644
--- a/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
+++ b/src/main/java/org/mockito/internal/stubbing/StubberImpl.java
@@ -4,6 +4,7 @@
*/
package org.mockito.internal.stubbing;
+import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.stubbing.answers.CallsRealMethods;
import org.mockito.internal.stubbing.answers.Returns;
import org.mockito.internal.stubbing.answers.ThrowsException;
@@ -15,7 +16,6 @@
import java.util.LinkedList;
import java.util.List;
-import org.mockito.internal.configuration.plugins.Plugins;
import static org.mockito.internal.exceptions.Reporter.notAMockPassedToWhenMethod;
import static org.mockito.internal.exceptions.Reporter.notAnException;
import static org.mockito.internal.exceptions.Reporter.nullPassedToWhenMethod;
@@ -36,10 +36,12 @@ public StubberImpl(Strictness strictness) {
@Override
public <T> T when(T mock) {
if (mock == null) {
+ mockingProgress().reset();
throw nullPassedToWhenMethod();
}
if (!isMock(mock)) {
+ mockingProgress().reset();
throw notAMockPassedToWhenMethod();
}
| diff --git a/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java b/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java
new file mode 100644
index 0000000000..2e5bf26d2c
--- /dev/null
+++ b/src/test/java/org/mockitousage/stubbing/MisusingStubbingTest.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitousage.stubbing;
+
+import org.junit.Test;
+import org.mockitoutil.TestBase;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.validateMockitoUsage;
+
+public class MisusingStubbingTest extends TestBase {
+
+ @Test
+ public void clean_state_after_not_a_mock() {
+ //when
+ assertThatThrownBy(() ->
+ doReturn(100).when("not a mock"));
+
+ //then
+ validateMockitoUsage();
+ }
+
+ @Test
+ public void clean_state_after_null_passed() {
+ //when
+ assertThatThrownBy(() ->
+ doReturn(100).when(null));
+
+ //then
+ validateMockitoUsage();
+ }
+}
| train | val | 2019-09-17T17:13:23 | "2019-03-05T22:45:40Z" | JonCook | train |
mockito/mockito/1786_1787 | mockito/mockito | mockito/mockito/1786 | mockito/mockito/1787 | [
"keyword_pr_to_issue"
] | 16328dbe6562056d382cd5aa7cba0d6695de9665 | f8581c6e875dc3fb587fe31e85d025ef4d110a3f | [] | [] | "2019-09-27T20:03:05Z" | [] | Difference between 'timeout' and 'after' not immediately clear | The first few lines of the JavaDoc for both methods do not exactly specify their difference. From `timeout` you have to jump to `after` where at the end of the JavaDoc the difference is explained.
I think this can be improved. The first sentence in `timeout` could be more specific to highlight the difference directly. | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 786b716a51..2f247045a2 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -2820,14 +2820,13 @@ public static VerificationMode only() {
}
/**
- * Verification will be triggered after given amount of millis, allowing testing of async code.
+ * Verification will be triggered over and over until the given amount of millis, allowing testing of async code.
* Useful when interactions with the mock object did not happened yet.
- * Extensive use of after() method can be a code smell - there are better ways of testing concurrent code.
+ * Extensive use of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code.
* <p>
* See also {@link #after(long)} method for testing async code.
* Differences between {@code timeout()} and {@code after} are explained in Javadoc for {@link #after(long)}.
- * <p>
- * Extensive use of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code.
+ *
* <pre class="code"><code class="java">
* //passes when someMethod() is called no later than within 100 ms
* //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
@@ -2856,7 +2855,7 @@ public static VerificationWithTimeout timeout(long millis) {
/**
* Verification will be triggered after given amount of millis, allowing testing of async code.
* Useful when interactions with the mock object did not happened yet.
- * Extensive use of after() method can be a code smell - there are better ways of testing concurrent code.
+ * Extensive use of {@code after()} method can be a code smell - there are better ways of testing concurrent code.
* <p>
* Not yet implemented to work with InOrder verification.
* <p>
| null | train | val | 2019-09-25T17:00:40 | "2019-09-27T19:58:25Z" | SimplyDanny | train |
mockito/mockito/1630_1788 | mockito/mockito | mockito/mockito/1630 | mockito/mockito/1788 | [
"keyword_pr_to_issue"
] | 16328dbe6562056d382cd5aa7cba0d6695de9665 | 112919971c0a985b0918a2e0c29b145c14e0d7d8 | [
"Hey! Can you take a look at our FAQ wiki. We documented how Mockito supports parallel execution.",
"I took a look at the wiki, but found just a very short section about parallel testing in the FAQ section. I issued the bug, because the parallel execution of whole test cases with JUnit 5 seems to be broken. I do not have any complex tests which use mocks in combination with multithreading.\r\n\r\nAnyway this seems to be a problem of the MockitoExtension, not Mockito itself. Because with our simple JUnit 5 extension for Mockito, parallel execution of test cases which use mocks with JUnit 5 works fine.",
"I got a similar issue. \r\nI have got a workaround, if only a few of your \"Mockito\"-test-classes in you testsuite are failing when running JUnit jupiter in parallel. You can execute those problematic tests using \"SAME_THREAD\" for avoiding Mockito concurrency issues.\r\n\r\n```\r\nimport org.junit.jupiter.api.extension.ExtendWith;\r\nimport org.junit.jupiter.api.parallel.Execution;\r\nimport org.junit.jupiter.api.parallel.ExecutionMode;\r\nimport org.mockito.junit.jupiter.MockitoExtension;\r\n\r\n@ExtendWith(MockitoExtension.class)\r\n@Execution(ExecutionMode.SAME_THREAD) // <--- Workaround\r\nclass SomeTest {\r\n```",
"To be a bit more specific, WantedButNotInvoked exceptions are thrown by verification calls failing, because of not recorded invocations: \"Actually, there were zero interactions with this mock.\".",
"The main difference between the current and the simple implementation above is, that the simple one inits the mocks in postProcessTestInstance() whereas the current one inits them in beforeEach(). Any ideas why that might be a problem? \r\n\r\nI tried the failing tests with a modified version of the current MockitoExtension which was just altered to init the mocks in postProcessTestInstance() and disabled the init in beforeEach() and the tests do no longer fail. So this seems to be the source of the problems.",
"Hey guys, can you provide us a test that reproduces the problem? Thanks!",
"@mockitoguy Here you go: https://github.com/SchulteMarkus/mockito.bug1630\r\n\r\nI am not sure, if I reduced the example as much as possible, but, well, the project is not large.",
"Thank you! The sample project looks great!\r\n\r\nI looked at the code but I haven't had time to debug it. How does the JUnit5 parallel execution work? Are we sharing the test instance (and thus, sharing mocks, SUTs?).",
"You are welcome :-) \r\nI don't know details about JUnit's parallelization.",
"> How does the JUnit5 parallel execution work? Are we sharing the test instance (and thus, sharing mocks, SUTs?).\r\n\r\nBy default not, and the user must be very explicit to enable sharing of the same test class instance with parallel execution enabled. I.e., even if parallel execution mode is enabled by default, and a test class is annotated with `Lifecycle.PER_CLASS`, its tests will still be executed sequentially _unless_ it is also annotated with `@Execution(CONCURRENT)`: https://junit.org/junit5/docs/current/user-guide/#writing-tests-parallel-execution\r\n\r\nI also bumped into this issue in our codebase, with some tests using `MockitoExtension` failing in parallel mode, and some working fine. Could not spot anything particularly special about the failing ones.\r\n",
"I can confirm, that the problem exists. I also have tests using MockitoExtension and they fail in a non-deterministic way randomly only if Junit5 parralelization is used.",
"Scenario:\r\n\r\n1. JUnit 5 creates a single `ClassExtensionContext `for a multithreaded test, but each thread becomes an instance of the test class\r\n2. Each thread will come into `postProcessTestInstance `where they put their test instance in the same `ClassExtensionContext.getStore(MOCKITO)` map with the same key (`TEST_INSTANCE`)\r\n3. Each thread then will get into `beforeEach`. They get a thread unique `MethodExtensionContext`, but each of them contain the same instance of `ClassExtensionContext`. Then they fetch the the last updated `TEST_INSTANCE `from the parent `ClassExtensionContext `inside the `collectParentTestInstances `method. Each thread gets quasi a random Test Instance depending on the fact which thread was before inside the `postProcessTestInstance `method. Then they prepare their broken Session inside the store of the current `MethodExtensionContext `with a random Test Instance included.\r\n\r\nThat is the explanation. I am thinking about how to solve this.\r\n\r\nIt is not 100% clear to me why the parent context test instance is included. I will check how this scenario looks like in a singlethreaded environment.",
"This is really painful to debug but I'm making progress. What I found out is that \"collectParentTestInstances()\" is non-deterministic:\r\n\r\n```\r\nThread[16] collectParentTestInstances() - returns: [org.mockito.AnotherTest@2bf588f6]\r\nThread[13] collectParentTestInstances() - returns: [org.mockito.AnotherTest@240da1f5, org.mockito.AnotherTest@6646267a]\r\nThread[17] collectParentTestInstances() - returns: [org.mockito.AnotherTest@6646267a]\r\nThread[14] collectParentTestInstances() - returns: [org.mockito.AnotherTest@f9b9d48]\r\n```\r\n\r\nNotice that AnotherTest@6646267a is processed twice. Effectively, initMocks() is called twice for that test instance, clearing up the invocations.\r\n\r\nDo you have an idea how to fix collectParentTestInstances()?",
"Perhaps we drop the collectParentTestInstances() complexity and just keep the test instances in static ThreadLocal object in the extension. postProcessTestInstance() feeds the thread local state, beforeEach() consumes it. I don't know enough about the \"context store\" API, though.",
"I have a plan how to fix it. First, we need to upgrade junit-jupiter (#1788)",
"@mockitoguy I am not sure why you have closed the issue. In the attached commit I cannot see the fix for the problem.\r\n\r\nContext store API seems to be pretty simple to me, it is just a map in the context to store some information. The real question is what is this kind of context hierarchy used for in Junit 5 and how it behaves in case of nested tests or multithreaded tests, or even in multithreaded nested tests. I guess it could have some interesting beahaviour in case of parameterized (dynamic) tests. Probably it would be a good idea simply to ask the JUnit developers about this issue. Maybe they could provide some valuable feedback.",
"PR #1789 fixes the problem. This ticket got closed by accident. Thanks for looking into it!",
"Looking forward to the next release!\r\nI would like to confirm the bug is gone, but I don't know how to do it in https://github.com/SchulteMarkus/mockito.bug1630.\r\nCan someone add a PR to https://github.com/SchulteMarkus/mockito.bug1630 using Mockito 3.0.12 (at least)? ",
"Release have been already published. See https://bintray.com/mockito/maven/mockito-development",
"@mockitoguy when will this fix be released to maven central?",
"I will publish a release today",
"I updated https://github.com/SchulteMarkus/mockito.bug1630 - seems to work without problems using Mockito v.3.1.0, thanks a lot!\r\nI will delete https://github.com/SchulteMarkus/mockito.bug1630 within a few weeks.",
"Publish to Maven Central failed yet again. I will need to contact sonatype again...",
"(Although https://repo1.maven.org/maven2/org/mockito/mockito-core/3.1.0/ does exist, so it might just work)",
"I can confirm, that the solution of 3.1.0 version works for all of the tests in my project. Still I don't understand how JUnit works, but it is fine now, since the tests work.\r\n\r\nThanks for your fast fix & release!"
] | [] | "2019-09-28T01:31:15Z" | [
"junit5"
] | Mockito JUnit Jupiter extension does not correctly support parallel test execution | Sorry for not being able to provide the required information, but we just noticed that the MockitoExtension (mockito-junit-jupiter 2.24.5) leads to spurious test failures (e.g. due to calls to mocks not being recorded) when using "junit.jupiter.execution.parallel.enabled=true" with surefire. Prior we used our much simpler MockitoExtension which works fine in the same situation:
```java
public class MockitoExtension implements Extension, TestInstancePostProcessor, AfterEachCallback {
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
MockitoAnnotations.initMocks(testInstance);
}
@Override
public void afterEach(ExtensionContext extensionContext) throws Exception {
Mockito.validateMockitoUsage();
}
}
``` | [
"gradle/dependencies.gradle"
] | [
"gradle/dependencies.gradle"
] | [
"subprojects/junit-jupiter/src/test/java/org/mockitousage/MultiLevelNestedTest.java"
] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index 7ac37ad658..2626d222e0 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -5,7 +5,7 @@ ext {
def versions = [:]
versions.bytebuddy = '1.9.10'
-versions.junitJupiter = '5.1.1'
+versions.junitJupiter = '5.4.2'
versions.errorprone = '2.3.2'
libraries.junit4 = 'junit:junit:4.12'
| diff --git a/subprojects/junit-jupiter/src/test/java/org/mockitousage/MultiLevelNestedTest.java b/subprojects/junit-jupiter/src/test/java/org/mockitousage/MultiLevelNestedTest.java
new file mode 100644
index 0000000000..58a42f97e4
--- /dev/null
+++ b/subprojects/junit-jupiter/src/test/java/org/mockitousage/MultiLevelNestedTest.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2018 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockitousage;
+
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@ExtendWith(MockitoExtension.class)
+class MultiLevelNestedTest {
+
+ @Mock
+ private Runnable level1Mock;
+
+ @Nested
+ class Level2Class {
+ @Mock Runnable level2Mock;
+
+ @Test
+ void mocks_created() {
+ assertThat(level1Mock).isNotNull();
+ assertThat(level2Mock).isNotNull();
+ }
+
+ @Nested
+ class Level3Class {
+ @Mock Runnable level3Mock;
+
+ @Test
+ void mocks_created() {
+ assertThat(level1Mock).isNotNull();
+ assertThat(level2Mock).isNotNull();
+ assertThat(level3Mock).isNotNull();
+ }
+ }
+ }
+}
| test | val | 2019-09-25T17:00:40 | "2019-02-25T12:54:15Z" | markusheiden | train |
mockito/mockito/1630_1789 | mockito/mockito | mockito/mockito/1630 | mockito/mockito/1789 | [
"keyword_issue_to_pr",
"keyword_pr_to_issue"
] | 214d4652aa1971cb554c434b0ac13b376aea33a7 | 30c50fa3442004996dc9c7b2bcfdae7aaaae3ce6 | [
"Hey! Can you take a look at our FAQ wiki. We documented how Mockito supports parallel execution.",
"I took a look at the wiki, but found just a very short section about parallel testing in the FAQ section. I issued the bug, because the parallel execution of whole test cases with JUnit 5 seems to be broken. I do not have any complex tests which use mocks in combination with multithreading.\r\n\r\nAnyway this seems to be a problem of the MockitoExtension, not Mockito itself. Because with our simple JUnit 5 extension for Mockito, parallel execution of test cases which use mocks with JUnit 5 works fine.",
"I got a similar issue. \r\nI have got a workaround, if only a few of your \"Mockito\"-test-classes in you testsuite are failing when running JUnit jupiter in parallel. You can execute those problematic tests using \"SAME_THREAD\" for avoiding Mockito concurrency issues.\r\n\r\n```\r\nimport org.junit.jupiter.api.extension.ExtendWith;\r\nimport org.junit.jupiter.api.parallel.Execution;\r\nimport org.junit.jupiter.api.parallel.ExecutionMode;\r\nimport org.mockito.junit.jupiter.MockitoExtension;\r\n\r\n@ExtendWith(MockitoExtension.class)\r\n@Execution(ExecutionMode.SAME_THREAD) // <--- Workaround\r\nclass SomeTest {\r\n```",
"To be a bit more specific, WantedButNotInvoked exceptions are thrown by verification calls failing, because of not recorded invocations: \"Actually, there were zero interactions with this mock.\".",
"The main difference between the current and the simple implementation above is, that the simple one inits the mocks in postProcessTestInstance() whereas the current one inits them in beforeEach(). Any ideas why that might be a problem? \r\n\r\nI tried the failing tests with a modified version of the current MockitoExtension which was just altered to init the mocks in postProcessTestInstance() and disabled the init in beforeEach() and the tests do no longer fail. So this seems to be the source of the problems.",
"Hey guys, can you provide us a test that reproduces the problem? Thanks!",
"@mockitoguy Here you go: https://github.com/SchulteMarkus/mockito.bug1630\r\n\r\nI am not sure, if I reduced the example as much as possible, but, well, the project is not large.",
"Thank you! The sample project looks great!\r\n\r\nI looked at the code but I haven't had time to debug it. How does the JUnit5 parallel execution work? Are we sharing the test instance (and thus, sharing mocks, SUTs?).",
"You are welcome :-) \r\nI don't know details about JUnit's parallelization.",
"> How does the JUnit5 parallel execution work? Are we sharing the test instance (and thus, sharing mocks, SUTs?).\r\n\r\nBy default not, and the user must be very explicit to enable sharing of the same test class instance with parallel execution enabled. I.e., even if parallel execution mode is enabled by default, and a test class is annotated with `Lifecycle.PER_CLASS`, its tests will still be executed sequentially _unless_ it is also annotated with `@Execution(CONCURRENT)`: https://junit.org/junit5/docs/current/user-guide/#writing-tests-parallel-execution\r\n\r\nI also bumped into this issue in our codebase, with some tests using `MockitoExtension` failing in parallel mode, and some working fine. Could not spot anything particularly special about the failing ones.\r\n",
"I can confirm, that the problem exists. I also have tests using MockitoExtension and they fail in a non-deterministic way randomly only if Junit5 parralelization is used.",
"Scenario:\r\n\r\n1. JUnit 5 creates a single `ClassExtensionContext `for a multithreaded test, but each thread becomes an instance of the test class\r\n2. Each thread will come into `postProcessTestInstance `where they put their test instance in the same `ClassExtensionContext.getStore(MOCKITO)` map with the same key (`TEST_INSTANCE`)\r\n3. Each thread then will get into `beforeEach`. They get a thread unique `MethodExtensionContext`, but each of them contain the same instance of `ClassExtensionContext`. Then they fetch the the last updated `TEST_INSTANCE `from the parent `ClassExtensionContext `inside the `collectParentTestInstances `method. Each thread gets quasi a random Test Instance depending on the fact which thread was before inside the `postProcessTestInstance `method. Then they prepare their broken Session inside the store of the current `MethodExtensionContext `with a random Test Instance included.\r\n\r\nThat is the explanation. I am thinking about how to solve this.\r\n\r\nIt is not 100% clear to me why the parent context test instance is included. I will check how this scenario looks like in a singlethreaded environment.",
"This is really painful to debug but I'm making progress. What I found out is that \"collectParentTestInstances()\" is non-deterministic:\r\n\r\n```\r\nThread[16] collectParentTestInstances() - returns: [org.mockito.AnotherTest@2bf588f6]\r\nThread[13] collectParentTestInstances() - returns: [org.mockito.AnotherTest@240da1f5, org.mockito.AnotherTest@6646267a]\r\nThread[17] collectParentTestInstances() - returns: [org.mockito.AnotherTest@6646267a]\r\nThread[14] collectParentTestInstances() - returns: [org.mockito.AnotherTest@f9b9d48]\r\n```\r\n\r\nNotice that AnotherTest@6646267a is processed twice. Effectively, initMocks() is called twice for that test instance, clearing up the invocations.\r\n\r\nDo you have an idea how to fix collectParentTestInstances()?",
"Perhaps we drop the collectParentTestInstances() complexity and just keep the test instances in static ThreadLocal object in the extension. postProcessTestInstance() feeds the thread local state, beforeEach() consumes it. I don't know enough about the \"context store\" API, though.",
"I have a plan how to fix it. First, we need to upgrade junit-jupiter (#1788)",
"@mockitoguy I am not sure why you have closed the issue. In the attached commit I cannot see the fix for the problem.\r\n\r\nContext store API seems to be pretty simple to me, it is just a map in the context to store some information. The real question is what is this kind of context hierarchy used for in Junit 5 and how it behaves in case of nested tests or multithreaded tests, or even in multithreaded nested tests. I guess it could have some interesting beahaviour in case of parameterized (dynamic) tests. Probably it would be a good idea simply to ask the JUnit developers about this issue. Maybe they could provide some valuable feedback.",
"PR #1789 fixes the problem. This ticket got closed by accident. Thanks for looking into it!",
"Looking forward to the next release!\r\nI would like to confirm the bug is gone, but I don't know how to do it in https://github.com/SchulteMarkus/mockito.bug1630.\r\nCan someone add a PR to https://github.com/SchulteMarkus/mockito.bug1630 using Mockito 3.0.12 (at least)? ",
"Release have been already published. See https://bintray.com/mockito/maven/mockito-development",
"@mockitoguy when will this fix be released to maven central?",
"I will publish a release today",
"I updated https://github.com/SchulteMarkus/mockito.bug1630 - seems to work without problems using Mockito v.3.1.0, thanks a lot!\r\nI will delete https://github.com/SchulteMarkus/mockito.bug1630 within a few weeks.",
"Publish to Maven Central failed yet again. I will need to contact sonatype again...",
"(Although https://repo1.maven.org/maven2/org/mockito/mockito-core/3.1.0/ does exist, so it might just work)",
"I can confirm, that the solution of 3.1.0 version works for all of the tests in my project. Still I don't understand how JUnit works, but it is fine now, since the tests work.\r\n\r\nThanks for your fast fix & release!"
] | [
"Instead of having a boolean here, can we pass in `context.getParent()` on line 164. E.g. we pass the first parent in already, but then we keep all the other logic the same. That seems a little bit nicer to me and easier to follow. The comment can then be placed before line 164 instead.",
"Please push a commit to this branch - it's simpler!",
"Sadly I am not at my working computer. I can do a push on Monday if you prefer.",
"This works :-) Push on Monday. Have a nice weekend!",
"Done PTAL"
] | "2019-09-28T22:08:17Z" | [
"junit5"
] | Mockito JUnit Jupiter extension does not correctly support parallel test execution | Sorry for not being able to provide the required information, but we just noticed that the MockitoExtension (mockito-junit-jupiter 2.24.5) leads to spurious test failures (e.g. due to calls to mocks not being recorded) when using "junit.jupiter.execution.parallel.enabled=true" with surefire. Prior we used our much simpler MockitoExtension which works fine in the same situation:
```java
public class MockitoExtension implements Extension, TestInstancePostProcessor, AfterEachCallback {
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) {
MockitoAnnotations.initMocks(testInstance);
}
@Override
public void afterEach(ExtensionContext extensionContext) throws Exception {
Mockito.validateMockitoUsage();
}
}
``` | [
"settings.gradle.kts",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java"
] | [
"settings.gradle.kts",
"subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java",
"subprojects/junitJupiterParallelTest/junitJupiterParallelTest.gradle"
] | [
"subprojects/junitJupiterParallelTest/src/test/java/org/mockito/ParallelBugTest.java",
"subprojects/junitJupiterParallelTest/src/test/resources/junit-platform.properties"
] | diff --git a/settings.gradle.kts b/settings.gradle.kts
index d57b84e560..dc31ca1f32 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -8,7 +8,8 @@ include("deprecatedPluginsTest",
"junitJupiterExtensionTest",
"module-test",
"memory-test",
- "errorprone")
+ "errorprone",
+ "junitJupiterParallelTest")
rootProject.name = "mockito"
diff --git a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
index 9b90a7d16e..9f697eae8d 100644
--- a/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
+++ b/subprojects/junit-jupiter/src/main/java/org/mockito/junit/jupiter/MockitoExtension.java
@@ -5,25 +5,30 @@
package org.mockito.junit.jupiter;
-import org.junit.jupiter.api.extension.*;
+import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
+import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
+
+import java.lang.reflect.Parameter;
+import java.util.LinkedHashSet;
+import java.util.Optional;
+import java.util.Set;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
+import org.junit.jupiter.api.extension.ParameterContext;
+import org.junit.jupiter.api.extension.ParameterResolutionException;
+import org.junit.jupiter.api.extension.ParameterResolver;
+import org.junit.jupiter.api.extension.TestInstancePostProcessor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoSession;
+import org.mockito.internal.configuration.MockAnnotationProcessor;
import org.mockito.internal.configuration.plugins.Plugins;
import org.mockito.internal.session.MockitoSessionLoggerAdapter;
-import org.mockito.internal.configuration.MockAnnotationProcessor;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.quality.Strictness;
-import java.lang.reflect.Parameter;
-import java.util.LinkedHashSet;
-import java.util.Optional;
-import java.util.Set;
-
-import static org.junit.jupiter.api.extension.ExtensionContext.Namespace.create;
-import static org.junit.platform.commons.support.AnnotationSupport.findAnnotation;
-
/**
* Extension that initializes mocks and handles strict stubbings. This extension is the JUnit Jupiter equivalent
* of our JUnit4 {@link MockitoJUnitRunner}.
@@ -188,19 +193,30 @@ private Optional<MockitoSettings> retrieveAnnotationFromTestClasses(final Extens
}
private void collectParentTestInstances(ExtensionContext context, Set<Object> testInstances) {
- Optional<ExtensionContext> parent = context.getParent();
+ Optional<ExtensionContext> initialParent = context.getParent();
- while (parent.isPresent() && parent.get() != context.getRoot()) {
- ExtensionContext parentContext = parent.get();
+ // Ignoring first parent avoids parallel execution issues
+ // We can ignore the first parent because it has the test instance that is already in 'testInstances'
+ // See how 'testInstances' is populated
+ initialParent.ifPresent(parent -> collectParentTestInstance(parent.getParent(), context, testInstances));
+ }
- Object testInstance = parentContext.getStore(MOCKITO).remove(TEST_INSTANCE);
+ @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
+ private void collectParentTestInstance(
+ Optional<ExtensionContext> parent, ExtensionContext context,
+ Set<Object> testInstances) {
- if (testInstance != null) {
- testInstances.add(testInstance);
- }
+ parent.ifPresent(currentParent -> {
+ if (currentParent != context.getRoot()) {
+ Object testInstance = currentParent.getStore(MOCKITO).remove(TEST_INSTANCE);
- parent = parentContext.getParent();
- }
+ if (testInstance != null) {
+ testInstances.add(testInstance);
+ }
+
+ collectParentTestInstance(currentParent.getParent(), context, testInstances);
+ }
+ });
}
/**
diff --git a/subprojects/junitJupiterParallelTest/junitJupiterParallelTest.gradle b/subprojects/junitJupiterParallelTest/junitJupiterParallelTest.gradle
new file mode 100644
index 0000000000..6da4f3b4d7
--- /dev/null
+++ b/subprojects/junitJupiterParallelTest/junitJupiterParallelTest.gradle
@@ -0,0 +1,15 @@
+description = "Tests that require fine tuned parallel settings for JUnit Jupiter (bug #1630)"
+
+apply from: "$rootDir/gradle/dependencies.gradle"
+
+apply plugin: "java"
+
+dependencies {
+ testImplementation libraries.junitJupiterApi
+ testImplementation project(":junit-jupiter")
+ testRuntime libraries.junitJupiterEngine
+}
+
+test {
+ useJUnitPlatform()
+}
| diff --git a/subprojects/junitJupiterParallelTest/src/test/java/org/mockito/ParallelBugTest.java b/subprojects/junitJupiterParallelTest/src/test/java/org/mockito/ParallelBugTest.java
new file mode 100644
index 0000000000..e3e1f8bb40
--- /dev/null
+++ b/subprojects/junitJupiterParallelTest/src/test/java/org/mockito/ParallelBugTest.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2019 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+/**
+ * See bug #1630
+ */
+@ExtendWith(MockitoExtension.class)
+class ParallelBugTest {
+
+ @Mock
+ private SomeService someService;
+
+ @InjectMocks
+ private AnotherService anotherService;
+
+ @Test
+ void test() {
+ perform();
+ }
+
+ private void perform() {
+ // when
+ anotherService.callSomeService();
+
+ // then
+ Mockito.verify(someService).doSomething();
+ }
+
+ @Test
+ void test2() {
+ perform();
+ }
+
+ @Test
+ void test3() {
+ perform();
+ }
+
+ @Test
+ void test4() {
+ perform();
+ }
+
+ @Test
+ void test5() {
+ perform();
+ }
+
+ @Test
+ void test6() {
+ perform();
+ }
+
+ @Test
+ void test7() {
+ perform();
+ }
+
+ public static class AnotherService {
+ private final SomeService someService;
+
+ public AnotherService(final SomeService someService) {
+ this.someService = someService;
+ }
+
+ void callSomeService() {
+ someService.doSomething();
+ }
+ }
+
+ static class SomeService {
+
+ void doSomething() {
+ }
+ }
+}
diff --git a/subprojects/junitJupiterParallelTest/src/test/resources/junit-platform.properties b/subprojects/junitJupiterParallelTest/src/test/resources/junit-platform.properties
new file mode 100644
index 0000000000..cd19e48ea4
--- /dev/null
+++ b/subprojects/junitJupiterParallelTest/src/test/resources/junit-platform.properties
@@ -0,0 +1,3 @@
+junit.jupiter.execution.parallel.enabled=true
+junit.jupiter.execution.parallel.config.strategy=dynamic
+junit.jupiter.execution.parallel.mode.default=concurrent
| test | val | 2019-09-28T21:08:43 | "2019-02-25T12:54:15Z" | markusheiden | train |
mockito/mockito/1791_1798 | mockito/mockito | mockito/mockito/1791 | mockito/mockito/1798 | [
"keyword_pr_to_issue"
] | ded29efbfbd7be6e3a0a2fdae07d370d099be625 | e4b27d1d99800b09c757ec1854a70f8c295943cd | [
"Feel free to send a PR!"
] | [] | "2019-10-05T08:57:05Z" | [] | Typo in Mockito.java Javadoc: "verification" in wiki link | https://github.com/mockito/mockito/blob/f8581c6e875dc3fb587fe31e85d025ef4d110a3f/src/main/java/org/mockito/Mockito.java#L2579
There's a missing "i" in the wiki link:
```
https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verfication-InOrder
https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verification-InOrder
``` | [
"src/main/java/org/mockito/Mockito.java"
] | [
"src/main/java/org/mockito/Mockito.java"
] | [] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index 2f247045a2..3c8cdf7478 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -2576,7 +2576,7 @@ public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext)
* <p>
* <code>InOrder</code> verification is 'greedy', but you will hardly ever notice it.
* If you want to find out more, read
- * <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verfication-InOrder">this wiki page</a>.
+ * <a href="https://github.com/mockito/mockito/wiki/Greedy-algorithm-of-verification-InOrder">this wiki page</a>.
* <p>
* As of Mockito 1.8.4 you can verifyNoMoreInteractions() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
* <p>
| null | val | val | 2019-10-04T20:59:47 | "2019-09-30T19:34:37Z" | mjustin | train |
mockito/mockito/1631_1810 | mockito/mockito | mockito/mockito/1631 | mockito/mockito/1810 | [
"keyword_issue_to_pr"
] | a9c5105f8fda310a00b6d784a8bf9fb694a94610 | 5225b593d6dc11fbc63bb1d0c6ba7f7f0503f0da | [
"Is there any update on this? This has broken our tests as well attempting to upgrade our version of Mockito. The usage of an @InjectMocks as well as a @Spy & @InjectMocks makes sense from the perspective of integration testing of two components that act as one cohesive unit. ",
"Here's a pseudo code to describe the issues around this issue.\r\n\r\n# Before 2.23.15:\t\r\n\r\n```\r\nwhile (clazz != Object.clazz) {\r\n\tval mocks = aggregateSpyOrMockFields(clazz.getMockFields());\r\n val fields = aggregateInjectMocksFields(clazz);\r\n\tval ret = tryConstructorInjection(clazz, fields, mock);\r\n if (! ret.fieldWasInitializedUsingConstructorInjection()) {\r\n trySetterOrPropertyInjection(clazz, fields, mock);\r\n }\r\n\tclazz = clazz.getSuperclass();\r\n}\r\n```\r\n# After 2.23.15:\r\n```\r\n\tval mocks = aggregateSpyOrMockFields(clazz.getMockFields());\r\n val fields = aggregateInjectMocksFields(clazz);\r\n\tval ret = tryConstructorInjection(clazz, fields, mock);\r\n if (! ret.fieldWasInitializedUsingConstructorInjection()) {\r\n trySetterOrPropertyInjection(clazz, fields, mock);\r\n }\r\n```\r\n\r\n# Details\r\n\r\nBefore 2.23.15, if the `@InjectMocks` field has a field that not listed in the constructor argument will fill by setter/property injection at the 2nd loop 😃\r\nIt may not the expected behaviors by Mockito authors, but some users' code depends on this behavior.\r\n\r\nMy suggestion is to revert the [Fixes #1587 : Remove unnecessary loop from InjectingAnnotationEngine by LihMeh · Pull Request #1588 · mockito/mockito · GitHub](https://github.com/mockito/mockito/pull/1588) at this time.\r\n",
"Feel free to open a PR with regression test and I will be happy to merge it. Thanks!",
"This should be fixed with #1810"
] | [
"Can we assert here on `target.getBar()`. Also please add another assertion with `assertEquals(target.foo, foo)`",
"Thanks. applied your feedback.",
"Why would you iterate over the super classes of the Test class ???",
"This behaviour does not reflect the docs of the annotation",
"This test only works if I is extended... seems to make little sense"
] | "2019-10-24T23:29:02Z" | [
"injection"
] | Regression: @Spy with @InjectMock are not injected anymore | Hi,
- [x] The mockito message in the stacktrace have useful information, but it didn't help
java.lang.NullPointerException
at org.test.TestedService.servivce(TestedService.java:16)
at org.test.TestedServiceTest.mockSpyAndInjectAll(TestedServiceTest.java:33)
- [x] The problematic code (if that's possible) is copied here;
Fix of #1587 (Remove unnecessary loop from InjectingAnnotationEngine) has introduce a regression.
- [x] Provide versions (mockito / jdk / os / any other relevant information)
Issue can be reproduce starting from Mockito version 2.23.15.
- [x] Provide a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org) of the issue
Please find attached [inject-spy.zip](https://github.com/mockito/mockito/files/2905749/inject-spy.zip).
execute `./gradlew check`
- [x] Read the [contributing guide](https://github.com/mockito/mockito/blob/master/.github/CONTRIBUTING.md)
We are experiencing a regression behavior caused by fix of #1587 (Remove unnecessary loop from InjectingAnnotationEngine) which prevent us to update from Mockito 2.23.4 to newer versions.
```java
public class TestedServiceTest extends AbstractTest {
@InjectMocks
private TestedService testedService;
@InjectMocks
@Spy
private SpiedCompositionService spiedCompositionService;
@Mock
private MockedDao mockedDao;
...
}
```
As you can see in this snippet and example project attached, with Mockito 2.23.14 when we try to inject a mock in a spy and this spy in the tested object, it works as expected and everything is injected. But when we switch to Mockito 2.23.15, this behavior doesn't work anymore, the spy is not injected to tested object and obviously causes a NullPointerException.
We also figured out injection of injected spies was working only because test class extends has an abstract test class.
I understand this test case is not a state of the art way to do unit test, our use case is more a component test because several classes work together to do a coherent unit of work and it makes more sense to test them together.
We are relying on the behavior provided up to Mockito 2.23.14 and the only workaround I see is to expose attributes to package visibility and do injection by hand.
The loop removed by #1587 was injecting injected spies newly instantiated by first loop. The depth of injection was relying on the depth of test hierarchy. | [
"src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java"
] | [
"src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java"
] | [
"src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java"
] | diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
index 20d967d07e..6cb5fb123b 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 class InjectingAnnotationEngine implements AnnotationEngine, org.mockito.
*/
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/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java b/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
new file mode 100644
index 0000000000..7a8b064f68
--- /dev/null
+++ b/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2019 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+
+class I { }
+
+@RunWith(MockitoJUnitRunner.class)
+public class InjectingAnnotationEngineTest extends I {
+ @InjectMocks
+ Target target;
+ @Mock
+ Foo foo;
+ @Spy
+ Bar bar = new Bar();
+
+ /*
+ If the test case has super classes, the @InjectMocks field has a field that not listed in the constructor argument
+ will fill by setter/property injection .
+
+ https://github.com/mockito/mockito/issues/1631
+ */
+ @Test
+ public void injectMocks() {
+ Assert.assertEquals(foo, target.getFoo());
+ Assert.assertNotNull(target.getBar());
+ }
+
+ public static class Target {
+ private final Foo foo;
+ private Bar bar;
+
+ public Target(Foo foo) {
+ this.foo = foo;
+ }
+
+ public Foo getFoo() {
+ return foo;
+ }
+
+ public Bar getBar() {
+ return bar;
+ }
+ }
+
+ public static class Foo {
+ }
+
+ public static class Bar {
+ }
+}
| val | val | 2019-10-25T15:18:30 | "2019-02-26T15:29:04Z" | arnor2000 | train |
mockito/mockito/1587_1810 | mockito/mockito | mockito/mockito/1587 | mockito/mockito/1810 | [
"keyword_pr_to_issue"
] | a9c5105f8fda310a00b6d784a8bf9fb694a94610 | 5225b593d6dc11fbc63bb1d0c6ba7f7f0503f0da | [] | [
"Can we assert here on `target.getBar()`. Also please add another assertion with `assertEquals(target.foo, foo)`",
"Thanks. applied your feedback.",
"Why would you iterate over the super classes of the Test class ???",
"This behaviour does not reflect the docs of the annotation",
"This test only works if I is extended... seems to make little sense"
] | "2019-10-24T23:29:02Z" | [
"injection"
] | InjectingAnnotationEngine does an unnecessary loop. | processInjectMocks method of InjectingAnnotationEngine does unnecessary work. It might call injectMocks several times while it is sufficient to call injectMocks once.
private void processInjectMocks(final Class<?> clazz, final Object testInstance) {
Class<?> classContext = clazz;
while (classContext != Object.class) {
injectMocks(testInstance);
classContext = classContext.getSuperclass();
}
}
Inside, injectMocks loops classes by himself.
public void injectMocks(final Object testClassInstance) {
Class<?> clazz = testClassInstance.getClass();
Set<Field> mockDependentFields = new HashSet<Field>();
Set<Object> mocks = newMockSafeHashSet();
while (clazz != Object.class) {
new InjectMocksScanner(clazz).addTo(mockDependentFields);
new MockScanner(testClassInstance, clazz).addPreparedMocks(mocks);
onInjection(testClassInstance, clazz, mockDependentFields, mocks);
clazz = clazz.getSuperclass();
}
new DefaultInjectionEngine().injectMocksOnFields(mockDependentFields, mocks, testClassInstance);
}
Why not delete the unnecessary loop? | [
"src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java"
] | [
"src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java"
] | [
"src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java"
] | diff --git a/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/src/main/java/org/mockito/internal/configuration/InjectingAnnotationEngine.java
index 20d967d07e..6cb5fb123b 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 class InjectingAnnotationEngine implements AnnotationEngine, org.mockito.
*/
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/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java b/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
new file mode 100644
index 0000000000..7a8b064f68
--- /dev/null
+++ b/src/test/java/org/mockito/internal/configuration/InjectingAnnotationEngineTest.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2019 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+
+class I { }
+
+@RunWith(MockitoJUnitRunner.class)
+public class InjectingAnnotationEngineTest extends I {
+ @InjectMocks
+ Target target;
+ @Mock
+ Foo foo;
+ @Spy
+ Bar bar = new Bar();
+
+ /*
+ If the test case has super classes, the @InjectMocks field has a field that not listed in the constructor argument
+ will fill by setter/property injection .
+
+ https://github.com/mockito/mockito/issues/1631
+ */
+ @Test
+ public void injectMocks() {
+ Assert.assertEquals(foo, target.getFoo());
+ Assert.assertNotNull(target.getBar());
+ }
+
+ public static class Target {
+ private final Foo foo;
+ private Bar bar;
+
+ public Target(Foo foo) {
+ this.foo = foo;
+ }
+
+ public Foo getFoo() {
+ return foo;
+ }
+
+ public Bar getBar() {
+ return bar;
+ }
+ }
+
+ public static class Foo {
+ }
+
+ public static class Bar {
+ }
+}
| train | val | 2019-10-25T15:18:30 | "2019-01-10T12:16:12Z" | LihMeh | train |
mockito/mockito/1815_1818 | mockito/mockito | mockito/mockito/1815 | mockito/mockito/1818 | [
"keyword_pr_to_issue"
] | 68bc593ebb79efa515a211f8cdff77c7c3746a6a | 9603fb28158de0fb519611d58e931bf7b4bbc33c | [
"That would makes sense to me. Feel free to open a PR to add these methods.\r\n\r\n@mockito/developers We have a lot of evidence of `long`s being misused in common API's. Do you have any concerns if we deprecate the `after(long)` in favor of `after(java.time.Duration)` (and the same for `timeout`)?",
"Ideally we'd plumb the `Duration` all the way through the various layers of Mockito:\r\n\r\n- `org.mockito.verification.After`\r\n- `org.mockito.verification.Timeout`\r\n- `org.mockito.internal.verification.VerificationOverTimeImpl`\r\n- `org.mockito.internal.util.Timer`\r\n\r\nI assume `After` and `Timeout` need to maintain backwards compatibility, but the latter 2 are in an `internal` package - does that mean I don't need to maintain backwards compatibility? Am I free to make breaking changes to those APIs?\r\n",
"Yes, any API in `org.mockito.internal` is not included in our semver policy and we are free to change.",
"I second that, now that mockito 3 is java 8 based !"
] | [
"This example is for the `timeout(Duration)` method. I think we should revert the sample in this method, but add an additional sentence above that this is discouraged and `Duration.ofMillis` should be used instead.",
"Same as above.",
"Would it make sense to change this comparison to the relevant `Duration` method as well? Not sure how much it will provide us, but maybe it would prevent regressions later?",
"Nit: we indent with 4 spaces. I am surprised that spotless didn't format that, I will reconfigure the autoformatter to take care of that.",
"Done.",
"Done.",
"Done.",
"Done - the deprecation should serve as the method of discouraging use.",
"Done."
] | "2019-11-06T14:33:31Z" | [] | FR: add Mockito.timeout(java.time.Duration) and after(java.time.Duration) | Representing durations as `long`'s is very error prone. We've seen (and fixed) hundreds of unit mismatch bugs inside of Google.
We (Guava) have recently updated most of our public APIs to add `java.time.Duration`-based overloads. [Caffeine](https://github.com/ben-manes/caffeine/issues/221) and [Selenium](https://github.com/SeleniumHQ/selenium/issues/7187) have done so as well.
Basically, I'd like to see the following APIs added:
`Mockito.after(java.time.Duration)`
`Mockito.timeout(java.time.Duration)`
And ideally the `long`-accepting APIs would be deprecated. | [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/util/Timer.java",
"src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java",
"src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java",
"src/main/java/org/mockito/verification/After.java",
"src/main/java/org/mockito/verification/Timeout.java"
] | [
"src/main/java/org/mockito/Mockito.java",
"src/main/java/org/mockito/internal/exceptions/Reporter.java",
"src/main/java/org/mockito/internal/util/Timer.java",
"src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java",
"src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java",
"src/main/java/org/mockito/verification/After.java",
"src/main/java/org/mockito/verification/Timeout.java"
] | [
"src/test/java/org/mockito/internal/util/TimerTest.java",
"src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java",
"src/test/java/org/mockito/verification/TimeoutTest.java",
"src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java"
] | diff --git a/src/main/java/org/mockito/Mockito.java b/src/main/java/org/mockito/Mockito.java
index af1ceb22e9..aea283881e 100644
--- a/src/main/java/org/mockito/Mockito.java
+++ b/src/main/java/org/mockito/Mockito.java
@@ -4,6 +4,8 @@
*/
package org.mockito;
+import java.time.Duration;
+
import org.mockito.exceptions.misusing.PotentialStubbingProblem;
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.internal.InternalMockHandler;
@@ -886,15 +888,15 @@
* <pre class="code"><code class="java">
* //passes when someMethod() is called no later than within 100 ms
* //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
- * verify(mock, timeout(100)).someMethod();
+ * verify(mock, timeout(Duration.ofMillis(100))).someMethod();
* //above is an alias to:
- * verify(mock, timeout(100).times(1)).someMethod();
+ * verify(mock, timeout(Duration.ofMillis(100)).times(1)).someMethod();
*
* //passes as soon as someMethod() has been called 2 times under 100 ms
- * verify(mock, timeout(100).times(2)).someMethod();
+ * verify(mock, timeout(Duration.ofMillis(100)).times(2)).someMethod();
*
* //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms
- * verify(mock, timeout(100).atLeast(2)).someMethod();
+ * verify(mock, timeout(Duration.ofMillis(100)).atLeast(2)).someMethod();
* </code></pre>
*
*
@@ -2846,10 +2848,45 @@ public static VerificationMode only() {
* @param millis - duration in milliseconds
*
* @return object that allows fluent specification of the verification (times(x), atLeast(y), etc.)
+ * @deprecated Use {@link #timeout(Duration)} instead.
*/
@CheckReturnValue
+ @Deprecated
public static VerificationWithTimeout timeout(long millis) {
- return new Timeout(millis, VerificationModeFactory.times(1));
+ return timeout(Duration.ofMillis(millis));
+ }
+
+ /**
+ * Verification will be triggered over and over until the given amount of time, allowing testing of async code.
+ * Useful when interactions with the mock object did not happened yet.
+ * Extensive use of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code.
+ * <p>
+ * See also {@link #after(Duration)} method for testing async code.
+ * Differences between {@code timeout()} and {@code after} are explained in Javadoc for {@link #after(Duration)}.
+ *
+ * <pre class="code"><code class="java">
+ * //passes when someMethod() is called no later than within 100 ms
+ * //exits immediately when verification is satisfied (e.g. may not wait full 100 ms)
+ * verify(mock, timeout(Duration.ofMillis(100))).someMethod();
+ * //above is an alias to:
+ * verify(mock, timeout(Duration.ofMillis(100)).times(1)).someMethod();
+ *
+ * //passes as soon as someMethod() has been called 2 times under 100 ms
+ * verify(mock, timeout(Duration.ofMillis(100)).times(2)).someMethod();
+ *
+ * //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms
+ * verify(mock, timeout(Duration.ofMillis(100)).atLeast(2)).someMethod();
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param timeout how long to wait before timing out
+ *
+ * @return object that allows fluent specification of the verification (times(x), atLeast(y), etc.)
+ */
+ @CheckReturnValue
+ public static VerificationWithTimeout timeout(Duration timeout) {
+ return new Timeout(timeout, VerificationModeFactory.times(1));
}
/**
@@ -2889,7 +2926,7 @@ public static VerificationWithTimeout timeout(long millis) {
* //1.
* mock.foo();
* verify(mock, after(1000)).foo();
- * //waits 1000 millis and succeeds
+ * //waits 1 second and succeeds
*
* //2.
* mock.foo();
@@ -2902,10 +2939,68 @@ public static VerificationWithTimeout timeout(long millis) {
* @param millis - duration in milliseconds
*
* @return object that allows fluent specification of the verification
+ * @deprecated Use {@link #after(Duration)} instead.
*/
@CheckReturnValue
+ @Deprecated
public static VerificationAfterDelay after(long millis) {
- return new After(millis, VerificationModeFactory.times(1));
+ return after(Duration.ofMillis(millis));
+ }
+
+ /**
+ * Verification will be triggered after given amount of time, allowing testing of async code.
+ * Useful when interactions with the mock object did not happened yet.
+ * Extensive use of {@code after()} method can be a code smell - there are better ways of testing concurrent code.
+ * <p>
+ * Not yet implemented to work with InOrder verification.
+ * <p>
+ * See also {@link #timeout(Duration)} method for testing async code.
+ * Differences between {@code timeout()} and {@code after()} are explained below.
+ *
+ * <pre class="code"><code class="java">
+ * //passes after 100ms, if someMethod() has only been called once at that time.
+ * verify(mock, after(Duration.ofMillis(100))).someMethod();
+ * //above is an alias to:
+ * verify(mock, after(Duration.ofMillis(100)).times(1)).someMethod();
+ *
+ * //passes if someMethod() is called <b>*exactly*</b> 2 times, as tested after 100 millis
+ * verify(mock, after(Duration.ofMillis(100)).times(2)).someMethod();
+ *
+ * //passes if someMethod() has not been called, as tested after 100 millis
+ * verify(mock, after(Duration.ofMillis(100)).never()).someMethod();
+ *
+ * //verifies someMethod() after a given time span using given verification mode
+ * //useful only if you have your own custom verification modes.
+ * verify(mock, new After(Duration.ofMillis(100), yourOwnVerificationMode)).someMethod();
+ * </code></pre>
+ *
+ * <strong>timeout() vs. after()</strong>
+ * <ul>
+ * <li>timeout() exits immediately with success when verification passes</li>
+ * <li>after() awaits full duration to check if verification passes</li>
+ * </ul>
+ * Examples:
+ * <pre class="code"><code class="java">
+ * //1.
+ * mock.foo();
+ * verify(mock, after(Duration.ofSeconds(1))).foo();
+ * //waits 1 second and succeeds
+ *
+ * //2.
+ * mock.foo();
+ * verify(mock, timeout(Duration.ofSeconds(1))).foo();
+ * //succeeds immediately
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param delay how to to wait before triggering verification
+ *
+ * @return object that allows fluent specification of the verification
+ */
+ @CheckReturnValue
+ public static VerificationAfterDelay after(Duration delay) {
+ return new After(delay, VerificationModeFactory.times(1));
}
/**
diff --git a/src/main/java/org/mockito/internal/exceptions/Reporter.java b/src/main/java/org/mockito/internal/exceptions/Reporter.java
index f661b81e5c..db8bbbeacc 100644
--- a/src/main/java/org/mockito/internal/exceptions/Reporter.java
+++ b/src/main/java/org/mockito/internal/exceptions/Reporter.java
@@ -10,6 +10,7 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
+import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -863,12 +864,12 @@ public static MockitoException usingConstructorWithFancySerializable(Serializabl
return new MockitoException("Mocks instantiated with constructor cannot be combined with " + mode + " serialization mode.");
}
- public static MockitoException cannotCreateTimerWithNegativeDurationTime(long durationMillis) {
+ public static MockitoException cannotCreateTimerWithNegativeDurationTime(Duration duration) {
return new FriendlyReminderException(join(
"",
"Don't panic! I'm just a friendly reminder!",
"It is impossible for time to go backward, therefore...",
- "You cannot put negative value of duration: (" + durationMillis + ")",
+ "You cannot put negative value of duration: (" + duration + ")",
"as argument of timer methods (after(), timeout())",
""
));
diff --git a/src/main/java/org/mockito/internal/util/Timer.java b/src/main/java/org/mockito/internal/util/Timer.java
index 783f580c92..650e887660 100644
--- a/src/main/java/org/mockito/internal/util/Timer.java
+++ b/src/main/java/org/mockito/internal/util/Timer.java
@@ -6,38 +6,42 @@
import static org.mockito.internal.exceptions.Reporter.cannotCreateTimerWithNegativeDurationTime;
+import java.time.Duration;
+import java.time.Instant;
+
public class Timer {
- private final long durationMillis;
- private long startTime = -1;
+ private final Duration duration;
+ private Instant startTime = null;
- public Timer(long durationMillis) {
- validateInput(durationMillis);
- this.durationMillis = durationMillis;
+ public Timer(Duration duration) {
+ validateInput(duration);
+ this.duration = duration;
}
/**
* Informs whether the timer is still counting down.
*/
public boolean isCounting() {
- assert startTime != -1;
- return System.currentTimeMillis() - startTime <= durationMillis;
+ assert startTime != null;
+ Duration elapsed = Duration.between(startTime, Instant.now());
+ return elapsed.compareTo(duration) <= 0;
}
/**
* Starts the timer count down.
*/
public void start() {
- startTime = System.currentTimeMillis();
+ startTime = Instant.now();
}
- private void validateInput(long durationMillis) {
- if (durationMillis < 0) {
- throw cannotCreateTimerWithNegativeDurationTime(durationMillis);
+ private void validateInput(Duration duration) {
+ if (duration.isNegative()) {
+ throw cannotCreateTimerWithNegativeDurationTime(duration);
}
}
- public long duration() {
- return durationMillis;
+ public Duration duration() {
+ return duration;
}
}
diff --git a/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java b/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java
index 24ec61a90d..edcf77cf62 100644
--- a/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationOverTimeImpl.java
@@ -4,6 +4,8 @@
*/
package org.mockito.internal.verification;
+import java.time.Duration;
+
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.internal.util.Timer;
import org.mockito.internal.verification.api.VerificationData;
@@ -11,12 +13,12 @@
/**
* Verifies that another verification mode (the delegate) is satisfied within a certain timeframe
- * (before timeoutMillis has passed, measured from the call to verify()), and either returns immediately
+ * (before timeout has passed, measured from the call to verify()), and either returns immediately
* once it does, or waits until it is definitely satisfied once the full time has passed.
*/
public class VerificationOverTimeImpl implements VerificationMode {
- private final long pollingPeriodMillis;
+ private final Duration pollingPeriod;
private final VerificationMode delegate;
private final boolean returnOnSuccess;
private final Timer timer;
@@ -24,22 +26,22 @@ public class VerificationOverTimeImpl implements VerificationMode {
/**
* Create this verification mode, to be used to verify invocation ongoing data later.
*
- * @param pollingPeriodMillis The frequency to poll delegate.verify(), to check whether the delegate has been satisfied
- * @param durationMillis The max time to wait (in millis) for the delegate verification mode to be satisfied
+ * @param pollingPeriod The frequency to poll delegate.verify(), to check whether the delegate has been satisfied
+ * @param duration The max time to wait for the delegate verification mode to be satisfied
* @param delegate The verification mode to delegate overall success or failure to
* @param returnOnSuccess Whether to immediately return successfully once the delegate is satisfied (as in
* {@link org.mockito.verification.VerificationWithTimeout}, or to only return once
* the delegate is satisfied and the full duration has passed (as in
* {@link org.mockito.verification.VerificationAfterDelay}).
*/
- public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, VerificationMode delegate, boolean returnOnSuccess) {
- this(pollingPeriodMillis, delegate, returnOnSuccess, new Timer(durationMillis));
+ public VerificationOverTimeImpl(Duration pollingPeriod, Duration duration, VerificationMode delegate, boolean returnOnSuccess) {
+ this(pollingPeriod, delegate, returnOnSuccess, new Timer(duration));
}
/**
* Create this verification mode, to be used to verify invocation ongoing data later.
*
- * @param pollingPeriodMillis The frequency to poll delegate.verify(), to check whether the delegate has been satisfied
+ * @param pollingPeriod The frequency to poll delegate.verify(), to check whether the delegate has been satisfied
* @param delegate The verification mode to delegate overall success or failure to
* @param returnOnSuccess Whether to immediately return successfully once the delegate is satisfied (as in
* {@link org.mockito.verification.VerificationWithTimeout}, or to only return once
@@ -47,8 +49,8 @@ public VerificationOverTimeImpl(long pollingPeriodMillis, long durationMillis, V
* {@link org.mockito.verification.VerificationAfterDelay}).
* @param timer Checker of whether the duration of the verification is still acceptable
*/
- public VerificationOverTimeImpl(long pollingPeriodMillis, VerificationMode delegate, boolean returnOnSuccess, Timer timer) {
- this.pollingPeriodMillis = pollingPeriodMillis;
+ public VerificationOverTimeImpl(Duration pollingPeriod, VerificationMode delegate, boolean returnOnSuccess, Timer timer) {
+ this.pollingPeriod = pollingPeriod;
this.delegate = delegate;
this.returnOnSuccess = returnOnSuccess;
this.timer = timer;
@@ -97,7 +99,7 @@ public void verify(VerificationData data) {
private AssertionError handleVerifyException(AssertionError e) {
if (canRecoverFromFailure(delegate)) {
- sleep(pollingPeriodMillis);
+ sleep(pollingPeriod);
return e;
} else {
throw e;
@@ -109,12 +111,12 @@ protected boolean canRecoverFromFailure(VerificationMode verificationMode) {
}
public VerificationOverTimeImpl copyWithVerificationMode(VerificationMode verificationMode) {
- return new VerificationOverTimeImpl(pollingPeriodMillis, timer.duration(), verificationMode, returnOnSuccess);
+ return new VerificationOverTimeImpl(pollingPeriod, timer.duration(), verificationMode, returnOnSuccess);
}
- private void sleep(long sleep) {
+ private void sleep(Duration sleep) {
try {
- Thread.sleep(sleep);
+ Thread.sleep(sleep.toMillis());
} catch (InterruptedException ie) {
throw new RuntimeException("Thread sleep has been interrupted", ie);
}
@@ -124,8 +126,8 @@ public boolean isReturnOnSuccess() {
return returnOnSuccess;
}
- public long getPollingPeriodMillis() {
- return pollingPeriodMillis;
+ public Duration getPollingPeriod() {
+ return pollingPeriod;
}
public Timer getTimer() {
diff --git a/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
index 87d9076e00..0f3845b6cd 100644
--- a/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
+++ b/src/main/java/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
@@ -35,7 +35,7 @@ private VerificationMode wrapInOrder(VerificationWrapper<?> verificationWrapper,
if (verificationMode instanceof VerificationOverTimeImpl) {
final VerificationOverTimeImpl verificationOverTime = (VerificationOverTimeImpl)verificationMode;
if (verificationOverTime.isReturnOnSuccess()) {
- return new VerificationOverTimeImpl(verificationOverTime.getPollingPeriodMillis(),
+ return new VerificationOverTimeImpl(verificationOverTime.getPollingPeriod(),
verificationOverTime.getTimer().duration(),
wrapInOrder(verificationWrapper, verificationOverTime.getDelegate(), inOrder),
verificationOverTime.isReturnOnSuccess());
diff --git a/src/main/java/org/mockito/verification/After.java b/src/main/java/org/mockito/verification/After.java
index 54d7453022..a65a244ef7 100644
--- a/src/main/java/org/mockito/verification/After.java
+++ b/src/main/java/org/mockito/verification/After.java
@@ -4,6 +4,8 @@
*/
package org.mockito.verification;
+import java.time.Duration;
+
import org.mockito.internal.verification.VerificationOverTimeImpl;
import org.mockito.internal.verification.VerificationWrapper;
@@ -20,13 +22,25 @@ public class After extends VerificationWrapper<VerificationOverTimeImpl> impleme
* <p>
* Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class.
* See javadoc for {@link VerificationWithTimeout}
+ * @deprecated Use {@link After#After(Duration, VerificationMode)} instead.
*/
+ @Deprecated
public After(long delayMillis, VerificationMode verificationMode) {
- this(10, delayMillis, verificationMode);
+ this(Duration.ofMillis(delayMillis), verificationMode);
+ }
+
+ /**
+ * See the javadoc for {@link VerificationAfterDelay}
+ * <p>
+ * Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class.
+ * See javadoc for {@link VerificationWithTimeout}
+ */
+ public After(Duration delay, VerificationMode verificationMode) {
+ this(Duration.ofMillis(10), delay, verificationMode);
}
- After(long pollingPeriod, long delayMillis, VerificationMode verificationMode) {
- this(new VerificationOverTimeImpl(pollingPeriod, delayMillis, verificationMode, false));
+ After(Duration pollingPeriod, Duration delay, VerificationMode verificationMode) {
+ this(new VerificationOverTimeImpl(pollingPeriod, delay, verificationMode, false));
}
After(VerificationOverTimeImpl verificationOverTime) {
diff --git a/src/main/java/org/mockito/verification/Timeout.java b/src/main/java/org/mockito/verification/Timeout.java
index 99dcc45f53..b7679abf26 100644
--- a/src/main/java/org/mockito/verification/Timeout.java
+++ b/src/main/java/org/mockito/verification/Timeout.java
@@ -6,6 +6,8 @@
import static org.mockito.internal.exceptions.Reporter.atMostAndNeverShouldNotBeUsedWithTimeout;
+import java.time.Duration;
+
import org.mockito.internal.util.Timer;
import org.mockito.internal.verification.VerificationOverTimeImpl;
import org.mockito.internal.verification.VerificationWrapper;
@@ -23,23 +25,35 @@ public class Timeout extends VerificationWrapper<VerificationOverTimeImpl> imple
* <p>
* Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class.
* See javadoc for {@link VerificationWithTimeout}
+ * @deprecated Use {@link Timeout#Timeout(Duration, VerificationMode)} instead.
*/
+ @Deprecated
public Timeout(long millis, VerificationMode delegate) {
- this(10, millis, delegate);
+ this(Duration.ofMillis(millis), delegate);
+ }
+
+ /**
+ * See the javadoc for {@link VerificationWithTimeout}
+ * <p>
+ * Typically, you won't use this class explicitly. Instead use timeout() method on Mockito class.
+ * See javadoc for {@link VerificationWithTimeout}
+ */
+ public Timeout(Duration timeout, VerificationMode delegate) {
+ this(Duration.ofMillis(10), timeout, delegate);
}
/**
* See the javadoc for {@link VerificationWithTimeout}
*/
- Timeout(long pollingPeriodMillis, long millis, VerificationMode delegate) {
- this(new VerificationOverTimeImpl(pollingPeriodMillis, millis, delegate, true));
+ Timeout(Duration pollingPeriod, Duration timeout, VerificationMode delegate) {
+ this(new VerificationOverTimeImpl(pollingPeriod, timeout, delegate, true));
}
/**
* See the javadoc for {@link VerificationWithTimeout}
*/
- Timeout(long pollingPeriodMillis, VerificationMode delegate, Timer timer) {
- this(new VerificationOverTimeImpl(pollingPeriodMillis, delegate, true, timer));
+ Timeout(Duration pollingPeriod, VerificationMode delegate, Timer timer) {
+ this(new VerificationOverTimeImpl(pollingPeriod, delegate, true, timer));
}
Timeout(VerificationOverTimeImpl verificationOverTime) {
| diff --git a/src/test/java/org/mockito/internal/util/TimerTest.java b/src/test/java/org/mockito/internal/util/TimerTest.java
index 8a4a173e02..2f2885b0da 100644
--- a/src/test/java/org/mockito/internal/util/TimerTest.java
+++ b/src/test/java/org/mockito/internal/util/TimerTest.java
@@ -4,6 +4,8 @@
*/
package org.mockito.internal.util;
+import java.time.Duration;
+
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
@@ -18,7 +20,7 @@ public class TimerTest extends TestBase {
@Test
public void should_return_true_if_task_is_in_acceptable_time_bounds() {
//given
- long duration = 10000L;
+ Duration duration = Duration.ofSeconds(10);
Timer timer = new Timer(duration);
//when
@@ -31,7 +33,7 @@ public void should_return_true_if_task_is_in_acceptable_time_bounds() {
@Test
public void should_return_false_when_time_run_out() throws Exception {
//given
- Timer timer = new Timer(0);
+ Timer timer = new Timer(Duration.ZERO);
timer.start();
//when
@@ -45,7 +47,7 @@ public void should_return_false_when_time_run_out() throws Exception {
public void should_throw_friendly_reminder_exception_when_duration_is_negative() {
expectedException.expect(FriendlyReminderException.class);
expectedException.expectMessage("Don't panic! I'm just a friendly reminder!");
- new Timer(-1);
+ new Timer(Duration.ofMillis(-1));
}
private void oneMillisecondPasses() throws InterruptedException {
diff --git a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
index 82cceeaea7..5f206c5420 100644
--- a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
+++ b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java
@@ -9,6 +9,8 @@
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
+import java.time.Duration;
+
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -29,7 +31,8 @@ public class VerificationOverTimeImplTest {
@Before
public void setUp() {
initMocks(this);
- impl = new VerificationOverTimeImpl(10, 1000, delegate, true);
+ impl = new VerificationOverTimeImpl(
+ Duration.ofMillis(10), Duration.ofSeconds(1), delegate, true);
}
@Test
diff --git a/src/test/java/org/mockito/verification/TimeoutTest.java b/src/test/java/org/mockito/verification/TimeoutTest.java
index ae6e5d2e84..3719ae4215 100644
--- a/src/test/java/org/mockito/verification/TimeoutTest.java
+++ b/src/test/java/org/mockito/verification/TimeoutTest.java
@@ -7,6 +7,8 @@
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
+import java.time.Duration;
+
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
@@ -28,7 +30,7 @@ public class TimeoutTest extends TestBase {
@Test
public void should_pass_when_verification_passes() {
- Timeout t = new Timeout(1, mode, timer);
+ Timeout t = new Timeout(Duration.ofMillis(1), mode, timer);
when(timer.isCounting()).thenReturn(true);
doNothing().when(mode).verify(data);
@@ -42,7 +44,7 @@ public void should_pass_when_verification_passes() {
@Test
public void should_fail_because_verification_fails() {
- Timeout t = new Timeout(1, mode, timer);
+ Timeout t = new Timeout(Duration.ofMillis(1), mode, timer);
when(timer.isCounting()).thenReturn(true, true, true, false);
doThrow(error).
@@ -60,7 +62,7 @@ public void should_fail_because_verification_fails() {
@Test
public void should_pass_even_if_first_verification_fails() {
- Timeout t = new Timeout(1, mode, timer);
+ Timeout t = new Timeout(Duration.ofMillis(1), mode, timer);
when(timer.isCounting()).thenReturn(true, true, true, false);
doThrow(error).
@@ -74,7 +76,7 @@ public void should_pass_even_if_first_verification_fails() {
@Test
public void should_try_to_verify_correct_number_of_times() {
- Timeout t = new Timeout(10, mode, timer);
+ Timeout t = new Timeout(Duration.ofMillis(10), mode, timer);
doThrow(error).when(mode).verify(data);
when(timer.isCounting()).thenReturn(true, true, true, true, true, false);
diff --git a/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java b/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java
index 0c50578f6c..230b632910 100644
--- a/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java
+++ b/src/test/java/org/mockitousage/verification/VerificationWithTimeoutTest.java
@@ -10,6 +10,7 @@
import static org.mockito.junit.MockitoJUnit.rule;
import static org.mockitoutil.Stopwatch.createNotStarted;
+import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.assertj.core.api.Assertions;
@@ -57,6 +58,17 @@ public void should_verify_with_timeout() {
verify(mock).oneArg('c'); //sanity check
}
+ @Test
+ public void should_verify_with_timeout_duration() {
+ // when
+ async.runAfter(50, callMock('c'));
+ async.runAfter(500, callMock('c'));
+
+ // then
+ verify(mock, timeout(Duration.ofMillis(200)).only()).oneArg('c');
+ verify(mock).oneArg('c'); //sanity check
+ }
+
@Test
public void should_verify_with_timeout_and_fail() {
// when
@@ -72,6 +84,21 @@ public void call() {
//TODO let's have a specific exception vs. generic assertion error + message
}
+ @Test
+ public void should_verify_with_timeout_and_fail_duration() {
+ // when
+ async.runAfter(200, callMock('c'));
+
+ // then
+ Assertions.assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
+ @Override
+ public void call() {
+ verify(mock, timeout(Duration.ofMillis(50)).only()).oneArg('c');
+ }
+ }).isInstanceOf(AssertionError.class).hasMessageContaining("Wanted but not invoked");
+ //TODO let's have a specific exception vs. generic assertion error + message
+ }
+
@Test
@Ignore //TODO nice to have
public void should_verify_with_timeout_and_fail_early() {
| train | val | 2019-11-06T11:59:06 | "2019-11-06T01:27:23Z" | kluever | train |
mockito/mockito/1827_1828 | mockito/mockito | mockito/mockito/1827 | mockito/mockito/1828 | [
"keyword_pr_to_issue"
] | d6cec3963eb37db6eb025c490136e277b75cc269 | 3dd936c7834a396f3676c2d07772e43b11578b87 | [
"We had same issues with Java 13. I just overrode Mockito Byte Buddy dependency to a newer version (1.10.3), and it solved inline mock failures in our tests.\r\n\r\nSubmitted the upgrade in Mockito itself: #1828",
"Please do not mock Inputstream, but create a real example with fake data instead. That said, we will update Byte Buddy to be compatible with Java 13.",
"Thank you @TimvdLippe ! Would it be possible please to push this release to Maven Central? Creating inline mocks of _any_ classes compiled with javac 13 does not work, not just platform classes like InputStream, so I think this release can be considered 'notable' according to the release policy.",
"It is being released: https://github.com/mockito/mockito/commit/d7c5ac446f156ba6fa913e041441ba4f566f3749",
"Wonderful, thanks!",
"Thanks everyone for the quick response :-)"
] | [] | "2019-11-26T18:57:00Z" | [] | Cannot mock this class: class java.io.InputStream with Java 13 | ## Versions
* Mockito: 3.1.0
* JDK: 13.0.1+9
* OS: macOS 10.13
* XCode: 10.1-19
## Code causing the error
```
InputStream in = mock(InputStream.class);
```
## Error:
```
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.015 s <<< FAILURE! - in uk.gov.nationalarchives.droid.core.interfaces.archive.ZipEntryRequestFactoryTest
[ERROR] testNewZipRequest(uk.gov.nationalarchives.droid.core.interfaces.archive.ZipEntryRequestFactoryTest) Time elapsed: 0.005 s <<< ERROR!
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class java.io.InputStream.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 13
JVM vendor name : Oracle Corporation
JVM vendor version : 13.0.1+9
JVM name : OpenJDK 64-Bit Server VM
JVM version : 13.0.1+9
JVM info : mixed mode, sharing
OS name : Mac OS X
OS version : 10.13.6
You are seeing this disclaimer because Mockito is configured to create inlined mocks.
You can learn about inline mocks and their limitations under item #39 of the Mockito class javadoc.
Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [class java.lang.Object, class java.io.InputStream, interface java.lang.AutoCloseable, interface java.io.Closeable]
at uk.gov.nationalarchives.droid.core.interfaces.archive.ZipEntryRequestFactoryTest.testNewZipRequest(ZipEntryRequestFactoryTest.java:70)
Caused by: org.mockito.exceptions.base.MockitoException: Could not modify all classes [class java.lang.Object, class java.io.InputStream, interface java.lang.AutoCloseable, interface java.io.Closeable]
at uk.gov.nationalarchives.droid.core.interfaces.archive.ZipEntryRequestFactoryTest.testNewZipRequest(ZipEntryRequestFactoryTest.java:70)
Caused by: java.lang.IllegalStateException:
Byte Buddy could not instrument all classes within the mock's type hierarchy
This problem should never occur for javac-compiled classes. This problem has been observed for classes that are:
- Compiled by older versions of scalac
- Classes that are part of the Android distribution
at uk.gov.nationalarchives.droid.core.interfaces.archive.ZipEntryRequestFactoryTest.testNewZipRequest(ZipEntryRequestFactoryTest.java:70)
Caused by: java.lang.IllegalArgumentException: Unsupported class file major version 57
at uk.gov.nationalarchives.droid.core.interfaces.archive.ZipEntryRequestFactoryTest.testNewZipRequest(ZipEntryRequestFactoryTest.java:70)
```
| [
"gradle/dependencies.gradle"
] | [
"gradle/dependencies.gradle"
] | [] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index 79cc490052..0e6b448762 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -4,7 +4,7 @@ ext {
def versions = [:]
-versions.bytebuddy = '1.10.2'
+versions.bytebuddy = '1.10.3'
versions.junitJupiter = '5.4.2'
versions.errorprone = '2.3.2'
| null | train | val | 2019-11-20T13:42:42 | "2019-11-24T10:28:30Z" | adamretter | train |
mockito/mockito/1839_1840 | mockito/mockito | mockito/mockito/1839 | mockito/mockito/1840 | [
"keyword_pr_to_issue"
] | 186a966054aa933b5ea9463ae908aa963107ffa7 | ae8117f6b72350788f429168292bafe13e231e04 | [] | [
"Same as on the website PR, let's keep this `mockito-development` and fix the bug in Shipkit instead.",
"OK, I've reverted that change. Sadly, it means that #1839 is not going to be fully fixed by this PR. At least \"Download\" would become \"Bintray\", so that users won't expect it to the **the** download link."
] | "2019-12-05T20:56:36Z" | [] | Bintray badge is out of date | The badges in README.md show:
```
maven-central 3.2.0 Download 3.1.13
```
That makes the project looks sloppy, as if the developers forgot to update their downloads. "Download" is actually a link to Bintray, which should be clarified.
Bintray does have version 3.2.0. The old version is shown because the package name in the link is wrong. It should be "mockito", not "mockito-development" | [
"README.md"
] | [
"README.md"
] | [] | diff --git a/README.md b/README.md
index 8d03229ad3..a69f94874a 100644
--- a/README.md
+++ b/README.md
@@ -6,12 +6,14 @@
Most popular mocking framework for Java
-[![Build Status](https://travis-ci.org/mockito/mockito.svg?branch=release/3.x)](https://travis-ci.org/mockito/mockito) [![Coverage Status](https://img.shields.io/codecov/c/github/mockito/mockito.svg)](https://codecov.io/github/mockito/mockito) [![MIT License](http://img.shields.io/badge/license-MIT-green.svg) ](https://github.com/mockito/mockito/blob/release/3.x/LICENSE)
-
-[![latest release](https://img.shields.io/badge/release%20notes-3.x-yellow.svg)](https://github.com/mockito/mockito/blob/release/3.x/doc/release-notes/official.md)
-[![Maven Central](https://img.shields.io/maven-central/v/org.mockito/mockito-core.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.mockito%22%20AND%20a%3A%22mockito-core%22)
-[![Bintray](https://api.bintray.com/packages/mockito/maven/mockito-development/images/download.svg)](https://bintray.com/mockito/maven)
-[![Javadocs](http://www.javadoc.io/badge/org.mockito/mockito-core.svg?color=red)](http://www.javadoc.io/doc/org.mockito/mockito-core)
+[![Build Status](https://travis-ci.org/mockito/mockito.svg?branch=release/3.x)](https://travis-ci.org/mockito/mockito)
+[![Coverage Status](https://img.shields.io/codecov/c/github/mockito/mockito.svg)](https://codecov.io/github/mockito/mockito)
+[![MIT License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/mockito/mockito/blob/release/3.x/LICENSE)
+
+[![Release Notes](https://img.shields.io/badge/release%20notes-3.x-yellow.svg)](https://github.com/mockito/mockito/blob/release/3.x/doc/release-notes/official.md)
+[![Maven Central](https://img.shields.io/maven-central/v/org.mockito/mockito-core.svg)](https://search.maven.org/artifact/org.mockito/mockito-core/)
+[![Bintray](https://img.shields.io/bintray/v/mockito/maven/mockito-development)](https://bintray.com/mockito/maven/mockito/_latestVersion)
+[![Javadoc](https://www.javadoc.io/badge/org.mockito/mockito-core.svg)](https://www.javadoc.io/doc/org.mockito/mockito-core)
## Current version is 3.x
| null | train | val | 2019-11-29T17:19:01 | "2019-12-05T20:50:59Z" | proski | train |
mockito/mockito/1841_1842 | mockito/mockito | mockito/mockito/1841 | mockito/mockito/1842 | [
"keyword_pr_to_issue"
] | 49c3b4ffd25f574cbd64a2f85b9ea4b9bfbfe623 | fe1141bcea74838fc1a5c1867ec932f180b8eb45 | [] | [] | "2019-12-11T20:12:44Z" | [] | Update byte-buddy to 1.10.5 | Hi,
Byte-buddy had a bug that prevented running tests in IntelliJ due to space in the executable name: https://github.com/raphw/byte-buddy/issues/732 This was fixed in [1.10.5](https://github.com/raphw/byte-buddy/releases/tag/byte-buddy-1.10.5) so it would make sense to update it in Mockito as well. | [
"gradle/dependencies.gradle"
] | [
"gradle/dependencies.gradle"
] | [] | diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle
index 0e6b448762..cebf8058cb 100644
--- a/gradle/dependencies.gradle
+++ b/gradle/dependencies.gradle
@@ -4,7 +4,7 @@ ext {
def versions = [:]
-versions.bytebuddy = '1.10.3'
+versions.bytebuddy = '1.10.5'
versions.junitJupiter = '5.4.2'
versions.errorprone = '2.3.2'
| null | train | val | 2019-12-07T18:57:47 | "2019-12-11T20:10:38Z" | villesau | train |