Add updated mockito target with v2.2.9
Test: mm
Change-Id: Ic19e6143a0df4733eb6da740b1e01f53253103e8
diff --git a/Android.mk b/Android.mk
index ffacf71..034936c 100644
--- a/Android.mk
+++ b/Android.mk
@@ -118,3 +118,5 @@
###################################################
explicit_target_excludes :=
target_src_files :=
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/mockito-updated/Android.mk b/mockito-updated/Android.mk
new file mode 100644
index 0000000..63ed866
--- /dev/null
+++ b/mockito-updated/Android.mk
@@ -0,0 +1,84 @@
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#
+
+LOCAL_PATH := $(call my-dir)
+
+###################################################################
+# Target build
+###################################################################
+
+# Builds the Mockito source code, but does not include any run-time
+# dependencies. Most projects should use mockito-target instead, which includes
+# everything needed to run Mockito tests.
+include $(CLEAR_VARS)
+
+# Exclude source used to dynamically create classes since target builds use
+# dexmaker instead and including it causes conflicts.
+explicit_target_excludes := \
+ src/org/mockito/internal/creation/AbstractMockitoMethodProxy.java \
+ src/org/mockito/internal/creation/AcrossJVMSerializationFeature.java \
+ src/org/mockito/internal/creation/CglibMockMaker.java \
+ src/org/mockito/internal/creation/DelegatingMockitoMethodProxy.java \
+ src/org/mockito/internal/creation/MethodInterceptorFilter.java \
+ src/org/mockito/internal/creation/MockitoMethodProxy.java \
+ src/org/mockito/internal/creation/SerializableMockitoMethodProxy.java \
+ src/org/mockito/internal/invocation/realmethod/FilteredCGLIBProxyRealMethod.java \
+ src/org/mockito/internal/invocation/realmethod/CGLIBProxyRealMethod.java \
+ src/org/mockito/internal/invocation/realmethod/HasCGLIBMethodProxy.java
+
+target_src_files := \
+ $(call all-java-files-under, src)
+target_src_files := \
+ $(filter-out src/org/mockito/internal/creation/cglib/%, $(target_src_files))
+target_src_files := \
+ $(filter-out src/org/mockito/internal/creation/jmock/%, $(target_src_files))
+target_src_files := \
+ $(filter-out $(explicit_target_excludes), $(target_src_files))
+
+LOCAL_SRC_FILES := $(target_src_files)
+LOCAL_JAVA_LIBRARIES := junit4-target objenesis-updated-target
+LOCAL_MODULE := mockito-updated-api
+LOCAL_SDK_VERSION := 16
+LOCAL_MODULE_TAGS := optional
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+# Main target for dependent projects. Bundles all the run-time dependencies
+# needed to run Mockito tests on the device.
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := mockito-updated-target
+LOCAL_STATIC_JAVA_LIBRARIES := mockito-updated-target-minus-junit4 junit4-target
+LOCAL_SDK_VERSION := 16
+LOCAL_MODULE_TAGS := optional
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+# A mockito target that doesn't pull in junit4-target. This is used to work around
+# issues caused by multiple copies of junit4 in the classpath, usually when a test
+# using mockito is run using android.test.runner.
+include $(CLEAR_VARS)
+LOCAL_MODULE := mockito-updated-target-minus-junit4
+LOCAL_STATIC_JAVA_LIBRARIES := mockito-updated-api dexmaker dexmaker-mockmaker-updated objenesis-updated-target
+LOCAL_JAVA_LIBRARIES := junit4-target
+LOCAL_SDK_VERSION := 16
+LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.7
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+###################################################
+# Clean up temp vars
+###################################################
+explicit_target_excludes :=
+target_src_files :=
diff --git a/mockito-updated/src/org/mockito/AdditionalAnswers.java b/mockito-updated/src/org/mockito/AdditionalAnswers.java
new file mode 100644
index 0000000..ade1ce3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/AdditionalAnswers.java
@@ -0,0 +1,365 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+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;
+import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.Answer1;
+import org.mockito.stubbing.Answer2;
+import org.mockito.stubbing.Answer3;
+import org.mockito.stubbing.Answer4;
+import org.mockito.stubbing.Answer5;
+import org.mockito.stubbing.VoidAnswer1;
+import org.mockito.stubbing.VoidAnswer2;
+import org.mockito.stubbing.VoidAnswer3;
+import org.mockito.stubbing.VoidAnswer4;
+import org.mockito.stubbing.VoidAnswer5;
+
+/**
+ * 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.
+ *
+ * <p>See factory methods for more information : {@link #returnsFirstArg}, {@link #returnsSecondArg},
+ * {@link #returnsLastArg}, {@link #returnsArgAt}, {@link #answer} and {@link #answerVoid}
+ *
+ * @since 1.9.5
+ */
+@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 :
+ * </p>
+ *
+ * <pre class="code"><code class="java">given(carKeyFob.authenticate(carKey)).will(returnsFirstArg());
+ * doAnswer(returnsFirstArg()).when(carKeyFob).authenticate(carKey)</code></pre>
+ *
+ * @param <T> Return type of the invocation.
+ * @return Answer that will return the first argument of the invocation.
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> returnsFirstArg() {
+ return (Answer<T>) RETURNS_FIRST_ARGUMENT;
+ }
+
+ /**
+ * Returns the second 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 :
+ * </p>
+ *
+ * <pre class="code"><code class="java">given(trader.apply(leesFormula, onCreditDefaultSwap)).will(returnsSecondArg());
+ * doAnswer(returnsSecondArg()).when(trader).apply(leesFormula, onCreditDefaultSwap)</code></pre>
+ *
+ * @param <T> Return type of the invocation.
+ * @return Answer that will return the second argument of the invocation.
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> returnsSecondArg() {
+ return (Answer<T>) RETURNS_SECOND_ARGUMENT;
+ }
+
+ /**
+ * Returns the last 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 :
+ * </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>
+ *
+ * @param <T> Return type of the invocation.
+ * @return Answer that will return the last argument of the invocation.
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> returnsLastArg() {
+ return (Answer<T>) RETURNS_LAST_ARGUMENT;
+ }
+
+ /**
+ * Returns the parameter of an invocation at the given position.
+ *
+ * <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 :
+ * </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>
+ *
+ * @param <T> Return type of the invocation.
+ * @param position index of the argument from the list of arguments.
+ * @return Answer that will return the argument from the given position in the argument's list
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> returnsArgAt(int position) {
+ return (Answer<T>) new ReturnsArgumentAt(position);
+ }
+
+ /**
+ * An answer that directly forwards the calls to the delegate. The delegate may or may not be of the same type as the mock.
+ * If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown.
+ * <p>
+ * Useful for spies or partial mocks of objects that are difficult to mock
+ * or spy using the usual spy API. Possible use cases:
+ * <ul>
+ * <li>Final classes but with an interface</li>
+ * <li>Already custom proxied object</li>
+ * <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
+ * </ul>
+ *
+ * <p>
+ * The difference with the regular spy:
+ * <ul>
+ * <li>
+ * The regular spy ({@link Mockito#spy(Object)}) contains <strong>all</strong> state from the spied instance
+ * and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
+ * If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
+ * for verifications, and they can be effectively stubbed.
+ * </li>
+ * <li>
+ * The mock that delegates simply delegates all methods to the delegate.
+ * The delegate is used all the time as methods are delegated onto it.
+ * If you call a method on a mock that delegates and it internally calls other methods on this mock,
+ * those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
+ * Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
+ * </li>
+ * </ul>
+ * An example with a final class that we want to delegate to:
+ * <p>
+ * <pre class="code"><code class="java">
+ * final class DontYouDareToMockMe implements list { ... }
+ *
+ * DontYouDareToMockMe awesomeList = new DontYouDareToMockMe();
+ *
+ * List mock = mock(List.class, delegatesTo(awesomeList));
+ * </code></pre>
+ *
+ * <p>
+ * This feature suffers from the same drawback as the spy.
+ * The mock will call the delegate if you use regular when().then() stubbing style.
+ * Since the real implementation is called this might have some side effects.
+ * Therefore you should to use the doReturn|Throw|Answer|CallRealMethod stubbing style. Example:
+ *
+ * <pre class="code"><code class="java">
+ * List listWithDelegate = mock(List.class, AdditionalAnswers.delegatesTo(awesomeList));
+ *
+ * //Impossible: real method is called so listWithDelegate.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(listWithDelegate.get(0)).thenReturn("foo");
+ *
+ * //You have to use doReturn() for stubbing
+ * doReturn("foo").when(listWithDelegate).get(0);
+ * </code></pre>
+ *
+ * @param delegate The delegate to forward calls to. It does not have to be of the same type as the mock (although it usually is).
+ * The only requirement is that the instance should have compatible method signatures including the return values.
+ * Only the methods that were actually executed on the mock need to be present on the delegate type.
+ * @return the answer
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> delegatesTo(Object delegate) {
+ return (Answer<T>) new ForwardsInvocations(delegate);
+ }
+
+ /**
+ * Returns elements of the collection. Keeps returning the last element forever.
+ * Might be useful on occasion when you have a collection of elements to return.
+ * <p>
+ * <pre class="code"><code class="java">
+ * //this:
+ * when(mock.foo()).thenReturn(1, 2, 3);
+ *
+ * //is equivalent to:
+ * when(mock.foo()).thenAnswer(new ReturnsElementsOf(Arrays.asList(1, 2, 3)));
+ * </code></pre>
+ *
+ * @param elements The collection of elements to return.
+ * @return the answer
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> returnsElementsOf(Collection<?> elements) {
+ return (Answer<T>) new ReturnsElementsOf(elements);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - which is expected to return something
+ * @param <T> return type
+ * @param <A> input parameter type 1
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <T, A> Answer<T> answer(Answer1<T, A> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - a void method
+ * @param <A> input parameter type 1
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <A> Answer<Void> answerVoid(VoidAnswer1<A> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - which is expected to return something
+ * @param <T> return type
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <T, A, B> Answer<T> answer(Answer2<T, A, B> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - a void method
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <A, B> Answer<Void> answerVoid(VoidAnswer2<A, B> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - which is expected to return something
+ * @param <T> return type
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @param <C> input parameter type 3
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <T, A, B, C> Answer<T> answer(Answer3<T, A, B, C> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - a void method
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @param <C> input parameter type 3
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <A, B, C> Answer<Void> answerVoid(VoidAnswer3<A, B, C> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - which is expected to return something
+ * @param <T> return type
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @param <C> input parameter type 3
+ * @param <D> input parameter type 4
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <T, A, B, C, D> Answer<T> answer(Answer4<T, A, B, C, D> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - a void method
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @param <C> input parameter type 3
+ * @param <D> input parameter type 4
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <A, B, C, D> Answer<Void> answerVoid(VoidAnswer4<A, B, C, D> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ * @param answer interface to the answer - which is expected to return something
+ * @param <T> return type
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @param <C> input parameter type 3
+ * @param <D> input parameter type 4
+ * @param <E> input parameter type 5
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <T, A, B, C, D, E> Answer<T> answer(Answer5<T, A, B, C, D, E> answer) {
+ return toAnswer(answer);
+ }
+
+ /**
+ * Creates an answer from a functional interface - allows for a strongly typed answer to be created
+ * ideally in Java 8
+ *
+ * @param answer interface to the answer - a void method
+ * @param <A> input parameter type 1
+ * @param <B> input parameter type 2
+ * @param <C> input parameter type 3
+ * @param <D> input parameter type 4
+ * @param <E> input parameter type 5
+ * @return the answer object to use
+ * @since 2.1.0
+ */
+ @Incubating
+ public static <A, B, C, D, E> Answer<Void> answerVoid(VoidAnswer5<A, B, C, D, E> answer) {
+ return toAnswer(answer);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/AdditionalMatchers.java b/mockito-updated/src/org/mockito/AdditionalMatchers.java
new file mode 100644
index 0000000..b0c4653
--- /dev/null
+++ b/mockito-updated/src/org/mockito/AdditionalMatchers.java
@@ -0,0 +1,1058 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito;
+
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+
+import org.mockito.internal.matchers.ArrayEquals;
+import org.mockito.internal.matchers.CompareEqual;
+import org.mockito.internal.matchers.EqualsWithDelta;
+import org.mockito.internal.matchers.Find;
+import org.mockito.internal.matchers.GreaterOrEqual;
+import org.mockito.internal.matchers.GreaterThan;
+import org.mockito.internal.matchers.LessOrEqual;
+import org.mockito.internal.matchers.LessThan;
+
+/**
+ * See {@link Matchers} for general info about matchers.
+ * <p>
+ * AdditionalMatchers provides rarely used matchers, kept only for somewhat compatibility with EasyMock.
+ * Use additional matchers very judiciously because they may impact readability of a test.
+ * It is recommended to use matchers from {@link Matchers} and keep stubbing and verification simple.
+ * <p>
+ * Example of using logical and(), not(), or() matchers:
+ *
+ * <pre class="code"><code class="java">
+ * //anything but not "ejb"
+ * mock.someMethod(not(eq("ejb")));
+ *
+ * //not "ejb" and not "michael jackson"
+ * mock.someMethod(and(not(eq("ejb")), not(eq("michael jackson"))));
+ *
+ * //1 or 10
+ * mock.someMethod(or(eq(1), eq(10)));
+ * </code></pre>
+ *
+ * Scroll down to see all methods - full list of matchers.
+ */
+@SuppressWarnings("ALL")
+public class AdditionalMatchers {
+
+ /**
+ * argument greater than or equal the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>null</code>.
+ */
+ public static <T extends Comparable<T>> T geq(T value) {
+ reportMatcher(new GreaterOrEqual<T>(value));
+ return null;
+ }
+
+ /**
+ * byte argument greater than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static byte geq(byte value) {
+ reportMatcher(new GreaterOrEqual<Byte>(value));
+ return 0;
+ }
+
+ /**
+ * double argument greater than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static double geq(double value) {
+ reportMatcher(new GreaterOrEqual<Double>(value));
+ return 0;
+ }
+
+ /**
+ * float argument greater than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static float geq(float value) {
+ reportMatcher(new GreaterOrEqual<Float>(value));
+ return 0;
+ }
+
+ /**
+ * int argument greater than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static int geq(int value) {
+ reportMatcher(new GreaterOrEqual<Integer>(value));
+ return 0;
+ }
+
+ /**
+ * long argument greater than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static long geq(long value) {
+ reportMatcher(new GreaterOrEqual<Long>(value));
+ return 0;
+ }
+
+ /**
+ * short argument greater than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static short geq(short value) {
+ reportMatcher(new GreaterOrEqual<Short>(value));
+ return 0;
+ }
+
+ /**
+ * comparable argument less than or equal the given value details.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>null</code>.
+ */
+ public static <T extends Comparable<T>> T leq(T value) {
+ reportMatcher(new LessOrEqual<T>(value));
+ return null;
+ }
+
+ /**
+ * byte argument less than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static byte leq(byte value) {
+ reportMatcher(new LessOrEqual<Byte>(value));
+ return 0;
+ }
+
+ /**
+ * double argument less than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static double leq(double value) {
+ reportMatcher(new LessOrEqual<Double>(value));
+ return 0;
+ }
+
+ /**
+ * float argument less than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static float leq(float value) {
+ reportMatcher(new LessOrEqual<Float>(value));
+ return 0;
+ }
+
+ /**
+ * int argument less than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static int leq(int value) {
+ reportMatcher(new LessOrEqual<Integer>(value));
+ return 0;
+ }
+
+ /**
+ * long argument less than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static long leq(long value) {
+ reportMatcher(new LessOrEqual<Long>(value));
+ return 0;
+ }
+
+ /**
+ * short argument less than or equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static short leq(short value) {
+ reportMatcher(new LessOrEqual<Short>(value));
+ return 0;
+ }
+
+ /**
+ * comparable argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>null</code>.
+ */
+ public static <T extends Comparable<T>> T gt(T value) {
+ reportMatcher(new GreaterThan<T>(value));
+ return null;
+ }
+
+ /**
+ * byte argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static byte gt(byte value) {
+ reportMatcher(new GreaterThan<Byte>(value));
+ return 0;
+ }
+
+ /**
+ * double argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static double gt(double value) {
+ reportMatcher(new GreaterThan<Double>(value));
+ return 0;
+ }
+
+ /**
+ * float argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static float gt(float value) {
+ reportMatcher(new GreaterThan<Float>(value));
+ return 0;
+ }
+
+ /**
+ * int argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static int gt(int value) {
+ reportMatcher(new GreaterThan<Integer>(value));
+ return 0;
+ }
+
+ /**
+ * long argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static long gt(long value) {
+ reportMatcher(new GreaterThan<Long>(value));
+ return 0;
+ }
+
+ /**
+ * short argument greater than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static short gt(short value) {
+ reportMatcher(new GreaterThan<Short>(value));
+ return 0;
+ }
+
+ /**
+ * comparable argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>null</code>.
+ */
+ public static <T extends Comparable<T>> T lt(T value) {
+ reportMatcher(new LessThan<T>(value));
+ return null;
+ }
+
+ /**
+ * byte argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static byte lt(byte value) {
+ reportMatcher(new LessThan<Byte>(value));
+ return 0;
+ }
+
+ /**
+ * double argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static double lt(double value) {
+ reportMatcher(new LessThan<Double>(value));
+ return 0;
+ }
+
+ /**
+ * float argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static float lt(float value) {
+ reportMatcher(new LessThan<Float>(value));
+ return 0;
+ }
+
+ /**
+ * int argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static int lt(int value) {
+ reportMatcher(new LessThan<Integer>(value));
+ return 0;
+ }
+
+ /**
+ * long argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static long lt(long value) {
+ reportMatcher(new LessThan<Long>(value));
+ return 0;
+ }
+
+ /**
+ * short argument less than the given value.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>0</code>.
+ */
+ public static short lt(short value) {
+ reportMatcher(new LessThan<Short>(value));
+ return 0;
+ }
+
+ /**
+ * comparable argument equals to the given value according to their
+ * compareTo method.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @return <code>null</code>.
+ */
+ public static <T extends Comparable<T>> T cmpEq(T value) {
+ reportMatcher(new CompareEqual<T>(value));
+ return null;
+ }
+
+ /**
+ * String argument that contains a substring that matches the given regular
+ * expression.
+ *
+ * @param regex
+ * the regular expression.
+ * @return <code>null</code>.
+ */
+ public static String find(String regex) {
+ reportMatcher(new Find(regex));
+ return null;
+ }
+
+ /**
+ * Object array argument that is equal to the given array, i.e. it has to
+ * have the same type, length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param <T>
+ * the type of the array, it is passed through to prevent casts.
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static <T> T[] aryEq(T[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * short array argument that is equal to the given array, i.e. it has to
+ * have the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static short[] aryEq(short[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * long array argument that is equal to the given array, i.e. it has to have
+ * the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static long[] aryEq(long[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * int array argument that is equal to the given array, i.e. it has to have
+ * the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static int[] aryEq(int[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * float array argument that is equal to the given array, i.e. it has to
+ * have the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static float[] aryEq(float[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * double array argument that is equal to the given array, i.e. it has to
+ * have the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static double[] aryEq(double[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * char array argument that is equal to the given array, i.e. it has to have
+ * the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static char[] aryEq(char[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * byte array argument that is equal to the given array, i.e. it has to have
+ * the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static byte[] aryEq(byte[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * boolean array argument that is equal to the given array, i.e. it has to
+ * have the same length, and each element has to be equal.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given array.
+ * @return <code>null</code>.
+ */
+ public static boolean[] aryEq(boolean[] value) {
+ reportMatcher(new ArrayEquals(value));
+ return null;
+ }
+
+ /**
+ * boolean argument that matches both given matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>false</code>.
+ */
+ public static boolean and(boolean first, boolean second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return false;
+ }
+
+ /**
+ * byte argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static byte and(byte first, byte second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * char argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static char and(char first, char second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * double argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static double and(double first, double second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * float argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static float and(float first, float second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * int argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static int and(int first, int second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * long argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static long and(long first, long second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * short argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static short and(short first, short second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return 0;
+ }
+
+ /**
+ * Object argument that matches both given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param <T>
+ * the type of the object, it is passed through to prevent casts.
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>null</code>.
+ */
+ public static <T> T and(T first, T second) {
+ mockingProgress().getArgumentMatcherStorage().reportAnd();
+ return null;
+ }
+
+ /**
+ * boolean argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>false</code>.
+ */
+ public static boolean or(boolean first, boolean second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return false;
+ }
+
+ /**
+ * Object argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param <T>
+ * the type of the object, it is passed through to prevent casts.
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>null</code>.
+ */
+ public static <T> T or(T first, T second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return null;
+ }
+
+ /**
+ * short argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static short or(short first, short second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * long argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static long or(long first, long second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * int argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static int or(int first, int second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * float argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static float or(float first, float second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * double argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static double or(double first, double second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * char argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static char or(char first, char second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * byte argument that matches any of the given argument matchers.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the first argument matcher.
+ * @param second
+ * placeholder for the second argument matcher.
+ * @return <code>0</code>.
+ */
+ public static byte or(byte first, byte second) {
+ mockingProgress().getArgumentMatcherStorage().reportOr();
+ return 0;
+ }
+
+ /**
+ * Object argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param <T>
+ * the type of the object, it is passed through to prevent casts.
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>null</code>.
+ */
+ public static <T> T not(T first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return null;
+ }
+
+ /**
+ * short argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static short not(short first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * int argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static int not(int first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * long argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static long not(long first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * float argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static float not(float first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * double argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static double not(double first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * char argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static char not(char first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * boolean argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>false</code>.
+ */
+ public static boolean not(boolean first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return false;
+ }
+
+ /**
+ * byte argument that does not match the given argument matcher.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param first
+ * placeholder for the argument matcher.
+ * @return <code>0</code>.
+ */
+ public static byte not(byte first) {
+ mockingProgress().getArgumentMatcherStorage().reportNot();
+ return 0;
+ }
+
+ /**
+ * double argument that has an absolute difference to the given value that
+ * is less than the given delta details.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @param delta
+ * the given delta.
+ * @return <code>0</code>.
+ */
+ public static double eq(double value, double delta) {
+ reportMatcher(new EqualsWithDelta(value, delta));
+ return 0;
+ }
+
+ /**
+ * float argument that has an absolute difference to the given value that is
+ * less than the given delta details.
+ * <p>
+ * See examples in javadoc for {@link AdditionalMatchers} class
+ *
+ * @param value
+ * the given value.
+ * @param delta
+ * the given delta.
+ * @return <code>0</code>.
+ */
+ public static float eq(float value, float delta) {
+ reportMatcher(new EqualsWithDelta(value, delta));
+ return 0;
+ }
+
+ private static void reportMatcher(ArgumentMatcher<?> matcher) {
+ mockingProgress().getArgumentMatcherStorage().reportMatcher(matcher);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/Answers.java b/mockito-updated/src/org/mockito/Answers.java
new file mode 100644
index 0000000..f220089
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Answers.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import org.mockito.internal.stubbing.answers.CallsRealMethods;
+import org.mockito.internal.stubbing.defaultanswers.TriesToReturnSelf;
+import org.mockito.internal.stubbing.defaultanswers.GloballyConfiguredAnswer;
+import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs;
+import org.mockito.internal.stubbing.defaultanswers.ReturnsMocks;
+import org.mockito.internal.stubbing.defaultanswers.ReturnsSmartNulls;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Enumeration of pre-configured mock answers
+ * <p>
+ * You can use it to pass extra parameters to @Mock annotation, see more info here: {@link Mock}
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * @Mock(answer = RETURNS_DEEP_STUBS) UserProvider userProvider;
+ * </code></pre>
+ * <b>This is not the full list</b> of Answers available in Mockito. Some interesting answers can be found in org.mockito.stubbing.answers package.
+ */
+public enum Answers implements Answer<Object>{
+ /**
+ * The default configured answer of every mock.
+ *
+ * <p>Please see the {@link org.mockito.Mockito#RETURNS_DEFAULTS} documentation for more details.</p>
+ *
+ * @see org.mockito.Mockito#RETURNS_DEFAULTS
+ */
+ RETURNS_DEFAULTS(new GloballyConfiguredAnswer()),
+
+ /**
+ * An answer that returns smart-nulls.
+ *
+ * <p>Please see the {@link org.mockito.Mockito#RETURNS_SMART_NULLS} documentation for more details.</p>
+ *
+ * @see org.mockito.Mockito#RETURNS_SMART_NULLS
+ */
+ RETURNS_SMART_NULLS(new ReturnsSmartNulls()),
+
+ /**
+ * An answer that returns <strong>mocks</strong> (not stubs).
+ *
+ * <p>Please see the {@link org.mockito.Mockito#RETURNS_MOCKS} documentation for more details.</p>
+ *
+ * @see org.mockito.Mockito#RETURNS_MOCKS
+ */
+ RETURNS_MOCKS(new ReturnsMocks()),
+
+
+ /**
+ * An answer that returns <strong>deep stubs</strong> (not mocks).
+ *
+ * <p>Please see the {@link org.mockito.Mockito#RETURNS_DEEP_STUBS} documentation for more details.</p>
+ *
+ * @see org.mockito.Mockito#RETURNS_DEEP_STUBS
+ */
+ RETURNS_DEEP_STUBS(new ReturnsDeepStubs()),
+
+ /**
+ * An answer that calls the real methods (used for partial mocks).
+ *
+ * <p>Please see the {@link org.mockito.Mockito#CALLS_REAL_METHODS} documentation for more details.</p>
+ *
+ * @see org.mockito.Mockito#CALLS_REAL_METHODS
+ */
+ CALLS_REAL_METHODS(new CallsRealMethods()),
+
+ /**
+ * An answer that tries to return itself. This is useful for mocking {@code Builders}.
+ *
+ * <p>Please see the {@link org.mockito.Mockito#RETURNS_SELF} documentation for more details.</p>
+ *
+ * @see org.mockito.Mockito#RETURNS_SELF
+ */
+ RETURNS_SELF(new TriesToReturnSelf())
+ ;
+
+ private final Answer<Object> implementation;
+
+ Answers(Answer<Object> implementation) {
+ this.implementation = implementation;
+ }
+
+ /**
+ * @deprecated as of 2.1.0 Use the enum-constant directly, instead of this getter. This method will be removed in a future release<br>
+ * E.g. instead of <code>Answers.CALLS_REAL_METHODS.get()</code> use <code>Answers.CALLS_REAL_METHODS</code> .
+ */
+ @Deprecated
+ public Answer<Object> get() {
+ return this;
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return implementation.answer(invocation);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/ArgumentCaptor.java b/mockito-updated/src/org/mockito/ArgumentCaptor.java
new file mode 100644
index 0000000..972f25d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/ArgumentCaptor.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import static org.mockito.internal.util.Primitives.defaultValue;
+
+import java.util.List;
+
+import org.mockito.internal.matchers.CapturingMatcher;
+
+/**
+ * Use it to capture argument values for further assertions.
+ *
+ * <p>
+ * Mockito verifies argument values in natural java style: by using an equals() method.
+ * This is also the recommended way of matching arguments because it makes tests clean & simple.
+ * In some situations though, it is helpful to assert on certain arguments after the actual verification.
+ * For example:
+ * <pre class="code"><code class="java">
+ * ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
+ * verify(mock).doSomething(argument.capture());
+ * assertEquals("John", argument.getValue().getName());
+ * </code></pre>
+ *
+ * Example of capturing varargs:
+ * <pre class="code"><code class="java">
+ * //capturing varargs:
+ * ArgumentCaptor<Person> varArgs = ArgumentCaptor.forClass(Person.class);
+ * verify(mock).varArgMethod(varArgs.capture());
+ * List expected = asList(new Person("John"), new Person("Jane"));
+ * assertEquals(expected, varArgs.getAllValues());
+ * </code></pre>
+ *
+ * <p>
+ * <strong>Warning:</strong> it is recommended to use ArgumentCaptor with verification <strong>but not</strong> with stubbing.
+ * Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block.
+ * Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
+ *
+ * <p>
+ * In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
+ * Both techniques can be used for making sure certain arguments where passed to mocks.
+ * However, ArgumentCaptor may be a better fit if:
+ * <ul>
+ * <li>custom argument matcher is not likely to be reused</li>
+ * <li>you just need it to assert on argument values to complete verification</li>
+ * </ul>
+ * Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
+ *
+ * <p>
+ * This utility class <strong>*don't do any type checks*</strong>, the generic signatures are only there to avoid casting
+ * in your code.
+ * <p>
+ * There is an <strong>annotation</strong> that you might find useful: @{@link Captor}
+ * <p>
+ * See the full documentation on Mockito in javadoc for {@link Mockito} class.
+ *
+ * @see Captor
+ * @since 1.8.0
+ */
+public class ArgumentCaptor<T> {
+
+
+ private final CapturingMatcher<T> capturingMatcher = new CapturingMatcher<T>();
+ private final Class<? extends T> clazz;
+
+ private ArgumentCaptor(Class<? extends T> clazz) {
+ this.clazz = clazz;
+ }
+
+ /**
+ * Use it to capture the argument. This method <b>must be used inside of verification</b>.
+ * <p>
+ * Internally, this method registers a special implementation of an {@link ArgumentMatcher}.
+ * This argument matcher stores the argument value so that you can use it later to perform assertions.
+ * <p>
+ * See examples in javadoc for {@link ArgumentCaptor} class.
+ *
+ * @return null or default values
+ */
+ public T capture() {
+ Mockito.argThat(capturingMatcher);
+ return defaultValue(clazz);
+ }
+
+ /**
+ * Returns the captured value of the argument. When capturing varargs use {@link #getAllValues()}.
+ * <p>
+ * If verified method was called multiple times then this method it returns the latest captured value.
+ * <p>
+ * See examples in javadoc for {@link ArgumentCaptor} class.
+ *
+ * @return captured argument value
+ */
+ public T getValue() {
+ return this.capturingMatcher.getLastValue();
+ }
+
+ /**
+ * Returns all captured values. Use it when capturing varargs or when the verified method was called multiple times.
+ * When varargs method was called multiple times, this method returns merged list of all values from all invocations.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * mock.doSomething(new Person("John");
+ * mock.doSomething(new Person("Jane");
+ *
+ * ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
+ * verify(mock, times(2)).doSomething(peopleCaptor.capture());
+ *
+ * List<Person> capturedPeople = peopleCaptor.getAllValues();
+ * assertEquals("John", capturedPeople.get(0).getName());
+ * assertEquals("Jane", capturedPeople.get(1).getName());
+ * </pre>
+ *
+ * Example of capturing varargs:
+ * <pre class="code"><code class="java">
+ * mock.countPeople(new Person("John"), new Person("Jane"); //vararg method
+ *
+ * ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
+ *
+ * verify(mock).countPeople(peopleCaptor.capture());
+ *
+ * List expected = asList(new Person("John"), new Person("Jane"));
+ * assertEquals(expected, peopleCaptor.getAllValues());
+ * </code></pre>
+ * See more examples in javadoc for {@link ArgumentCaptor} class.
+ *
+ * @return captured argument value
+ */
+ public List<T> getAllValues() {
+ return this.capturingMatcher.getAllValues();
+ }
+
+ /**
+ * Build a new <code>ArgumentCaptor</code>.
+ * <p>
+ * Note that an <code>ArgumentCaptor</code> <b>*don't do any type checks*</b>, it is only there to avoid casting
+ * in your code. This might however change (type checks could be added) in a
+ * future major release.
+ *
+ * @param clazz Type matching the parameter to be captured.
+ * @param <S> Type of clazz
+ * @param <U> Type of object captured by the newly built ArgumentCaptor
+ * @return A new ArgumentCaptor
+ */
+ public static <U,S extends U> ArgumentCaptor<U> forClass(Class<S> clazz) {
+ return new ArgumentCaptor<U>(clazz);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/ArgumentMatcher.java b/mockito-updated/src/org/mockito/ArgumentMatcher.java
new file mode 100644
index 0000000..6b0fe37
--- /dev/null
+++ b/mockito-updated/src/org/mockito/ArgumentMatcher.java
@@ -0,0 +1,124 @@
+package org.mockito;
+
+/**
+ * Allows creating customized argument matchers.
+ * This API was changed in Mockito 2.1.0 in an effort to decouple Mockito from Hamcrest
+ * and reduce the risk of version incompatibility.
+ * Migration guide is included close to the bottom of this javadoc.
+ * <p>
+ * For non-trivial method arguments used in stubbing or verification, you have following options
+ * (in no particular order):
+ * <ul>
+ * <li>refactor the code so that the interactions with collaborators are easier to test with mocks.
+ * Perhaps it is possible to pass a different argument to the method so that mocking is easier?
+ * If stuff is hard to test it usually indicates the design could be better, so do refactor for testability!
+ * </li>
+ * <li>don't match the argument strictly, just use one of the lenient argument matchers like
+ * {@link Mockito#notNull()}. Some times it is better to have a simple test that works than
+ * a complicated test that seem to work.
+ * </li>
+ * <li>implement equals() method in the objects that are used as arguments to mocks.
+ * Mockito naturally uses equals() for argument matching.
+ * Many times, this is option is clean and simple.
+ * </li>
+ * <li>use {@link ArgumentCaptor} to capture the arguments and perform assertions on their state.
+ * Useful when you need to verify the arguments. Captor is not useful if you need argument matching for stubbing.
+ * Many times, this option leads to clean and readable tests with fine-grained validation of arguments.
+ * </li>
+ * <li>use customized argument matchers by implementing {@link ArgumentMatcher} interface
+ * and passing the implementation to the {@link Mockito#argThat} method.
+ * This option is useful if custom matcher is needed for stubbing and can be reused a lot.
+ * Note that {@link Mockito#argThat} demonstrates <b>NullPointerException</b> auto-unboxing caveat.
+ * </li>
+ * <li>use an instance of hamcrest matcher and pass it to
+ * {@link org.mockito.hamcrest.MockitoHamcrest#argThat(org.hamcrest.Matcher)}
+ * Useful if you already have a hamcrest matcher. Reuse and win!
+ * Note that {@link org.mockito.hamcrest.MockitoHamcrest#argThat(org.hamcrest.Matcher)} demonstrates <b>NullPointerException</b> auto-unboxing caveat.
+ * </li>
+ * <li>Java 8 only - use a lambda in place of an {@link ArgumentMatcher} since {@link ArgumentMatcher}
+ * is effectively a functional interface. A lambda can be used with the {@link Mockito#argThat} method.</li>
+ * </ul>
+ *
+ * <p>
+ * Implementations of this interface can be used with {@link Matchers#argThat} method.
+ * Use <code>toString()</code> method for description of the matcher
+ * - it is printed in verification errors.
+ *
+ * <pre class="code"><code class="java">
+ * class ListOfTwoElements implements ArgumentMatcher<List> {
+ * public boolean matches(List list) {
+ * return list.size() == 2;
+ * }
+ * public String toString() {
+ * //printed in verification errors
+ * return "[list of 2 elements]";
+ * }
+ * }
+ *
+ * List mock = mock(List.class);
+ *
+ * when(mock.addAll(argThat(new ListOfTwoElements))).thenReturn(true);
+ *
+ * mock.addAll(Arrays.asList("one", "two"));
+ *
+ * verify(mock).addAll(argThat(new ListOfTwoElements()));
+ * </code></pre>
+ *
+ * To keep it readable you can extract method, e.g:
+ *
+ * <pre class="code"><code class="java">
+ * verify(mock).addAll(<b>argThat(new ListOfTwoElements())</b>);
+ * //becomes
+ * verify(mock).addAll(<b>listOfTwoElements()</b>);
+ * </code></pre>
+ *
+ * In Java 8 you can treat ArgumentMatcher as a functional interface
+ * and use a lambda, e.g.:
+ *
+ * <pre class="code"><code class="java">
+ * verify(mock).addAll(<b>argThat(list -> list.size() == 2)</b>);
+ * </code></pre>
+ *
+ * <p>
+ * Read more about other matchers in javadoc for {@link Matchers} class.
+ * <h2>2.1.0 migration guide</h2>
+ *
+ * All existing custom implementations of <code>ArgumentMatcher</code> will no longer compile.
+ * All locations where hamcrest matchers are passed to <code>argThat()</code> will no longer compile.
+ * There are 2 approaches to fix the problems:
+ * <ul>
+ * <li>a) Refactor the hamcrest matcher to Mockito matcher:
+ * Use "implements ArgumentMatcher" instead of "extends ArgumentMatcher".
+ * Then refactor <code>describeTo()</code> method into <code>toString()</code> method.
+ * </li>
+ * <li>
+ * b) Use <code>org.mockito.hamcrest.MockitoHamcrest.argThat()</code> instead of <code>Mockito.argThat()</code>.
+ * Ensure that there is <a href="http://hamcrest.org/JavaHamcrest/">hamcrest</a> dependency on classpath
+ * (Mockito does not depend on hamcrest any more).
+ *
+ * </li>
+ * </ul>
+ * What option is right for you? If you don't mind compile dependency to hamcrest
+ * then option b) is probably right for you.
+ * Your choice should not have big impact and is fully reversible -
+ * you can choose different option in future (and refactor the code)
+ *
+ * @param <T> type of argument
+ * @since 2.1.0
+ */
+public interface ArgumentMatcher<T> {
+
+ /**
+ * Informs if this matcher accepts the given argument.
+ * <p>
+ * The method should <b>never</b> assert if the argument doesn't match. It
+ * should only return false.
+ * <p>
+ * See the example in the top level javadoc for {@link ArgumentMatcher}
+ *
+ * @param argument
+ * the argument
+ * @return true if this matcher accepts the given argument.
+ */
+ boolean matches(T argument);
+}
diff --git a/mockito-updated/src/org/mockito/ArgumentMatchers.java b/mockito-updated/src/org/mockito/ArgumentMatchers.java
new file mode 100644
index 0000000..3b87a28
--- /dev/null
+++ b/mockito-updated/src/org/mockito/ArgumentMatchers.java
@@ -0,0 +1,1278 @@
+package org.mockito;
+
+import org.mockito.internal.matchers.Any;
+import org.mockito.internal.matchers.Contains;
+import org.mockito.internal.matchers.EndsWith;
+import org.mockito.internal.matchers.Equals;
+import org.mockito.internal.matchers.InstanceOf;
+import org.mockito.internal.matchers.Matches;
+import org.mockito.internal.matchers.NotNull;
+import org.mockito.internal.matchers.Null;
+import org.mockito.internal.matchers.Same;
+import org.mockito.internal.matchers.StartsWith;
+import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
+import org.mockito.internal.util.Primitives;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+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}.
+ *
+ * <p>
+ * {@link Mockito} extends ArgumentMatchers so to get access to all matchers just import Mockito class statically.
+ *
+ * <pre class="code"><code class="java">
+ * //stubbing using anyInt() argument matcher
+ * when(mockedList.get(anyInt())).thenReturn("element");
+ *
+ * //following prints "element"
+ * System.out.println(mockedList.get(999));
+ *
+ * //you can also verify using argument matcher
+ * verify(mockedList).get(anyInt());
+ * </code></pre>
+ *
+ * <p>
+ * Since Mockito <code>any(Class)</code> and <code>anyInt</code> family matchers perform a type check, thus they won't
+ * match <code>null</code> arguments. Instead use the <code>isNull</code> matcher.
+ *
+ * <pre class="code"><code class="java">
+ * // stubbing using anyBoolean() argument matcher
+ * when(mock.dryRun(anyBoolean())).thenReturn("state");
+ *
+ * // below the stub won't match, and won't return "state"
+ * mock.dryRun(null);
+ *
+ * // either change the stub
+ * when(mock.dryRun(isNull())).thenReturn("state");
+ * mock.dryRun(null); // ok
+ *
+ * // or fix the code ;)
+ * when(mock.dryRun(anyBoolean())).thenReturn("state");
+ * mock.dryRun(true); // ok
+ *
+ * </code></pre>
+ *
+ * The same apply for verification.
+ * </p>
+ *
+ *
+ * Scroll down to see all methods - full list of matchers.
+ *
+ * <p>
+ * <b>Warning:</b><br/>
+ *
+ * If you are using argument matchers, <b>all arguments</b> have to be provided by matchers.
+ *
+ * E.g: (example shows verification but the same applies to stubbing):
+ * </p>
+ *
+ * <pre class="code"><code class="java">
+ * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
+ * //above is correct - eq() is also an argument matcher
+ *
+ * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
+ * //above is incorrect - exception will be thrown because third argument is given without argument matcher.
+ * </code></pre>
+ *
+ * <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.
+ * The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
+ * </p>
+ *
+ * <h1>Custom Argument ArgumentMatchers</h1>
+ * <p>
+ * It is important to understand the use cases and available options for dealing with non-trivial arguments
+ * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach
+ * for given scenario and produce highest quality test (clean and maintainable).
+ * Please read on in the javadoc for {@link ArgumentMatcher} to learn about approaches and see the examples.
+ * </p>
+ */
+@SuppressWarnings("unchecked")
+public class ArgumentMatchers {
+
+ /**
+ * Matches <strong>anything</strong>, including nulls and varargs.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * This is an alias of: {@link #anyObject()} and {@link #any(java.lang.Class)}
+ * </p>
+ *
+ * <p>
+ * <strong>Notes : </strong><br/>
+ * <ul>
+ * <li>For primitive types use {@link #anyChar()} family or {@link #isA(Class)} or {@link #any(Class)}.</li>
+ * <li>Since mockito 2.1.0 {@link #any(Class)} is not anymore an alias of this method.</li>
+ * </ul>
+ * </p>
+ *
+ * @return <code>null</code>.
+ *
+ * @see #any(Class)
+ * @see #anyObject()
+ * @see #anyVararg()
+ * @see #anyChar()
+ * @see #anyInt()
+ * @see #anyBoolean()
+ * @see #anyCollectionOf(Class)
+ */
+ public static <T> T any() {
+ return anyObject();
+ }
+
+ /**
+ * Matches anything, including <code>null</code>.
+ *
+ * <p>
+ * This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}.
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>null</code>.
+ * @see #any()
+ * @see #any(Class)
+ * @see #notNull()
+ * @see #notNull(Class)
+ * @deprecated This will be removed in Mockito 3.0 (which will be java 8 only)
+ */
+ @Deprecated
+ public static <T> T anyObject() {
+ reportMatcher(Any.ANY);
+ return null;
+ }
+
+ /**
+ * Matches any object of given type, excluding nulls.
+ *
+ * <p>
+ * This matcher will perform a type check with the given type, thus excluding values.
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ *
+ * This is an alias of: {@link #isA(Class)}}
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null instance of <code></code>, thus <code>null</code> is not anymore a valid value.
+ * As reference are nullable, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p><strong>Notes : </strong><br/>
+ * <ul>
+ * <li>For primitive types use {@link #anyChar()} family.</li>
+ * <li>Since Mockito 2.1.0 this method will perform a type check thus <code>null</code> values are not authorized.</li>
+ * <li>Since mockito 2.1.0 {@link #any()} and {@link #anyObject()} are not anymore aliases of this method.</li>
+ * </ul>
+ * </p>
+ *
+ * @param <T> The accepted type
+ * @param type the class of the accepted type.
+ * @return <code>null</code>.
+ * @see #any()
+ * @see #anyObject()
+ * @see #anyVararg()
+ * @see #isA(Class)
+ * @see #notNull()
+ * @see #notNull(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static <T> T any(Class<T> type) {
+ reportMatcher(new InstanceOf.VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
+ return defaultValue(type);
+ }
+
+ /**
+ * <code>Object</code> argument that implements the given class.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param <T> the accepted type.
+ * @param type the class of the accepted type.
+ * @return <code>null</code>.
+ * @see #any(Class)
+ */
+ public static <T> T isA(Class<T> type) {
+ reportMatcher(new InstanceOf(type));
+ return defaultValue(type);
+ }
+
+ /**
+ * Any vararg, meaning any number and values of arguments.
+ *
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * //verification:
+ * mock.foo(1, 2);
+ * mock.foo(1, 2, 3, 4);
+ *
+ * verify(mock, times(2)).foo(anyVararg());
+ *
+ * //stubbing:
+ * when(mock.foo(anyVararg()).thenReturn(100);
+ *
+ * //prints 100
+ * System.out.println(mock.foo(1, 2));
+ * //also prints 100
+ * System.out.println(mock.foo(1, 2, 3, 4));
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>null</code>.
+ * @see #any()
+ * @see #any(Class)
+ * @deprecated as of 2.1.0 use {@link #any()}
+ */
+ @Deprecated
+ public static <T> T anyVararg() {
+ any();
+ return null;
+ }
+
+ /**
+ * Any <code>boolean</code> or <strong>non-null</strong> <code>Boolean</code>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Boolean</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>false</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static boolean anyBoolean() {
+ reportMatcher(new InstanceOf(Boolean.class, "<any boolean>"));
+ return false;
+ }
+
+ /**
+ * Any <code>byte</code> or <strong>non-null</strong> <code>Byte</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Byte</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static byte anyByte() {
+ reportMatcher(new InstanceOf(Byte.class, "<any byte>"));
+ return 0;
+ }
+
+ /**
+ * Any <code>char</code> or <strong>non-null</strong> <code>Character</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Character</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static char anyChar() {
+ reportMatcher(new InstanceOf(Character.class, "<any char>"));
+ return 0;
+ }
+
+ /**
+ * Any int or <strong>non-null</strong> <code>Integer</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Integer</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static int anyInt() {
+ reportMatcher(new InstanceOf(Integer.class, "<any integer>"));
+ return 0;
+ }
+
+ /**
+ * Any <code>long</code> or <strong>non-null</strong> <code>Long</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Long</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static long anyLong() {
+ reportMatcher(new InstanceOf(Long.class, "<any long>"));
+ return 0;
+ }
+
+ /**
+ * Any <code>float</code> or <strong>non-null</strong> <code>Float</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Float</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static float anyFloat() {
+ reportMatcher(new InstanceOf(Float.class, "<any float>"));
+ return 0;
+ }
+
+ /**
+ * Any <code>double</code> or <strong>non-null</strong> <code>Double</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Double</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static double anyDouble() {
+ reportMatcher(new InstanceOf(Double.class, "<any double>"));
+ return 0;
+ }
+
+ /**
+ * Any <code>short</code> or <strong>non-null</strong> <code>Short</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow valued <code>Short</code>, thus <code>null</code> is not anymore a valid value.
+ * As primitive wrappers are nullable, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return <code>0</code>.
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static short anyShort() {
+ reportMatcher(new InstanceOf(Short.class, "<any short>"));
+ return 0;
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>String</code>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>String</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty String ("")
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static String anyString() {
+ reportMatcher(new InstanceOf(String.class, "<any string>"));
+ return "";
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>List</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>List</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty List.
+ * @see #anyListOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static <T> List<T> anyList() {
+ reportMatcher(new InstanceOf(List.class, "<any List>"));
+ return new ArrayList<T>(0);
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>List</code>.
+ *
+ * Generic friendly alias to {@link ArgumentMatchers#anyList()}. It's an alternative to
+ * <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ *
+ * <p>
+ * This method doesn't do type checks of the list content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>List</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @param clazz Type owned by the list to avoid casting
+ * @return empty List.
+ * @see #anyList()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> List<T> anyListOf(Class<T> clazz) {
+ return anyList();
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Set</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Set</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty Set
+ * @see #anySetOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static <T> Set<T> anySet() {
+ reportMatcher(new InstanceOf(Set.class, "<any set>"));
+ return new HashSet<T>(0);
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Set</code>.
+ *
+ * <p>
+ * Generic friendly alias to {@link ArgumentMatchers#anySet()}.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
+ * <p>
+ * This method doesn't do type checks of the set content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Set</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @param clazz Type owned by the Set to avoid casting
+ * @return empty Set
+ * @see #anySet()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> Set<T> anySetOf(Class<T> clazz) {
+ return anySet();
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Map</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Map</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty Map.
+ * @see #anyMapOf(Class, Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static <K, V> Map<K, V> anyMap() {
+ reportMatcher(new InstanceOf(Map.class, "<any map>"));
+ return new HashMap<K, V>(0);
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Map</code>.
+ *
+ * <p>
+ * Generic friendly alias to {@link ArgumentMatchers#anyMap()}.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
+ * <p>
+ * This method doesn't do type checks of the map content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Map</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @param keyClazz Type of the map key to avoid casting
+ * @param valueClazz Type of the value to avoid casting
+ * @return empty Map.
+ * @see #anyMap()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <K, V> Map<K, V> anyMapOf(Class<K> keyClazz, Class<V> valueClazz) {
+ return anyMap();
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Collection</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Collection</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty Collection.
+ * @see #anyCollectionOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static <T> Collection<T> anyCollection() {
+ reportMatcher(new InstanceOf(Collection.class, "<any collection>"));
+ return new ArrayList<T>(0);
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Collection</code>.
+ *
+ * <p>
+ * Generic friendly alias to {@link ArgumentMatchers#anyCollection()}.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
+ * <p>
+ * This method doesn't do type checks of the collection content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Collection</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @param clazz Type owned by the collection to avoid casting
+ * @return empty Collection.
+ * @see #anyCollection()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> Collection<T> anyCollectionOf(Class<T> clazz) {
+ return anyCollection();
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Iterable</code>.
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>Iterable</code>.
+ * As this is a nullable reference, the suggested API to <strong>match</strong> <code>null</code>
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @return empty Iterable.
+ * @see #anyIterableOf(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @since 2.1.0
+ */
+ public static <T> Iterable<T> anyIterable() {
+ reportMatcher(new InstanceOf(Iterable.class, "<any iterable>"));
+ return new ArrayList<T>(0);
+ }
+
+ /**
+ * Any <strong>non-null</strong> <code>Iterable</code>.
+ *
+ * <p>
+ * Generic friendly alias to {@link ArgumentMatchers#anyIterable()}.
+ * It's an alternative to <code>@SuppressWarnings("unchecked")</code> to keep code clean of compiler warnings.
+ * </p>
+ *
+ * <p>
+ * This method doesn't do type checks of the iterable content with the given type parameter, it is only there
+ * to avoid casting in the code.
+ * </p>
+ *
+ * <p>
+ * Since Mockito 2.1.0, only allow non-null <code>String</code>.
+ * As strings are nullable reference, the suggested API to <strong>match</strong> <code>null</code> wrapper
+ * would be {@link #isNull()}. We felt this change would make tests harness much safer that it was with Mockito
+ * 1.x.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class.
+ * </p>
+ *
+ * @param clazz Type owned by the collection to avoid casting
+ * @return empty Iterable.
+ * @see #anyIterable()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @since 2.1.0
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> Iterable<T> anyIterableOf(Class<T> clazz) {
+ return anyIterable();
+ }
+
+
+
+ /**
+ * <code>boolean</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static boolean eq(boolean value) {
+ reportMatcher(new Equals(value));
+ return false;
+ }
+
+ /**
+ * <code>byte</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static byte eq(byte value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * <code>char</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static char eq(char value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * <code>double</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static double eq(double value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * <code>float</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static float eq(float value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * <code>int</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static int eq(int value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * <code>long</code> argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static long eq(long value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * <code>short</code> argument that is equal to the given value.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param value the given value.
+ * @return <code>0</code>.
+ */
+ public static short eq(short value) {
+ reportMatcher(new Equals(value));
+ return 0;
+ }
+
+ /**
+ * Object argument that is equal to the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @return <code>null</code>.
+ */
+ public static <T> T eq(T value) {
+ reportMatcher(new Equals(value));
+ if (value == null)
+ return null;
+ return (T) Primitives.defaultValue(value.getClass());
+ }
+
+ /**
+ * Object argument that is reflection-equal to the given value with support for excluding
+ * selected fields from a class.
+ *
+ * <p>
+ * This matcher can be used when equals() is not implemented on compared objects.
+ * Matcher uses java reflection API to compare fields of wanted and actual object.
+ * </p>
+ *
+ * <p>
+ * Works similarly to <code>EqualsBuilder.reflectionEquals(this, other, exlucdeFields)</code> from
+ * apache commons library.
+ * <p>
+ * <b>Warning</b> The equality check is shallow!
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param value the given value.
+ * @param excludeFields fields to exclude, if field does not exist it is ignored.
+ * @return <code>null</code>.
+ */
+ public static <T> T refEq(T value, String... excludeFields) {
+ reportMatcher(new ReflectionEquals(value, excludeFields));
+ return null;
+ }
+
+ /**
+ * Object argument that is the same as the given value.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param <T> the type of the object, it is passed through to prevent casts.
+ * @param value the given value.
+ * @return <code>null</code>.
+ */
+ public static <T> T same(T value) {
+ reportMatcher(new Same(value));
+ if (value == null)
+ return null;
+ return (T) Primitives.defaultValue(value.getClass());
+ }
+
+ /**
+ * <code>null</code> argument.
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @return <code>null</code>.
+ * @see #isNull(Class)
+ * @see #isNotNull()
+ * @see #isNotNull(Class)
+ */
+ public static <T> T isNull() {
+ reportMatcher(Null.NULL);
+ return null;
+ }
+
+ /**
+ * <code>null</code> argument.
+ *
+ * <p>
+ * The class argument is provided to avoid casting.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param clazz Type to avoid casting
+ * @return <code>null</code>.
+ * @see #isNull()
+ * @see #isNotNull()
+ * @see #isNotNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> T isNull(Class<T> clazz) {
+ return isNull();
+ }
+
+ /**
+ * Not <code>null</code> argument.
+ *
+ * <p>
+ * Alias to {@link ArgumentMatchers#isNotNull()}
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @return <code>null</code>.
+ */
+ public static <T> T notNull() {
+ reportMatcher(NotNull.NOT_NULL);
+ return null;
+ }
+
+ /**
+ * Not <code>null</code> argument, not necessary of the given class.
+ *
+ * <p>
+ * The class argument is provided to avoid casting.
+ *
+ * Alias to {@link ArgumentMatchers#isNotNull(Class)}
+ * <p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param clazz Type to avoid casting
+ * @return <code>null</code>.
+ * @see #isNotNull()
+ * @see #isNull()
+ * @see #isNull(Class)
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> T notNull(Class<T> clazz) {
+ return notNull();
+ }
+
+ /**
+ * Not <code>null</code> argument.
+ *
+ * <p>
+ * Alias to {@link ArgumentMatchers#notNull()}
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @return <code>null</code>.
+ * @see #isNotNull(Class)
+ * @see #isNull()
+ * @see #isNull(Class)
+ */
+ public static <T> T isNotNull() {
+ return notNull();
+ }
+
+ /**
+ * Not <code>null</code> argument, not necessary of the given class.
+ *
+ * <p>
+ * The class argument is provided to avoid casting.
+ * Alias to {@link ArgumentMatchers#notNull(Class)}
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ * </p>
+ *
+ * @param clazz Type to avoid casting
+ * @return <code>null</code>.
+ * @deprecated With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic
+ * friendliness to avoid casting, this is not anymore needed in Java 8.
+ */
+ public static <T> T isNotNull(Class<T> clazz) {
+ return notNull(clazz);
+ }
+
+ /**
+ * <code>String</code> argument that contains the given substring.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param substring the substring.
+ * @return empty String ("").
+ */
+ public static String contains(String substring) {
+ reportMatcher(new Contains(substring));
+ return "";
+ }
+
+ /**
+ * <code>String</code> argument that matches the given regular expression.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param regex the regular expression.
+ * @return empty String ("").
+ */
+ public static String matches(String regex) {
+ reportMatcher(new Matches(regex));
+ return "";
+ }
+
+ /**
+ * <code>String</code> argument that ends with the given suffix.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param suffix the suffix.
+ * @return empty String ("").
+ */
+ public static String endsWith(String suffix) {
+ reportMatcher(new EndsWith(suffix));
+ return "";
+ }
+
+ /**
+ * <code>String</code> argument that starts with the given prefix.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param prefix the prefix.
+ * @return empty String ("").
+ */
+ public static String startsWith(String prefix) {
+ reportMatcher(new StartsWith(prefix));
+ return "";
+ }
+
+ /**
+ * Allows creating custom argument matchers.
+ *
+ * <p>
+ * This API has changed in 2.1.0, please read {@link ArgumentMatcher} for rationale and migration guide.
+ * <b>NullPointerException</b> auto-unboxing caveat is described below.
+ * </p>
+ *
+ * <p>
+ * It is important to understand the use cases and available options for dealing with non-trivial arguments
+ * <b>before</b> implementing custom argument matchers. This way, you can select the best possible approach
+ * for given scenario and produce highest quality test (clean and maintainable).
+ * Please read the documentation for {@link ArgumentMatcher} to learn about approaches and see the examples.
+ * </p>
+ *
+ * <p>
+ * <b>NullPointerException</b> auto-unboxing caveat.
+ * In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method.
+ * This way you will avoid <code>NullPointerException</code> during auto-unboxing.
+ * Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem.
+ * Hopefully, the javadoc describes the problem and solution well.
+ * If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker.
+ * </p>
+ *
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatcher} class
+ * </p>
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>null</code>.
+ */
+ public static <T> T argThat(ArgumentMatcher<T> matcher) {
+ reportMatcher(matcher);
+ return null;
+ }
+
+ /**
+ * Allows creating custom <code>char</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static char charThat(ArgumentMatcher<Character> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Allows creating custom <code>boolean</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>false</code>.
+ */
+ public static boolean booleanThat(ArgumentMatcher<Boolean> matcher) {
+ reportMatcher(matcher);
+ return false;
+ }
+
+ /**
+ * Allows creating custom <code>byte</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static byte byteThat(ArgumentMatcher<Byte> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Allows creating custom <code>short</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static short shortThat(ArgumentMatcher<Short> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Allows creating custom <code>int</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static int intThat(ArgumentMatcher<Integer> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Allows creating custom <code>long</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static long longThat(ArgumentMatcher<Long> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Allows creating custom <code>float</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static float floatThat(ArgumentMatcher<Float> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Allows creating custom <code>double</code> argument matchers.
+ *
+ * Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p>
+ * See examples in javadoc for {@link ArgumentMatchers} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static double doubleThat(ArgumentMatcher<Double> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ private static void reportMatcher(ArgumentMatcher<?> matcher) {
+ mockingProgress().getArgumentMatcherStorage().reportMatcher(matcher);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/BDDMockito.java b/mockito-updated/src/org/mockito/BDDMockito.java
new file mode 100644
index 0000000..9090fa8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/BDDMockito.java
@@ -0,0 +1,529 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.OngoingStubbing;
+import org.mockito.stubbing.Stubber;
+import org.mockito.verification.VerificationMode;
+
+/**
+ * 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!
+ * <p>
+ * Start learning about BDD here: <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">http://en.wikipedia.org/wiki/Behavior_Driven_Development</a>
+ * <p>
+ * The problem is that current stubbing api with canonical role of <b>when</b> word does not integrate nicely with <b>//given //when //then</b> comments.
+ * It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test.
+ * Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
+ * Now it really nicely integrates with the <b>given</b> component of a BDD style test!
+ * <p>
+ * Here is how the test might look like:
+ * <pre class="code"><code class="java">
+ * import static org.mockito.BDDMockito.*;
+ *
+ * Seller seller = mock(Seller.class);
+ * Shop shop = new Shop(seller);
+ *
+ * public void shouldBuyBread() throws Exception {
+ * //given
+ * given(seller.askForBread()).willReturn(new Bread());
+ *
+ * //when
+ * Goods goods = shop.buyBread();
+ *
+ * //then
+ * assertThat(goods, containBread());
+ * }
+ * </code></pre>
+ *
+ * Stubbing voids with throwables:
+ * <pre class="code"><code class="java">
+ * //given
+ * willThrow(new RuntimeException("boo")).given(mock).foo();
+ *
+ * //when
+ * Result result = systemUnderTest.perform();
+ *
+ * //then
+ * assertEquals(failure, result);
+ * </code></pre>
+ * <p>
+ * For BDD style mock verification take a look at {@link Then} in action:
+ * <pre class="code"><code class="java">
+ * person.ride(bike);
+ * person.ride(bike);
+ *
+ * then(person).should(times(2)).ride(bike);
+ * then(person).shouldHaveNoMoreInteractions();
+ * then(police).shouldHaveZeroInteractions();
+ * </code></pre>
+ * <p>
+ * It is also possible to do BDD style {@link InOrder} verification:
+ * <pre class="code"><code class="java">
+ * InOrder inOrder = inOrder(person);
+ *
+ * person.drive(car);
+ * person.ride(bike);
+ * person.ride(bike);
+ *
+ * then(person).should(inOrder).drive(car);
+ * then(person).should(inOrder, times(2)).ride(bike);
+ * </code></pre>
+ * <p>
+ * One of the purposes of BDDMockito is also to show how to tailor the mocking syntax to a different programming style.
+ *
+ * @since 1.8.0
+ */
+@SuppressWarnings("unchecked")
+public class BDDMockito extends Mockito {
+
+ /**
+ * See original {@link OngoingStubbing}
+ * @since 1.8.0
+ */
+ public interface BDDMyOngoingStubbing<T> {
+
+ /**
+ * See original {@link OngoingStubbing#thenAnswer(Answer)}
+ * @since 1.8.0
+ */
+ BDDMyOngoingStubbing<T> willAnswer(Answer<?> answer);
+
+ /**
+ * See original {@link OngoingStubbing#then(Answer)}
+ * @since 1.9.0
+ */
+ BDDMyOngoingStubbing<T> will(Answer<?> answer);
+
+ /**
+ * See original {@link OngoingStubbing#thenReturn(Object)}
+ * @since 1.8.0
+ */
+ BDDMyOngoingStubbing<T> willReturn(T value);
+
+ /**
+ * See original {@link OngoingStubbing#thenReturn(Object, Object[])}
+ * @since 1.8.0
+ */
+ @SuppressWarnings({"unchecked", "varargs"})
+ BDDMyOngoingStubbing<T> willReturn(T value, T... values);
+
+ /**
+ * See original {@link OngoingStubbing#thenThrow(Throwable...)}
+ * @since 1.8.0
+ */
+ BDDMyOngoingStubbing<T> willThrow(Throwable... throwables);
+
+ /**
+ * See original {@link OngoingStubbing#thenThrow(Class)}
+ * @since 2.1.0
+ */
+ BDDMyOngoingStubbing<T> willThrow(Class<? extends Throwable> throwableType);
+
+ /**
+ * See original {@link OngoingStubbing#thenThrow(Class, Class[])}
+ * @since 2.1.0
+ */
+ // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
+ @SuppressWarnings ({"unchecked", "varargs"})
+ BDDMyOngoingStubbing<T> willThrow(Class<? extends Throwable> throwableType, Class<? extends Throwable>... throwableTypes);
+
+ /**
+ * See original {@link OngoingStubbing#thenCallRealMethod()}
+ * @since 1.9.0
+ */
+ BDDMyOngoingStubbing<T> willCallRealMethod();
+
+ /**
+ * See original {@link OngoingStubbing#getMock()}
+ * @since 1.9.0
+ */
+ <M> M getMock();
+ }
+
+ private static class BDDOngoingStubbingImpl<T> implements BDDMyOngoingStubbing<T> {
+
+ private final OngoingStubbing<T> mockitoOngoingStubbing;
+
+ public BDDOngoingStubbingImpl(OngoingStubbing<T> ongoingStubbing) {
+ this.mockitoOngoingStubbing = ongoingStubbing;
+ }
+
+ public BDDMyOngoingStubbing<T> willAnswer(Answer<?> answer) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenAnswer(answer));
+ }
+
+ public BDDMyOngoingStubbing<T> will(Answer<?> answer) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.then(answer));
+ }
+
+ public BDDMyOngoingStubbing<T> willReturn(T value) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenReturn(value));
+ }
+
+ public BDDMyOngoingStubbing<T> willReturn(T value, T... values) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenReturn(value, values));
+ }
+
+ public BDDMyOngoingStubbing<T> willThrow(Throwable... throwables) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenThrow(throwables));
+ }
+
+ public BDDMyOngoingStubbing<T> willThrow(Class<? extends Throwable> throwableType) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenThrow(throwableType));
+ }
+
+ public BDDMyOngoingStubbing<T> willThrow(Class<? extends Throwable> throwableType, Class<? extends Throwable>... throwableTypes) {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenThrow(throwableType, throwableTypes));
+ }
+
+ public BDDMyOngoingStubbing<T> willCallRealMethod() {
+ return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenCallRealMethod());
+ }
+
+ public <M> M getMock() {
+ return (M) mockitoOngoingStubbing.getMock();
+ }
+ }
+
+ /**
+ * see original {@link Mockito#when(Object)}
+ * @since 1.8.0
+ */
+ public static <T> BDDMyOngoingStubbing<T> given(T methodCall) {
+ return new BDDOngoingStubbingImpl<T>(Mockito.when(methodCall));
+ }
+
+ /**
+ * Bdd style verification of mock behavior.
+ *
+ * <pre class="code"><code class="java">
+ * person.ride(bike);
+ * person.ride(bike);
+ *
+ * then(person).should(times(2)).ride(bike);
+ * </code></pre>
+ *
+ * @see #verify(Object)
+ * @see #verify(Object, VerificationMode)
+ * @since 1.10.0
+ */
+ public static <T> Then<T> then(T mock) {
+ return new ThenImpl<T>(mock);
+ }
+
+ /**
+ * Provides fluent way of mock verification.
+ *
+ * @param <T> type of the mock
+ *
+ * @since 1.10.5
+ */
+ public interface Then<T> {
+
+ /**
+ * @see #verify(Object)
+ * @since 1.10.5
+ */
+ T should();
+
+ /**
+ * @see #verify(Object, VerificationMode)
+ * @since 1.10.5
+ */
+ T should(VerificationMode mode);
+
+ /**
+ * @see InOrder#verify(Object)
+ * @since 2.1.0
+ */
+ T should(InOrder inOrder);
+
+ /**
+ * @see InOrder#verify(Object, VerificationMode)
+ * @since 2.1.0
+ */
+ T should(InOrder inOrder, VerificationMode mode);
+
+ /**
+ * @see #verifyZeroInteractions(Object...)
+ * @since 2.1.0
+ */
+ void shouldHaveZeroInteractions();
+
+ /**
+ * @see #verifyNoMoreInteractions(Object...)
+ * @since 2.1.0
+ */
+ void shouldHaveNoMoreInteractions();
+ }
+
+ private static class ThenImpl<T> implements Then<T> {
+
+ private final T mock;
+
+ ThenImpl(T mock) {
+ this.mock = mock;
+ }
+
+ /**
+ * @see #verify(Object)
+ * @since 1.10.5
+ */
+ public T should() {
+ return verify(mock);
+ }
+
+ /**
+ * @see #verify(Object, VerificationMode)
+ * @since 1.10.5
+ */
+ public T should(VerificationMode mode) {
+ return verify(mock, mode);
+ }
+
+ /**
+ * @see InOrder#verify(Object)
+ * @since 2.1.0
+ */
+ public T should(InOrder inOrder) {
+ return inOrder.verify(mock);
+ }
+
+ /**
+ * @see InOrder#verify(Object, VerificationMode)
+ * @since 2.1.0
+ */
+ public T should(InOrder inOrder, VerificationMode mode) {
+ return inOrder.verify(mock, mode);
+ }
+
+ /**
+ * @see #verifyZeroInteractions(Object...)
+ * @since 2.1.0
+ */
+ public void shouldHaveZeroInteractions() {
+ verifyZeroInteractions(mock);
+ }
+
+ /**
+ * @see #verifyNoMoreInteractions(Object...)
+ * @since 2.1.0
+ */
+ public void shouldHaveNoMoreInteractions() {
+ verifyNoMoreInteractions(mock);
+ }
+ }
+
+ /**
+ * See original {@link Stubber}
+ * @since 1.8.0
+ */
+ public interface BDDStubber {
+ /**
+ * See original {@link Stubber#doAnswer(Answer)}
+ * @since 1.8.0
+ */
+ BDDStubber willAnswer(Answer<?> answer);
+
+ /**
+ * See original {@link Stubber#doAnswer(Answer)}
+ * @since 1.8.0
+ */
+ BDDStubber will(Answer<?> answer);
+
+ /**
+ * See original {@link Stubber#doNothing()}.
+ *
+ * This method will be removed in version 3.0.0
+ *
+ * @since 1.8.0
+ * @deprecated as of 2.1.0 please use {@link #willDoNothing()} instead
+ */
+ @Deprecated
+ BDDStubber willNothing();
+
+ /**
+ * See original {@link Stubber#doNothing()}
+ * @since 1.10.20
+ */
+ BDDStubber willDoNothing();
+
+ /**
+ * See original {@link Stubber#doReturn(Object)}
+ * @since 2.1.0
+ */
+ BDDStubber willReturn(Object toBeReturned);
+
+ /**
+ * See original {@link Stubber#doReturn(Object)}
+ * @since 2.1.0
+ */
+ @SuppressWarnings({"unchecked", "varargs"})
+ BDDStubber willReturn(Object toBeReturned, Object... nextToBeReturned);
+
+ /**
+ * See original {@link Stubber#doThrow(Throwable...)}
+ * @since 1.8.0
+ */
+ BDDStubber willThrow(Throwable... toBeThrown);
+
+ /**
+ * See original {@link Stubber#doThrow(Class)}
+ * @since 2.1.0
+ */
+ BDDStubber willThrow(Class<? extends Throwable> toBeThrown);
+
+ /**
+ * See original {@link Stubber#doThrow(Class, Class[])}
+ * @since 2.1.0
+ */
+ @SuppressWarnings ({"unchecked", "varargs"})
+ BDDStubber willThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown);
+
+ /**
+ * See original {@link Stubber#doCallRealMethod()}
+ * @since 1.9.0
+ */
+ BDDStubber willCallRealMethod();
+
+ /**
+ * See original {@link Stubber#when(Object)}
+ * @since 1.8.0
+ */
+ <T> T given(T mock);
+ }
+
+ private static class BDDStubberImpl implements BDDStubber {
+
+ private final Stubber mockitoStubber;
+
+ public BDDStubberImpl(Stubber mockitoStubber) {
+ this.mockitoStubber = mockitoStubber;
+ }
+
+ public <T> T given(T mock) {
+ return mockitoStubber.when(mock);
+ }
+
+ public BDDStubber willAnswer(Answer<?> answer) {
+ return new BDDStubberImpl(mockitoStubber.doAnswer(answer));
+ }
+
+ public BDDStubber will(Answer<?> answer) {
+ return new BDDStubberImpl(mockitoStubber.doAnswer(answer));
+ }
+
+ /**
+ * @deprecated please use {@link #willDoNothing()} instead
+ */
+ @Deprecated
+ public BDDStubber willNothing() {
+ return willDoNothing();
+ }
+
+ public BDDStubber willDoNothing() {
+ return new BDDStubberImpl(mockitoStubber.doNothing());
+ }
+
+ public BDDStubber willReturn(Object toBeReturned) {
+ return new BDDStubberImpl(mockitoStubber.doReturn(toBeReturned));
+ }
+
+ public BDDStubber willReturn(Object toBeReturned, Object... nextToBeReturned) {
+ return new BDDStubberImpl(mockitoStubber.doReturn(toBeReturned).doReturn(nextToBeReturned));
+ }
+
+ public BDDStubber willThrow(Throwable... toBeThrown) {
+ return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown));
+ }
+
+ public BDDStubber willThrow(Class<? extends Throwable> toBeThrown) {
+ return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown));
+ }
+
+ public BDDStubber willThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
+ return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown, nextToBeThrown));
+ }
+
+ public BDDStubber willCallRealMethod() {
+ return new BDDStubberImpl(mockitoStubber.doCallRealMethod());
+ }
+ }
+
+ /**
+ * see original {@link Mockito#doThrow(Throwable[])}
+ * @since 2.1.0
+ */
+ public static BDDStubber willThrow(Throwable... toBeThrown) {
+ return new BDDStubberImpl(Mockito.doThrow(toBeThrown));
+ }
+
+ /**
+ * see original {@link Mockito#doThrow(Class)}
+ * @since 1.9.0
+ */
+ public static BDDStubber willThrow(Class<? extends Throwable> toBeThrown) {
+ return new BDDStubberImpl(Mockito.doThrow(toBeThrown));
+ }
+
+ /**
+ * see original {@link Mockito#doThrow(Class)}
+ * @since 1.9.0
+ */
+ public static BDDStubber willThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... throwableTypes) {
+ return new BDDStubberImpl(Mockito.doThrow(toBeThrown, throwableTypes));
+ }
+
+ /**
+ * see original {@link Mockito#doAnswer(Answer)}
+ * @since 1.8.0
+ */
+ public static BDDStubber willAnswer(Answer<?> answer) {
+ return new BDDStubberImpl(Mockito.doAnswer(answer));
+ }
+
+ /**
+ * see original {@link Mockito#doAnswer(Answer)}
+ * @since 2.1.0
+ */
+ public static BDDStubber will(Answer<?> answer) {
+ return new BDDStubberImpl(Mockito.doAnswer(answer));
+ }
+
+ /**
+ * see original {@link Mockito#doNothing()}
+ * @since 1.8.0
+ */
+ public static BDDStubber willDoNothing() {
+ return new BDDStubberImpl(Mockito.doNothing());
+ }
+
+ /**
+ * see original {@link Mockito#doReturn(Object)}
+ * @since 1.8.0
+ */
+ public static BDDStubber willReturn(Object toBeReturned) {
+ return new BDDStubberImpl(Mockito.doReturn(toBeReturned));
+ }
+
+ /**
+ * see original {@link Mockito#doReturn(Object, Object...)}
+ * @since 2.1.0
+ */
+ @SuppressWarnings({"unchecked", "varargs"})
+ public static BDDStubber willReturn(Object toBeReturned, Object... toBeReturnedNext) {
+ return new BDDStubberImpl(Mockito.doReturn(toBeReturned, toBeReturnedNext));
+ }
+
+ /**
+ * see original {@link Mockito#doCallRealMethod()}
+ * @since 1.8.0
+ */
+ public static BDDStubber willCallRealMethod() {
+ return new BDDStubberImpl(Mockito.doCallRealMethod());
+ }
+}
diff --git a/mockito-updated/src/org/mockito/Captor.java b/mockito-updated/src/org/mockito/Captor.java
new file mode 100644
index 0000000..225bf70
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Captor.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import java.lang.annotation.*;
+
+/**
+ * Allows shorthand {@link org.mockito.ArgumentCaptor} creation on fields.
+ *
+ * <p>Example:
+ * <pre class="code"><code class="java">
+ * public class Test{
+ *
+ * @Captor ArgumentCaptor<AsyncCallback<Foo>> captor;
+ *
+ * @Before
+ * public void init(){
+ * MockitoAnnotations.initMocks(this);
+ * }
+ *
+ * @Test public void shouldDoSomethingUseful() {
+ * //...
+ * verify(mock).doStuff(captor.capture());
+ * assertEquals("foo", captor.getValue());
+ * }
+ * }
+ * </code></pre>
+ *
+ * <p>
+ * One of the advantages of using @Captor annotation is that you can avoid warnings related capturing complex generic types.
+ *
+ * @see ArgumentCaptor
+ * @since 1.8.3
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+@Documented
+public @interface Captor {}
diff --git a/mockito-updated/src/org/mockito/InOrder.java b/mockito-updated/src/org/mockito/InOrder.java
new file mode 100644
index 0000000..8d6d3c7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/InOrder.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito;
+
+import org.mockito.verification.VerificationMode;
+
+/**
+ * Allows verification in order. E.g:
+ *
+ * <pre class="code"><code class="java">
+ * InOrder inOrder = inOrder(firstMock, secondMock);
+ *
+ * inOrder.verify(firstMock).add("was called first");
+ * inOrder.verify(secondMock).add("was called second");
+ * </code></pre>
+ *
+ * As of Mockito 1.8.4 you can verifyNoMoreInteractions() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
+ * <p>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ */
+public interface InOrder {
+ /**
+ * Verifies interaction <b>happened once</b> in order.
+ * <p>
+ * Alias to <code>inOrder.verify(mock, times(1))</code>
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * InOrder inOrder = inOrder(firstMock, secondMock);
+ *
+ * inOrder.verify(firstMock).someMethod("was called first");
+ * inOrder.verify(secondMock).someMethod("was called second");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param mock to be verified
+ *
+ * @return mock object itself
+ */
+ <T> T verify(T mock);
+
+ /**
+ * Verifies interaction in order. E.g:
+ *
+ * <pre class="code"><code class="java">
+ * InOrder inOrder = inOrder(firstMock, secondMock);
+ *
+ * inOrder.verify(firstMock, times(2)).someMethod("was called first two times");
+ * inOrder.verify(secondMock, atLeastOnce()).someMethod("was called second at least once");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param mock to be verified
+ * @param mode for example times(x) or atLeastOnce()
+ *
+ * @return mock object itself
+ */
+ <T> T verify(T mock, VerificationMode mode);
+
+
+ /**
+ * Verifies that no more interactions happened <b>in order</b>.
+ * Different from {@link Mockito#verifyNoMoreInteractions(Object...)} because the order of verification matters.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * mock.foo(); //1st
+ * mock.bar(); //2nd
+ * mock.baz(); //3rd
+ *
+ * InOrder inOrder = inOrder(mock);
+ *
+ * inOrder.verify(mock).bar(); //2n
+ * inOrder.verify(mock).baz(); //3rd (last method)
+ *
+ * //passes because there are no more interactions after last method:
+ * inOrder.verifyNoMoreInteractions();
+ *
+ * //however this fails because 1st method was not verified:
+ * Mockito.verifyNoMoreInteractions(mock);
+ * </code></pre>
+ */
+ void verifyNoMoreInteractions();
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/Incubating.java b/mockito-updated/src/org/mockito/Incubating.java
new file mode 100644
index 0000000..ea53bd0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Incubating.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * The annotation conveys following information:
+ * <ul>
+ * <li>The API is fairly new and we would appreciate your feedback. For example, what are you missing from the API
+ * to solve your use case.</li>
+ * <li>The API might change.
+ * The chance for that is small because we care great deal for the initial design.
+ * The incubating API might change based on the feedback from the community in order to make the API most useful for the users.
+ * </li>
+ * <li>
+ * For types or methods that are not yet released it means the API is <strong>work in progress</strong>
+ * and can change before release.
+ * </li>
+ * </ul>
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface Incubating {
+}
diff --git a/mockito-updated/src/org/mockito/InjectMocks.java b/mockito-updated/src/org/mockito/InjectMocks.java
new file mode 100644
index 0000000..866df22
--- /dev/null
+++ b/mockito-updated/src/org/mockito/InjectMocks.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Mark a field on which injection should be performed.
+ *
+ * <ul>
+ * <li>Allows shorthand mock and spy injection.</li>
+ * <li>Minimizes repetitive mock and spy injection.</li>
+ * </ul>
+ * <p>
+ * Mockito will try to inject mocks only either by constructor injection,
+ * setter injection, or property injection in order and as described below.
+ * If any of the following strategy fail, then Mockito <strong>won't report failure</strong>;
+ * i.e. you will have to provide dependencies yourself.
+ * <ol>
+ * <li><strong>Constructor injection</strong>; the biggest constructor is chosen,
+ * then arguments are resolved with mocks declared in the test only. If the object is successfully created
+ * with the constructor, then <strong>Mockito won't try the other strategies</strong>. Mockito has decided to no
+ * corrupt an object if it has a parametered constructor.
+ * <p><u>Note:</u> If arguments can not be found, then null is passed.
+ * If non-mockable types are wanted, then constructor injection won't happen.
+ * In these cases, you will have to satisfy dependencies yourself.</p></li>
+ *
+ * <li><strong>Property setter injection</strong>; mocks will first be resolved by type (if a single type match
+ * injection will happen regardless of the name),
+ * then, if there is several property of the same type, by the match of the property name and the mock name.
+ * <p><u>Note 1:</u> If you have properties with the same type (or same erasure), it's better to name all @Mock
+ * annotated fields with the matching properties, otherwise Mockito might get confused and injection won't happen.</p>
+ * <p><u>Note 2:</u> If @InjectMocks instance wasn't initialized before and have a no-arg constructor,
+ * then it will be initialized with this constructor.</p></li>
+ *
+ * <li><strong>Field injection</strong>; mocks will first be resolved by type (if a single type match
+ * injection will happen regardless of the name),
+ * then, if there is several property of the same type, by the match of the field name and the mock name.
+ * <p><u>Note 1:</u> If you have fields with the same type (or same erasure), it's better to name all @Mock
+ * annotated fields with the matching fields, otherwise Mockito might get confused and injection won't happen.</p>
+ * <p><u>Note 2:</u> If @InjectMocks instance wasn't initialized before and have a no-arg constructor,
+ * then it will be initialized with this constructor.</p></li>
+ * </ol>
+ * </p>
+ *
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * public class ArticleManagerTest extends SampleBaseTestCase {
+ *
+ * @Mock private ArticleCalculator calculator;
+ * @Mock(name = "database") private ArticleDatabase dbMock; // note the mock name attribute
+ * @Spy private UserProvider userProvider = new ConsumerUserProvider();
+ *
+ * @InjectMocks private ArticleManager manager;
+ *
+ * @Test public void shouldDoSomething() {
+ * manager.initiateArticle();
+ * verify(database).addListener(any(ArticleListener.class));
+ * }
+ * }
+ *
+ * public class SampleBaseTestCase {
+ *
+ * @Before public void initMocks() {
+ * MockitoAnnotations.initMocks(this);
+ * }
+ * }
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * In the above example the field <code>ArticleManager</code> annotated with <code>@InjectMocks</code> can have
+ * a parameterized constructor only or a no-arg constructor only, or both.
+ * All these constructors can be package protected, protected or private, however
+ * <u>Mockito cannot instantiate inner classes, local classes, abstract classes and of course interfaces.</u>
+ * <u>Beware of private nest static classes too.</u>
+ *
+ * <p>The same stands for setters or fields, they can be declared with private
+ * visibility, Mockito will see them through reflection.
+ * However fields that are static or final will be ignored.</p>
+ *
+ * <p>So on the field that needs injection, for example constructor injection will happen here :</p>
+ * <pre class="code"><code class="java">
+ * public class ArticleManager {
+ * ArticleManager(ArticleCalculator calculator, ArticleDatabase database) {
+ * // parameterized constructor
+ * }
+ * }
+ * </code></pre>
+ *
+ * <p>Property setter injection will happen here :</p>
+ * <pre class="code"><code class="java">
+ * public class ArticleManager {
+ * // no-arg constructor
+ * ArticleManager() { }
+ *
+ * // setter
+ * void setDatabase(ArticleDatabase database) { }
+ *
+ * // setter
+ * void setCalculator(ArticleCalculator calculator) { }
+ * }
+ * </code></pre>
+ *
+ * <p>Field injection will be used here :</p>
+ * <pre class="code"><code class="java">
+ * public class ArticleManager {
+ * private ArticleDatabase database;
+ * private ArticleCalculator calculator;
+ * }
+ * </code></pre>
+ * </p>
+ *
+ * <p>And finally, no injection will happen on the type in this case:</p>
+ * <pre class="code"><code class="java">
+ * public class ArticleManager {
+ * private ArticleDatabase database;
+ * private ArticleCalculator calculator;
+ *
+ * ArticleManager(ArticleObserver observer, boolean flag) {
+ * // observer is not declared in the test above.
+ * // flag is not mockable anyway
+ * }
+ * }
+ * </code></pre>
+ * </p>
+ *
+ *
+ * <p>
+ * Again, note that @InjectMocks will only inject mocks/spies created using the @Spy or @Mock annotation.
+ * </p>
+ *
+ * <p>
+ * <strong><code>MockitoAnnotations.initMocks(this)</code></strong> method has to be called to initialize annotated objects.
+ * In above example, <code>initMocks()</code> is called in @Before (JUnit4) method of test's base class.
+ * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class.
+ * <strong>Instead</strong> you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in
+ * {@link org.mockito.runners.MockitoJUnitRunner}.
+ * </p>
+ *
+ * <p>
+ * Mockito is not an dependency injection framework, don't expect this shorthand utility to inject a complex graph of objects
+ * be it mocks/spies or real objects.
+ * </p>
+ *
+ * @see Mock
+ * @see Spy
+ * @see MockitoAnnotations#initMocks(Object)
+ * @see org.mockito.runners.MockitoJUnitRunner
+ * @since 1.8.3
+ */
+@Documented
+@Target(FIELD)
+@Retention(RUNTIME)
+public @interface InjectMocks {}
diff --git a/mockito-updated/src/org/mockito/Matchers.java b/mockito-updated/src/org/mockito/Matchers.java
new file mode 100644
index 0000000..f6d07bc
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Matchers.java
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+/**
+ * @deprecated Use {@link ArgumentMatchers}. This class is now deprecated in order to avoid a name clash with Hamcrest
+ * <code>org.hamcrest.Matchers</code> class. This class will likely be removed in version 3.0.
+ */
+@Deprecated
+public class Matchers extends ArgumentMatchers {
+}
diff --git a/mockito-updated/src/org/mockito/Mock.java b/mockito-updated/src/org/mockito/Mock.java
new file mode 100644
index 0000000..2988cb2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Mock.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.PARAMETER;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Mark a field as a mock.
+ *
+ * <ul>
+ * <li>Allows shorthand mock creation.</li>
+ * <li>Minimizes repetitive mock creation code.</li>
+ * <li>Makes the test class more readable.</li>
+ * <li>Makes the verification error easier to read because the <b>field name</b> is used to identify the mock.</li>
+ * </ul>
+ *
+ * <pre class="code"><code class="java">
+ * public class ArticleManagerTest extends SampleBaseTestCase {
+ *
+ * @Mock private ArticleCalculator calculator;
+ * @Mock(name = "database") private ArticleDatabase dbMock;
+ * @Mock(answer = RETURNS_MOCKS) private UserProvider userProvider;
+ * @Mock(extraInterfaces = {Queue.class, Observer.class}) private articleMonitor;
+ *
+ * private ArticleManager manager;
+ *
+ * @Before public void setup() {
+ * manager = new ArticleManager(userProvider, database, calculator, articleMonitor);
+ * }
+ * }
+ *
+ * public class SampleBaseTestCase {
+ *
+ * @Before public void initMocks() {
+ * MockitoAnnotations.initMocks(this);
+ * }
+ * }
+ * </code></pre>
+ *
+ * <p>
+ * <strong><code>MockitoAnnotations.initMocks(this)</code></strong> method has to be called to initialize annotated objects.
+ * In above example, <code>initMocks()</code> is called in @Before (JUnit4) method of test's base class.
+ * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class.
+ * <strong>Instead</strong> you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in
+ * {@link org.mockito.runners.MockitoJUnitRunner}.
+ * </p>
+ *
+ * @see Mockito#mock(Class)
+ * @see Spy
+ * @see InjectMocks
+ * @see MockitoAnnotations#initMocks(Object)
+ * @see org.mockito.runners.MockitoJUnitRunner
+ */
+@Target({FIELD, PARAMETER})
+@Retention(RUNTIME)
+@Documented
+public @interface Mock {
+
+ Answers answer() default Answers.RETURNS_DEFAULTS;
+
+ String name() default "";
+
+ Class<?>[] extraInterfaces() default {};
+
+ boolean serializable() default false;
+}
diff --git a/mockito-updated/src/org/mockito/MockSettings.java b/mockito-updated/src/org/mockito/MockSettings.java
new file mode 100644
index 0000000..137764c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/MockSettings.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.SerializableMode;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+
+/**
+ * Allows mock creation with additional mock settings.
+ * <p/>
+ * Don't use it too often.
+ * Consider writing simple tests that use simple mocks.
+ * Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
+ * If you cannot write a test in a simple way - refactor the code under test.
+ * <p/>
+ * Examples of mock settings:
+ * <pre class="code"><code class="java">
+ * //Creates mock with different default answer & name
+ * Foo mock = mock(Foo.class, withSettings()
+ * .defaultAnswer(RETURNS_SMART_NULLS)
+ * .name("cool mockie")
+ * );
+ *
+ * //Creates mock with different default answer, descriptive name and extra interfaces
+ * Foo mock = mock(Foo.class, withSettings()
+ * .defaultAnswer(RETURNS_SMART_NULLS)
+ * .name("cool mockie")
+ * .extraInterfaces(Bar.class));
+ * </code></pre>
+ * {@link MockSettings} has been introduced for two reasons.
+ * 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.
+ */
+public interface MockSettings extends Serializable {
+
+ /**
+ * Specifies extra interfaces the mock should implement. Might be useful for legacy code or some corner cases.
+ * <p>
+ * This mysterious feature should be used very occasionally.
+ * The object under test should know exactly its collaborators & dependencies.
+ * If you happen to use it often than please make sure you are really producing simple, clean & readable code.
+ * <p>
+ * Examples:
+ * <pre class="code"><code class="java">
+ * Foo foo = mock(Foo.class, withSettings().extraInterfaces(Bar.class, Baz.class));
+ *
+ * //now, the mock implements extra interfaces, so following casting is possible:
+ * Bar bar = (Bar) foo;
+ * Baz baz = (Baz) foo;
+ * </code></pre>
+ *
+ * @param interfaces extra interfaces the should implement.
+ * @return settings instance so that you can fluently specify other settings
+ */
+ MockSettings extraInterfaces(Class<?>... interfaces);
+
+ /**
+ * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
+ * <p>
+ * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
+ * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
+ * <p>
+ * <b>If you use @Mock annotation then you've got naming mocks for free!</b> @Mock uses field name as mock name. {@link Mock Read more.}
+ * <p>
+ * Examples:
+ * <pre class="code"><code class="java">
+ * Foo foo = mock(Foo.class, withSettings().name("foo"));
+ *
+ * //Below does exactly the same:
+ * Foo foo = mock(Foo.class, "foo");
+ * </code></pre>
+ * @param name the name of the mock, later used in all verification errors
+ * @return settings instance so that you can fluently specify other settings
+ */
+ MockSettings name(String name);
+
+ /**
+ * Specifies the instance to spy on. Makes sense only for spies/partial mocks.
+ *
+ * Sets the instance that will be spied. Actually copies the internal fields of the passed instance to the mock.
+ * <p>
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming is more or less about tackling complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ * <p>
+ * Enough warnings about partial mocks, see an example how spiedInstance() works:
+ * <pre class="code"><code class="java">
+ * Foo foo = mock(Foo.class, withSettings().spiedInstance(fooInstance));
+ *
+ * //Below does exactly the same:
+ * Foo foo = spy(fooInstance);
+ * </code></pre>
+ *
+ * About stubbing for a partial mock, as it is a spy it will always call the real method, unless you use the
+ * <code>doReturn</code>|<code>Throw</code>|<code>Answer</code>|<code>CallRealMethod</code> stubbing style. Example:
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(spy.get(0)).thenReturn("foo");
+ *
+ * //You have to use doReturn() for stubbing
+ * doReturn("foo").when(spy).get(0);
+ * </code>
+ *
+ * @param instance to spy on
+ * @return settings instance so that you can fluently specify other settings
+ */
+ MockSettings spiedInstance(Object instance);
+
+ /**
+ * Specifies default answers to interactions.
+ * It's quite advanced feature and typically you don't need it to write decent tests.
+ * However it can be helpful when working with legacy systems.
+ * <p>
+ * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
+ *
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
+ * Foo mockTwo = mock(Foo.class, withSettings().defaultAnswer(new YourOwnAnswer()));
+ *
+ * //Below does exactly the same:
+ * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
+ * </code></pre>
+ *
+ * @param defaultAnswer default answer to be used by mock when not stubbed
+ * @return settings instance so that you can fluently specify other settings
+ */
+ @SuppressWarnings("unchecked")
+ MockSettings defaultAnswer(Answer defaultAnswer);
+
+ /**
+ * Configures the mock to be serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
+ * <p>
+ * WARNING: This should be rarely used in unit testing.
+ * <p>
+ * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
+ * was in a web environment and the objects from the external dependency were being serialized to pass between layers.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * List serializableMock = mock(List.class, withSettings().serializable());
+ * </code></pre>
+ *
+ * @return settings instance so that you can fluently specify other settings
+ * @since 1.8.1
+ */
+ MockSettings serializable();
+
+ /**
+ * Configures the mock to be serializable with a specific serializable mode.
+ * With this feature you can use a mock in a place that requires dependencies to be serializable.
+ * <p>
+ * WARNING: This should be rarely used in unit testing.
+ * <p>
+ * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
+ * was in a web environment and the objects from the external dependency were being serialized to pass between layers.
+ *
+ * <pre class="code"><code class="java">
+ * List serializableMock = mock(List.class, withSettings().serializable(SerializableMode.ACROSS_CLASSLOADERS));
+ * </code></pre>
+ *
+ * @param mode serialization mode
+ * @return settings instance so that you can fluently specify other settings
+ * @since 1.10.0
+ */
+ MockSettings serializable(SerializableMode mode);
+
+ /**
+ * Enables real-time logging of method invocations on this mock. Can be used
+ * during test debugging in order to find wrong interactions with this mock.
+ * <p>
+ * Invocations are logged as they happen to the standard output stream.
+ * <p>
+ * Calling this method multiple times makes no difference.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * List mockWithLogger = mock(List.class, withSettings().verboseLogging());
+ * </code></pre>
+ *
+ * @return settings instance so that you can fluently specify other settings
+ */
+ MockSettings verboseLogging();
+
+ /**
+ * Registers a listener for method invocations on this mock. The listener is
+ * notified every time a method on this mock is called.
+ * <p>
+ * Multiple listeners may be added, but the same object is only added once.
+ * The order, in which the listeners are added, is not guaranteed to be the
+ * order in which the listeners are notified.
+ *
+ * Example:
+ * <pre class="code"><code class="java">
+ * List mockWithListener = mock(List.class, withSettings().invocationListeners(new YourInvocationListener()));
+ * </code></pre>
+ *
+ * See the {@link InvocationListener listener interface} for more details.
+ *
+ * @param listeners The invocation listeners to add. May not be null.
+ * @return settings instance so that you can fluently specify other settings
+ */
+ MockSettings invocationListeners(InvocationListener... listeners);
+
+ /**
+ * A stub-only mock does not record method
+ * invocations, thus saving memory but
+ * disallowing verification of invocations.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * List stubOnly = mock(List.class, withSettings().stubOnly());
+ * </code></pre>
+ *
+ * @return settings instance so that you can fluently specify other settings
+ */
+ MockSettings stubOnly();
+
+ /**
+ * Mockito attempts to use constructor when creating instance of the mock.
+ * This is particularly useful for spying on abstract classes. See also {@link Mockito#spy(Class)}.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * //Robust API, via settings builder:
+ * OtherAbstract spy = mock(OtherAbstract.class, withSettings()
+ * .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+ *
+ * //Mocking a non-static inner abstract class:
+ * InnerAbstract spy = mock(InnerAbstract.class, withSettings()
+ * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
+ * </code></pre>
+ *
+ * @return settings instance so that you can fluently specify other settings
+ * @since 1.10.12
+ */
+ @Incubating
+ MockSettings useConstructor();
+
+ /**
+ * Makes it possible to mock non-static inner classes in conjunction with {@link #useConstructor()}.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * InnerClass mock = mock(InnerClass.class, withSettings()
+ * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
+ * </code></pre>
+ *
+ * @return settings instance so that you can fluently specify other settings
+ * @since 1.10.12
+ */
+ @Incubating
+ MockSettings outerInstance(Object outerClassInstance);
+}
diff --git a/mockito-updated/src/org/mockito/MockingDetails.java b/mockito-updated/src/org/mockito/MockingDetails.java
new file mode 100644
index 0000000..6ac617c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/MockingDetails.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import org.mockito.stubbing.Stubbing;
+import org.mockito.invocation.Invocation;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.quality.MockitoHint;
+
+import java.util.Collection;
+
+/**
+ * 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
+ */
+public interface MockingDetails {
+
+ /**
+ * Informs if the object is a mock. isMock() for null input returns false.
+ * @return true if the object is a mock or a spy (spy is a different kind of mock, but it is still a mock).
+ *
+ * @since 1.9.5
+ */
+ boolean isMock();
+
+ /**
+ * Informs if the object is a spy. isSpy() for null input returns false.
+ * @return true if the object is a spy.
+ *
+ * @since 1.9.5
+ */
+ boolean isSpy();
+
+ /**
+ * All method invocations on this mock.
+ * Can be empty - it means there were no interactions with the mock.
+ * <p>
+ * This method is useful for framework integrators and for certain edge cases.
+ * <p>
+ * Manipulating the collection (e.g. by removing, adding elements) is safe and has no effect on the mock.
+ * <p>
+ * Throws meaningful exception when object wrapped by MockingDetails is not a mock.
+ *
+ * @since 1.10.0
+ */
+ Collection<Invocation> getInvocations();
+
+ /**
+ * Returns various mock settings provided when the mock was created, for example:
+ * mocked class, mock name (if any), any extra interfaces (if any), etc.
+ * See also {@link MockCreationSettings}.
+ * <p>
+ * This method is useful for framework integrators and for certain edge cases.
+ * <p>
+ * If <code>null</code> or non-mock was passed to {@link Mockito#mockingDetails(Object)}
+ * then this method will throw with an appropriate exception.
+ * After all, non-mock objects do not have any mock creation settings.
+ * @since 2.1.0
+ */
+ MockCreationSettings<?> getMockCreationSettings();
+
+ /**
+ * Returns stubbings declared on this mock object.
+ * <pre class="code"><code class="java">
+ * Mockito.mockingDetails(mock).getStubbings()
+ * </code></pre>
+ * What is 'stubbing'?
+ * Stubbing is your when(x).then(y) declaration, e.g. configuring the mock to behave in a specific way,
+ * when specific method with specific arguments is invoked on a mock.
+ * Typically stubbing is configuring mock to return X when method Y is invoked.
+ * <p>
+ * Why do you need to access stubbings of a mock?
+ * In a normal workflow of creation clean tests, there is no need for this API.
+ * However, it is useful for advanced users, edge cases or framework integrators.
+ * For example, Mockito internally uses this API to report and detect unused stubbings
+ * that should be removed from test. Unused stubbings are dead code that needs to be removed
+ * (see {@link MockitoHint}).
+ * <p>
+ * Manipulating the collection (e.g. by removing, adding elements) is safe and has no effect on the mock.
+ * <p>
+ * This method throws meaningful exception when object wrapped by MockingDetails is not a mock.
+ *
+ * @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/mockito-updated/src/org/mockito/Mockito.java b/mockito-updated/src/org/mockito/Mockito.java
new file mode 100644
index 0000000..684add4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Mockito.java
@@ -0,0 +1,2671 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import org.mockito.internal.MockitoCore;
+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.MockitoRule;
+import org.mockito.mock.SerializableMode;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.OngoingStubbing;
+import org.mockito.stubbing.Stubber;
+import org.mockito.verification.*;
+
+/**
+ * <p align="left"><img src="logo.png" srcset="logo@2x.png 2x" alt="Mockito logo"/></p>
+ * The Mockito library enables mock creation, verification and stubbing.
+ * <p>
+ * This javadoc content is also available on the <a href="http://mockito.org">http://mockito.org</a> web page.
+ * All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code.
+ * It allows access to documentation straight from the IDE even if you work offline.
+ * It motivates Mockito developers to keep documentation up-to-date with the code that they write,
+ * every day, with every commit.
+ *
+ * <h1>Contents</h1>
+ *
+ * <b>
+ * <a href="#0">0. Migrating to Mockito 2</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/>
+ * <a href="#4">4. Verifying exact number of invocations / at least once / never </a><br/>
+ * <a href="#5">5. Stubbing void methods with exceptions </a><br/>
+ * <a href="#6">6. Verification in order </a><br/>
+ * <a href="#7">7. Making sure interaction(s) never happened on mock </a><br/>
+ * <a href="#8">8. Finding redundant invocations </a><br/>
+ * <a href="#9">9. Shorthand for mocks creation - <code>@Mock</code> annotation </a><br/>
+ * <a href="#10">10. Stubbing consecutive calls (iterator-style stubbing) </a><br/>
+ * <a href="#11">11. Stubbing with callbacks </a><br/>
+ * <a href="#12">12. <code>doReturn()</code>|<code>doThrow()</code>|<code>doAnswer()</code>|<code>doNothing()</code>|<code>doCallRealMethod()</code> family of methods</a><br/>
+ * <a href="#13">13. Spying on real objects </a><br/>
+ * <a href="#14">14. Changing default return values of unstubbed invocations (Since 1.7) </a><br/>
+ * <a href="#15">15. Capturing arguments for further assertions (Since 1.8.0) </a><br/>
+ * <a href="#16">16. Real partial mocks (Since 1.8.0) </a><br/>
+ * <a href="#17">17. Resetting mocks (Since 1.8.0) </a><br/>
+ * <a href="#18">18. Troubleshooting & validating framework usage (Since 1.8.0) </a><br/>
+ * <a href="#19">19. Aliases for behavior driven development (Since 1.8.0) </a><br/>
+ * <a href="#20">20. Serializable mocks (Since 1.8.1) </a><br/>
+ * <a href="#21">21. New annotations: <code>@Captor</code>, <code>@Spy</code>, <code>@InjectMocks</code> (Since 1.8.3) </a><br/>
+ * <a href="#22">22. Verification with timeout (Since 1.8.5) </a><br/>
+ * <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.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/>
+ * <a href="#30">30. Spying or mocking abstract classes (Since 1.10.12)</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/>
+ * <a href="#34">34. Switch <em>on</em> or <em>off</em> plugins (Since 1.10.15)</a><br/>
+ * <a href="#35">35. Custom verification failure message (Since 2.1.0)</a><br/>
+ * <a href="#36">36. Java 8 Lambda Matcher Support (Since 2.1.0)</a><br/>
+ * <a href="#37">37. Java 8 Custom Answer Support (Since 2.1.0)</a><br/>
+ * <a href="#38">38. Meta data and generic type retention (Since 2.1.0)</a><br/>
+ * <a href="#39">39. Mocking final types, enums and final methods (Since 2.1.0)</a><br/>
+ * </b>
+ *
+ * <h3 id="0">0. <a class="meaningful_link" href="#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.
+ * In the lifecycle of a library, breaking changes are necessary
+ * to roll out a set of brand new features that alter the existing behavior or even change the API.
+ * For a comprehensive guide on the new release including incompatible changes,
+ * 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="1">1. <a class="meaningful_link" href="#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>
+ * In reality, please don't mock the List class. Use a real instance instead.
+ *
+ * <pre class="code"><code class="java">
+ * //Let's import Mockito statically so that the code looks clearer
+ * import static org.mockito.Mockito.*;
+ *
+ * //mock creation
+ * List mockedList = mock(List.class);
+ *
+ * //using mock object
+ * mockedList.add("one");
+ * mockedList.clear();
+ *
+ * //verification
+ * verify(mockedList).add("one");
+ * verify(mockedList).clear();
+ * </code></pre>
+ *
+ * <p>
+ * Once created, a mock will remember all interactions. Then you can selectively
+ * verify whatever interactions you are interested in.
+ *
+ *
+ *
+ *
+ * <h3 id="2">2. <a class="meaningful_link" href="#stubbing">How about some stubbing?</a></h3>
+ *
+ * <pre class="code"><code class="java">
+ * //You can mock concrete classes, not just interfaces
+ * LinkedList mockedList = mock(LinkedList.class);
+ *
+ * //stubbing
+ * when(mockedList.get(0)).thenReturn("first");
+ * when(mockedList.get(1)).thenThrow(new RuntimeException());
+ *
+ * //following prints "first"
+ * System.out.println(mockedList.get(0));
+ *
+ * //following throws runtime exception
+ * System.out.println(mockedList.get(1));
+ *
+ * //following prints "null" because get(999) was not stubbed
+ * System.out.println(mockedList.get(999));
+ *
+ * //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>.
+ * verify(mockedList).get(0);
+ * </code></pre>
+ *
+ * <ul>
+ * <li> By default, for all methods that return a value, a mock will return either null, a
+ * a primitive/primitive wrapper value, or an empty collection, as appropriate.
+ * For example 0 for an int/Integer and false for a boolean/Boolean. </li>
+ *
+ * <li> Stubbing can be overridden: for example common stubbing can go to
+ * fixture setup but the test methods can override it.
+ * Please note that overridding stubbing is a potential code smell that points out too much stubbing</li>
+ *
+ * <li> Once stubbed, the method will always return a stubbed value, regardless
+ * of how many times it is called. </li>
+ *
+ * <li> Last stubbing is more important - when you stubbed the same method with
+ * the same arguments many times.
+ * Other words: <b>the order of stubbing matters</b> but it is only meaningful rarely,
+ * e.g. when stubbing exactly the same method calls or sometimes when argument matchers are used, etc.</li>
+ *
+ * </ul>
+ *
+ *
+ *
+ * <h3 id="3">3. <a class="meaningful_link" href="#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:
+ *
+ * <pre class="code"><code class="java">
+ * //stubbing using built-in anyInt() argument matcher
+ * when(mockedList.get(anyInt())).thenReturn("element");
+ *
+ * //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
+ * when(mockedList.contains(argThat(isValid()))).thenReturn("element");
+ *
+ * //following prints "element"
+ * System.out.println(mockedList.get(999));
+ *
+ * //<b>you can also verify using an argument matcher</b>
+ * verify(mockedList).get(anyInt());
+ *
+ * //<b>argument matchers can also be written as Java 8 Lambdas</b>
+ * verify(mockedList).add(someString -> someString.length() > 5);
+ *
+ * </code></pre>
+ *
+ * <p>
+ * Argument matchers allow flexible verification or stubbing.
+ * {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest or here} to see more built-in matchers
+ * and examples of <b>custom argument matchers / hamcrest matchers</b>.
+ * <p>
+ * For information solely on <b>custom argument matchers</b> check out javadoc for {@link ArgumentMatcher} class.
+ * <p>
+ * Be reasonable with using complicated argument matching.
+ * The natural matching style using <code>equals()</code> with occasional <code>anyX()</code> matchers tend to give clean & simple tests.
+ * Sometimes it's just better to refactor the code to allow <code>equals()</code> matching or even implement <code>equals()</code> method to help out with testing.
+ * <p>
+ * Also, read <a href="#15">section 15</a> or javadoc for {@link ArgumentCaptor} class.
+ * {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions.
+ * <p>
+ * <b>Warning on argument matchers:</b>
+ * <p>
+ * If you are using argument matchers, <b>all arguments</b> have to be provided
+ * by matchers.
+ * <p>
+ The following example shows verification but the same applies to stubbing:
+ *
+ * <pre class="code"><code class="java">
+ * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>);
+ * //above is correct - eq() is also an argument matcher
+ *
+ * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>);
+ * //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
+ * </code></pre>
+ *
+ * <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 to static type safety imposed by the java compiler.
+ * The consequence is that you cannot use <code>anyObject()</code>, <code>eq()</code> methods outside of verified/stubbed method.
+ *
+ *
+ *
+ *
+ * <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>
+ *
+ * <pre class="code"><code class="java">
+ * //using mock
+ * mockedList.add("once");
+ *
+ * mockedList.add("twice");
+ * mockedList.add("twice");
+ *
+ * mockedList.add("three times");
+ * mockedList.add("three times");
+ * mockedList.add("three times");
+ *
+ * //following two verifications work exactly the same - times(1) is used by default
+ * verify(mockedList).add("once");
+ * verify(mockedList, times(1)).add("once");
+ *
+ * //exact number of invocations verification
+ * verify(mockedList, times(2)).add("twice");
+ * verify(mockedList, times(3)).add("three times");
+ *
+ * //verification using never(). never() is an alias to times(0)
+ * verify(mockedList, never()).add("never happened");
+ *
+ * //verification using atLeast()/atMost()
+ * verify(mockedList, atLeastOnce()).add("three times");
+ * verify(mockedList, atLeast(2)).add("five times");
+ * verify(mockedList, atMost(5)).add("three times");
+ *
+ * </code></pre>
+ *
+ * <p>
+ * <b>times(1) is the default.</b> Therefore using times(1) explicitly can be
+ * omitted.
+ *
+ *
+ *
+ *
+ * <h3 id="5">5. <a class="meaningful_link" href="#stubbing_with_exceptions">Stubbing void methods with exceptions</a></h3>
+ *
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException()).when(mockedList).clear();
+ *
+ * //following throws RuntimeException:
+ * mockedList.clear();
+ * </code></pre>
+ *
+ * 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>
+ *
+ * <pre class="code"><code class="java">
+ * // A. Single mock whose methods must be invoked in a particular order
+ * List singleMock = mock(List.class);
+ *
+ * //using a single mock
+ * singleMock.add("was added first");
+ * singleMock.add("was added second");
+ *
+ * //create an inOrder verifier for a single mock
+ * InOrder inOrder = inOrder(singleMock);
+ *
+ * //following will make sure that add is first called with "was added first, then with "was added second"
+ * inOrder.verify(singleMock).add("was added first");
+ * inOrder.verify(singleMock).add("was added second");
+ *
+ * // B. Multiple mocks that must be used in a particular order
+ * List firstMock = mock(List.class);
+ * List secondMock = mock(List.class);
+ *
+ * //using mocks
+ * firstMock.add("was called first");
+ * secondMock.add("was called second");
+ *
+ * //create inOrder object passing any mocks that need to be verified in order
+ * InOrder inOrder = inOrder(firstMock, secondMock);
+ *
+ * //following will make sure that firstMock was called before secondMock
+ * inOrder.verify(firstMock).add("was called first");
+ * inOrder.verify(secondMock).add("was called second");
+ *
+ * // Oh, and A + B can be mixed together at will
+ * </code></pre>
+ *
+ * Verification in order is flexible - <b>you don't have to verify all
+ * interactions</b> one-by-one but only those that you are interested in
+ * testing in order.
+ * <p>
+ * Also, you can create an InOrder object passing only the mocks that are relevant for
+ * in-order verification.
+ *
+ *
+ *
+ *
+ * <h3 id="7">7. <a class="meaningful_link" href="#never_verification">Making sure interaction(s) never happened on mock</a></h3>
+ *
+ * <pre class="code"><code class="java">
+ * //using mocks - only mockOne is interacted
+ * mockOne.add("one");
+ *
+ * //ordinary verification
+ * verify(mockOne).add("one");
+ *
+ * //verify that method was never called on a mock
+ * verify(mockOne, never()).add("two");
+ *
+ * //verify that other mocks were not interacted
+ * verifyZeroInteractions(mockTwo, mockThree);
+ *
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="8">8. <a class="meaningful_link" href="#finding_redundant_invocations">Finding redundant invocations</a></h3>
+ *
+ * <pre class="code"><code class="java">
+ * //using mocks
+ * mockedList.add("one");
+ * mockedList.add("two");
+ *
+ * verify(mockedList).add("one");
+ *
+ * //following verification will fail
+ * verifyNoMoreInteractions(mockedList);
+ * </code></pre>
+ *
+ * A word of <b>warning</b>:
+ * 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>.
+ *
+ * <p>
+ * See also {@link Mockito#never()} - it is more explicit and
+ * communicates the intent well.
+ * <p>
+ *
+ *
+ *
+ *
+ * <h3 id="9">9. <a class="meaningful_link" href="#mock_annotation">Shorthand for mocks creation - <code>@Mock</code> annotation</a></h3>
+ *
+ * <ul>
+ * <li>Minimizes repetitive mock creation code.</li>
+ * <li>Makes the test class more readable.</li>
+ * <li>Makes the verification error easier to read because the <b>field name</b>
+ * is used to identify the mock.</li>
+ * </ul>
+ *
+ * <pre class="code"><code class="java">
+ * public class ArticleManagerTest {
+ *
+ * @Mock private ArticleCalculator calculator;
+ * @Mock private ArticleDatabase database;
+ * @Mock private UserProvider userProvider;
+ *
+ * private ArticleManager manager;
+ * </code></pre>
+ *
+ * <b>Important!</b> This needs to be somewhere in the base class or a test
+ * runner:
+ *
+ * <pre class="code"><code class="java">
+ * MockitoAnnotations.initMocks(testClass);
+ * </code></pre>
+ *
+ * You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
+ * <p>
+ * Read more here: {@link MockitoAnnotations}
+ *
+ *
+ *
+ *
+ * <h3 id="10">10. <a class="meaningful_link" href="#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.
+ * Original version of Mockito did not have this feature to promote simple mocking.
+ * For example, instead of iterators one could use {@link Iterable} or simply
+ * collections. Those offer natural ways of stubbing (e.g. using real
+ * collections). In rare scenarios stubbing consecutive calls could be useful,
+ * though:
+ * <p>
+ *
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod("some arg"))
+ * .thenThrow(new RuntimeException())
+ * .thenReturn("foo");
+ *
+ * //First call: throws runtime exception:
+ * mock.someMethod("some arg");
+ *
+ * //Second call: prints "foo"
+ * System.out.println(mock.someMethod("some arg"));
+ *
+ * //Any consecutive call: prints "foo" as well (last stubbing wins).
+ * System.out.println(mock.someMethod("some arg"));
+ * </code></pre>
+ *
+ * Alternative, shorter version of consecutive stubbing:
+ *
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod("some arg"))
+ * .thenReturn("one", "two", "three");
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="11">11. <a class="meaningful_link" href="#answer_stubs">Stubbing with callbacks</a></h3>
+ *
+ * Allows stubbing with generic {@link Answer} interface.
+ * <p>
+ * Yet another controversial feature which was not included in Mockito
+ * originally. We recommend simply stubbing with <code>thenReturn()</code> or
+ * <code>thenThrow()</code>, which should be enough to test/test-drive
+ * any clean & simple code. However, if you do have a need to stub with the generic Answer interface, here is an example:
+ *
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod(anyString())).thenAnswer(new Answer() {
+ * Object answer(InvocationOnMock invocation) {
+ * Object[] args = invocation.getArguments();
+ * Object mock = invocation.getMock();
+ * return "called with arguments: " + args;
+ * }
+ * });
+ *
+ * //the following prints "called with arguments: foo"
+ * System.out.println(mock.someMethod("foo"));
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="12">12. <a class="meaningful_link" href="#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
+ * like void methods inside brackets...
+ * <p>
+ * Use <code>doThrow()</code> when you want to stub a void method with an exception:
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException()).when(mockedList).clear();
+ *
+ * //following throws RuntimeException:
+ * mockedList.clear();
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * You can use <code>doThrow()</code>, <code>doAnswer()</code>, <code>doNothing()</code>, <code>doReturn()</code>
+ * and <code>doCallRealMethod()</code> in place of the corresponding call with <code>when()</code>, for any method.
+ * It is necessary when you
+ * <ul>
+ * <li>stub void methods</li>
+ * <li>stub methods on spy objects (see below)</li>
+ * <li>stub the same method more than once, to change the behaviour of a mock in the middle of a test.</li>
+ * </ul>
+ * but you may prefer to use these methods in place of the alternative with <code>when()</code>, for all of your stubbing calls.
+ * <p>
+ * Read more about these methods:
+ * <p>
+ * {@link Mockito#doReturn(Object)}
+ * <p>
+ * {@link Mockito#doThrow(Throwable...)}
+ * <p>
+ * {@link Mockito#doThrow(Class)}
+ * <p>
+ * {@link Mockito#doAnswer(Answer)}
+ * <p>
+ * {@link Mockito#doNothing()}
+ * <p>
+ * {@link Mockito#doCallRealMethod()}
+ *
+ *
+ *
+ *
+ * <h3 id="13">13. <a class="meaningful_link" href="#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).
+ * <p>
+ * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
+ *
+ * <p>
+ * Spying on real objects can be associated with "partial mocking" concept.
+ * <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>)
+ * <p>
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //optionally, you can stub out some methods:
+ * when(spy.size()).thenReturn(100);
+ *
+ * //using the spy calls <b>*real*</b> methods
+ * spy.add("one");
+ * spy.add("two");
+ *
+ * //prints "one" - the first element of a list
+ * System.out.println(spy.get(0));
+ *
+ * //size() method was stubbed - 100 is printed
+ * System.out.println(spy.size());
+ *
+ * //optionally, you can verify
+ * verify(spy).add("one");
+ * verify(spy).add("two");
+ * </code></pre>
+ *
+ * <h4>Important gotcha on spying real objects!</h4>
+ * <ol>
+ * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
+ * Therefore when using spies please consider <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code> family of
+ * methods for stubbing. Example:
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(spy.get(0)).thenReturn("foo");
+ *
+ * //You have to use doReturn() for stubbing
+ * doReturn("foo").when(spy).get(0);
+ * </code></pre>
+ * </li>
+ *
+ * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
+ * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
+ * and their effect on real instance state.
+ * The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
+ * you won't see any effects on the real instance.
+ * </li>
+ *
+ * <li>Watch out for final methods.
+ * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
+ * Also you won't be able to verify those method as well.
+ * </li>
+ * </ol>
+ *
+ *
+ *
+ *
+ * <h3 id="14">14. Changing <a class="meaningful_link" href="#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.
+ * However, it can be helpful for working with <b>legacy systems</b>.
+ * <p>
+ * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
+ *
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
+ * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
+ * </code></pre>
+ *
+ * <p>
+ * Read more about this interesting implementation of <i>Answer</i>: {@link Mockito#RETURNS_SMART_NULLS}
+ *
+ *
+ *
+ *
+ * <h3 id="15">15. <a class="meaningful_link" href="#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.
+ * In some situations though, it is helpful to assert on certain arguments after the actual verification.
+ * For example:
+ * <pre class="code"><code class="java">
+ * ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
+ * verify(mock).doSomething(argument.capture());
+ * assertEquals("John", argument.getValue().getName());
+ * </code></pre>
+ *
+ * <b>Warning:</b> it is recommended to use ArgumentCaptor with verification <b>but not</b> with stubbing.
+ * Using ArgumentCaptor with stubbing may decrease test readability because captor is created outside of assert (aka verify or 'then') block.
+ * Also it may reduce defect localization because if stubbed method was not called then no argument is captured.
+ * <p>
+ * In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
+ * Both techniques can be used for making sure certain arguments where passed to mocks.
+ * However, ArgumentCaptor may be a better fit if:
+ * <ul>
+ * <li>custom argument matcher is not likely to be reused</li>
+ * <li>you just need it to assert on argument values to complete verification</li>
+ * </ul>
+ * Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
+ *
+ *
+ *
+ *
+ * <h3 id="16">16. <a class="meaningful_link" href="#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>
+ * <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.
+ * <p>
+ * <pre class="code"><code class="java">
+ * //you can create partial mock with spy() method:
+ * List list = spy(new LinkedList());
+ *
+ * //you can enable partial mock capabilities selectively on mocks:
+ * Foo mock = mock(Foo.class);
+ * //Be sure the real implementation is 'safe'.
+ * //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
+ * when(mock.someMethod()).thenCallRealMethod();
+ * </code></pre>
+ *
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ *
+ *
+ *
+ *
+ * <h3 id="17">17. <a class="meaningful_link" href="#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.
+ * <p>
+ * Instead of <code>reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
+ * <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
+ * Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
+ * There are several threads about it on mockito mailing list.
+ * <p>
+ * The only reason we added <code>reset()</code> method is to
+ * make it possible to work with container-injected mocks.
+ * For more information see FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
+ * <p>
+ * <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
+ * <pre class="code"><code class="java">
+ * List mock = mock(List.class);
+ * when(mock.size()).thenReturn(10);
+ * mock.add(1);
+ *
+ * reset(mock);
+ * //at this point the mock forgot any interactions & stubbing
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="18">18. <a class="meaningful_link" href="#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>
+ * <p>
+ * In case of questions you may also post to mockito mailing list:
+ * <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
+ * <p>
+ * Next, you should know that Mockito validates if you use it correctly <b>all the time</b>.
+ * However, there's a gotcha so please read the javadoc for {@link Mockito#validateMockitoUsage()}
+ *
+ *
+ *
+ *
+ * <h3 id="19">19. <a class="meaningful_link" href="#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!
+ * <p>
+ * Start learning about BDD here: <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">http://en.wikipedia.org/wiki/Behavior_Driven_Development</a>
+ * <p>
+ * The problem is that current stubbing api with canonical role of <b>when</b> word does not integrate nicely with <b>//given //when //then</b> comments.
+ * It's because stubbing belongs to <b>given</b> component of the test and not to the <b>when</b> component of the test.
+ * Hence {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
+ * Now it really nicely integrates with the <b>given</b> component of a BDD style test!
+ * <p>
+ * Here is how the test might look like:
+ * <pre class="code"><code class="java">
+ * import static org.mockito.BDDMockito.*;
+ *
+ * Seller seller = mock(Seller.class);
+ * Shop shop = new Shop(seller);
+ *
+ * public void shouldBuyBread() throws Exception {
+ * //given
+ * given(seller.askForBread()).willReturn(new Bread());
+ *
+ * //when
+ * Goods goods = shop.buyBread();
+ *
+ * //then
+ * assertThat(goods, containBread());
+ * }
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="20">20. <a class="meaningful_link" href="#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>
+ * WARNING: This should be rarely used in unit testing.
+ * <p>
+ * The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
+ * was in a web environment and the objects from the external dependency were being serialized to pass between layers.
+ * <p>
+ * To create serializable mock use {@link MockSettings#serializable()}:
+ * <pre class="code"><code class="java">
+ * List serializableMock = mock(List.class, withSettings().serializable());
+ * </code></pre>
+ * <p>
+ * The mock can be serialized assuming all the normal <a href='http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html'>
+ * serialization requirements</a> are met by the class.
+ * <p>
+ * Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version
+ * which accepts MockSettings. No worries, you will hardly ever use it.
+ *
+ * <pre class="code"><code class="java">
+ * List<Object> list = new ArrayList<Object>();
+ * List<Object> spy = mock(ArrayList.class, withSettings()
+ * .spiedInstance(list)
+ * .defaultAnswer(CALLS_REAL_METHODS)
+ * .serializable());
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <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>
+ *
+ * <p>
+ * Release 1.8.3 brings new annotations that may be helpful on occasion:
+ *
+ * <ul>
+ * <li>@{@link Captor} simplifies creation of {@link ArgumentCaptor}
+ * - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
+ * <li>@{@link Spy} - you can use it instead {@link Mockito#spy(Object)}.
+ * <li>@{@link InjectMocks} - injects mock or spy fields into tested object automatically.
+ * </ul>
+ *
+ * <p>
+ * Note that @{@link InjectMocks} can also be used in combination with the @{@link Spy} annotation, it means
+ * that Mockito will inject mocks into the partial mock under test. This complexity is another good reason why you
+ * should only use partial mocks as a last resort. See point 16 about partial mocks.
+ *
+ * <p>
+ * All new annotations are <b>*only*</b> processed on {@link MockitoAnnotations#initMocks(Object)}.
+ * Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule:
+ * {@link MockitoRule}.
+ * <p>
+ *
+ *
+ *
+ *
+ * <h3 id="22">22. <a class="meaningful_link" href="#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
+ * conditions.
+ * <p>
+ * This feature should be used rarely - figure out a better way of testing your multi-threaded system.
+ * <p>
+ * Not yet implemented to work with InOrder verification.
+ * <p>
+ * Examples:
+ * <p>
+ * <pre class="code"><code class="java">
+ * //passes when someMethod() is called within given time span
+ * verify(mock, timeout(100)).someMethod();
+ * //above is an alias to:
+ * verify(mock, timeout(100).times(1)).someMethod();
+ *
+ * //passes when someMethod() is called <b>*exactly*</b> 2 times within given time span
+ * verify(mock, timeout(100).times(2)).someMethod();
+ *
+ * //passes when someMethod() is called <b>*at least*</b> 2 times within given time span
+ * verify(mock, timeout(100).atLeast(2)).someMethod();
+ *
+ * //verifies someMethod() within given time span using given verification mode
+ * //useful only if you have your own custom verification modes.
+ * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <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>
+ *
+ * <p>
+ * Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields
+ * using <b>constructor</b> injection, <b>setter</b> injection, or <b>field</b> injection.
+ * <p>
+ * To take advantage of this feature you need to use {@link MockitoAnnotations#initMocks(Object)}, {@link MockitoJUnitRunner}
+ * or {@link MockitoRule}.
+ * <p>
+ * Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks}
+ * <pre class="code"><code class="java">
+ * //instead:
+ * @Spy BeerDrinker drinker = new BeerDrinker();
+ * //you can write:
+ * @Spy BeerDrinker drinker;
+ *
+ * //same applies to @InjectMocks annotation:
+ * @InjectMocks LocalPub;
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="24">24. <a class="meaningful_link" href="#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.
+ * This can be helpful to keep test code clean.
+ * For example, some boring stub can be created & stubbed at field initialization in a test:
+ * <pre class="code"><code class="java">
+ * public class CarTest {
+ * Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
+ *
+ * @Test public void should... {}
+ * </code></pre>
+ *
+ *
+ *
+ *
+ * <h3 id="25">25. <a class="meaningful_link" href="#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>.
+ * 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 verifyNoMoreInteractions(ignoreStubs(...));
+ * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
+ * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
+ * <p>Some examples:
+ * <pre class="code"><code class="java">
+ * verify(mock).foo();
+ * verify(mockTwo).bar();
+ *
+ * //ignores all stubbed methods:
+ * verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));
+ *
+ * //creates InOrder that will ignore stubbed
+ * InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));
+ * inOrder.verify(mock).foo();
+ * inOrder.verify(mockTwo).bar();
+ * inOrder.verifyNoMoreInteractions();
+ * </code></pre>
+ * <p>
+ * Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)}
+ *
+ *
+ *
+ *
+ * <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.
+ * This API is useful for advanced users and mocking framework integrators.
+ *
+ * <pre class="code"><code class="java">
+ * //To identify whether a particular object is a mock or a spy:
+ * Mockito.mockingDetails(someObject).isMock();
+ * Mockito.mockingDetails(someObject).isSpy();
+ *
+ * //Getting details like type to mock or default answer:
+ * MockingDetails details = mockingDetails(mock);
+ * details.getMockCreationSettings().getTypeToMock();
+ * details.getMockCreationSettings().getDefaultAnswer();
+ *
+ * //Getting interactions and stubbings of the mock:
+ * 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}.
+ *
+ * <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>
+ *
+ * <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.
+ * If the type is different, a matching method needs to be found on delegate type otherwise an exception is thrown.
+ *
+ * Possible use cases for this feature:
+ * <ul>
+ * <li>Final classes but with an interface</li>
+ * <li>Already custom proxied object</li>
+ * <li>Special objects with a finalize method, i.e. to avoid executing it 2 times</li>
+ * </ul>
+ *
+ * <p>The difference with the regular spy:
+ * <ul>
+ * <li>
+ * The regular spy ({@link #spy(Object)}) contains <strong>all</strong> state from the spied instance
+ * and the methods are invoked on the spy. The spied instance is only used at mock creation to copy the state from.
+ * If you call a method on a regular spy and it internally calls other methods on this spy, those calls are remembered
+ * for verifications, and they can be effectively stubbed.
+ * </li>
+ * <li>
+ * The mock that delegates simply delegates all methods to the delegate.
+ * The delegate is used all the time as methods are delegated onto it.
+ * If you call a method on a mock that delegates and it internally calls other methods on this mock,
+ * those calls are <strong>not</strong> remembered for verifications, stubbing does not have effect on them, too.
+ * Mock that delegates is less powerful than the regular spy but it is useful when the regular spy cannot be created.
+ * </li>
+ * </ul>
+ *
+ * <p>
+ * See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}.
+ *
+ *
+ *
+ *
+ * <h3 id="28">28. <a class="meaningful_link" href="#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.
+ * <p>The extension point is for advanced users that want to extend Mockito. For example, it is now possible
+ * to use Mockito for Android testing with a help of <a href="https://github.com/crittercism/dexmaker">dexmaker</a>.
+ * <p>For more details, motivations and examples please refer to
+ * the docs for {@link org.mockito.plugins.MockMaker}.
+ *
+ *
+ *
+ *
+ * <h3 id="29">29. <a class="meaningful_link" href="#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.
+ *
+ * <pre class="code"><code class="java">
+ * given(dog.bark()).willReturn(2);
+ *
+ * // when
+ * ...
+ *
+ * then(person).should(times(2)).ride(bike);
+ * </code></pre>
+ *
+ * For more information and an example see {@link BDDMockito#then(Object)}}
+ *
+ *
+ *
+ *
+ * <h3 id="30">30. <a class="meaningful_link" href="#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>
+ * Previously, spying was only possible on instances of objects.
+ * New API makes it possible to use constructor when creating an instance of the mock.
+ * This is particularly useful for mocking abstract classes because the user is no longer required to provide an instance of the abstract class.
+ * At the moment, only parameter-less constructor is supported, let us know if it is not enough.
+ *
+ * <pre class="code"><code class="java">
+ * //convenience API, new overloaded spy() method:
+ * SomeAbstract spy = spy(SomeAbstract.class);
+ *
+ * //Robust API, via settings builder:
+ * OtherAbstract spy = mock(OtherAbstract.class, withSettings()
+ * .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+ *
+ * //Mocking a non-static inner abstract class:
+ * InnerAbstract spy = mock(InnerAbstract.class, withSettings()
+ * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
+ * </code></pre>
+ *
+ * For more information please see {@link MockSettings#useConstructor()}.
+ *
+ *
+ *
+ *
+ * <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>
+ *
+ * Mockito introduces serialization across classloader.
+ *
+ * Like with any other form of serialization, all types in the mock hierarchy have to serializable, inclusing answers.
+ * As this serialization mode require considerably more work, this is an opt-in setting.
+ *
+ * <pre class="code"><code class="java">
+ * // use regular serialization
+ * mock(Book.class, withSettings().serializable());
+ *
+ * // use serialization across classloaders
+ * mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));
+ * </code></pre>
+ *
+ * For more details see {@link MockSettings#serializable(SerializableMode)}.
+ *
+ *
+ *
+ *
+ * <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>
+ *
+ * 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.
+ *
+ * <pre class="code"><code class="java">
+ * class Lines extends List<Line> {
+ * // ...
+ * }
+ *
+ * lines = mock(Lines.class, RETURNS_DEEP_STUBS);
+ *
+ * // Now Mockito understand this is not an Object but a Line
+ * Line line = lines.iterator().next();
+ * </code></pre>
+ *
+ * Please note that in most scenarios a mock returning a mock is wrong.
+ *
+ *
+ *
+ *
+ * <h3 id="33">33. <a class="meaningful_link" href="#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.
+ *
+ * <ul>
+ * <li>Annotating the JUnit test class with a <code>@{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)</code></li>
+ * <li>Invoking <code>{@link MockitoAnnotations#initMocks(Object)}</code> in the <code>@{@link org.junit.Before}</code> method</li>
+ * </ul>
+ *
+ * Now you can choose to use a rule :
+ *
+ * <pre class="code"><code class="java">
+ * @RunWith(YetAnotherRunner.class)
+ * public class TheTest {
+ * @Rule public MockitoRule mockito = MockitoJUnit.rule();
+ * // ...
+ * }
+ * </code></pre>
+ *
+ * For more information see {@link MockitoJUnit#rule()}.
+ *
+ *
+ *
+ *
+ * <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>
+ *
+ * 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>
+ * <p>
+ * Allows specifying a custom message to be printed if verification fails.
+ * <p>
+ * Examples:
+ * <p>
+ * <pre class="code"><code class="java">
+ *
+ * // will print a custom message on verification failure
+ * verify(mock, description("This will print on failure")).someMethod();
+ *
+ * // will work with any verification mode
+ * 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>
+ * <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
+ * use the {@link ArgumentCaptor} to find the operands used and then do subsequent assertions on them. While
+ * for complex examples this can be useful, it's also long-winded.<p>
+ * Writing a lambda to express the match is quite easy. The argument to your function, when used in conjunction
+ * with argThat, will be passed to the ArgumentMatcher as a strongly typed object, so it is possible
+ * to do anything with it.
+ * <p>
+ * Examples:
+ * <p>
+ * <pre class="code"><code class="java">
+ *
+ * // verify a list only had strings of a certain length added to it
+ * // note - this will only compile under Java 8
+ * verify(list, times(2)).add(argThat(string -> string.length() < 5));
+ *
+ * // Java 7 equivalent - not as neat
+ * verify(list, times(2)).add(argThat(new ArgumentMatcher<String>(){
+ * public boolean matches(String arg) {
+ * return arg.length() < 5;
+ * }
+ * }));
+ *
+ * // more complex Java 8 example - where you can specify complex verification behaviour functionally
+ * verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));
+ *
+ * // this can also be used when defining the behaviour of a mock under different inputs
+ * // in this case if the input list was fewer than 3 items the mock returns null
+ * 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>
+ * <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,
+ * the more you need to typecast the arguments from {@link org.mockito.invocation.InvocationOnMock}.
+ *
+ * <p>
+ * Examples:
+ * <p>
+ * <pre class="code"><code class="java">
+ * // answer by returning 12 every time
+ * doAnswer(invocation -> 12).when(mock).doSomething();
+ *
+ * // answer by using one of the parameters - converting into the right
+ * // type as your go - in this case, returning the length of the second string parameter
+ * // as the answer. This gets long-winded quickly, with casting of parameters.
+ * doAnswer(invocation -> ((String)invocation.getArgument(1)).length())
+ * .when(mock).doSomething(anyString(), anyString(), anyString());
+ * </code></pre>
+ *
+ * For convenience it is possible to write custom answers/actions, which use the parameters to the method call,
+ * 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
+ *
+ * <p>
+ * Examples:
+ * <p>
+ * <pre class="code"><code class="java">
+ *
+ * // Example interface to be mocked has a function like:
+ * void execute(String operand, Callback callback);
+ *
+ * // the example callback has a function and the class under test
+ * // will depend on the callback being invoked
+ * void receive(String item);
+ *
+ * // Java 8 - style 1
+ * doAnswer(AdditionalAnswers.<String,Callback>answerVoid((operand, callback) -> callback.receive("dummy"))
+ * .when(mock).execute(anyString(), any(Callback.class));
+ *
+ * // Java 8 - style 2 - assuming static import of AdditionalAnswers
+ * doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))
+ * .when(mock).execute(anyString(), any(Callback.class));
+ *
+ * // Java 8 - style 3 - where mocking function to is a static member of test class
+ * private static void dummyCallbackImpl(String operation, Callback callback) {
+ * callback.receive("dummy");
+ * }
+ *
+ * doAnswer(answerVoid(TestClass::dummyCallbackImpl)
+ * .when(mock).execute(anyString(), any(Callback.class));
+ *
+ * // Java 7
+ * doAnswer(answerVoid(new AnswerFunctionalInterfaces.VoidAnswer2<String, Callback>() {
+ * public void answer(String operation, Callback callback) {
+ * callback.receive("dummy");
+ * }})).when(mock).execute(anyString(), any(Callback.class));
+ *
+ * // returning a value is possible with the answer() function
+ * // and the non-void version of the functional interfaces
+ * // so if the mock interface had a method like
+ * boolean isSameString(String input1, String input2);
+ *
+ * // this could be mocked
+ * // Java 8
+ * doAnswer(AdditionalAnswers.<Boolean,String,String>answer((input1, input2) -> input1.equals(input2))))
+ * .when(mock).execute(anyString(), anyString());
+ *
+ * // Java 7
+ * doAnswer(answer(new AnswerFunctionalInterfaces.Answer2<String, String, String>() {
+ * public String answer(String input1, String input2) {
+ * return input1 + input2;
+ * }})).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>
+ *
+ * <p>
+ * Mockito now preserves annotations on mocked methods and types as well as generic meta data. Previously, a mock type did not preserve
+ * annotations on types unless they were explicitly inherited and never retained annotations on methods. As a consequence, the following
+ * conditions now hold true:
+ *
+ * <pre class="code"><code class="java">
+ * {@literal @}{@code MyAnnotation
+ * class Foo {
+ * List<String> bar() { ... }
+ * }
+ *
+ * Class<?> mockType = mock(Foo.class).getClass();
+ * assert mockType.isAnnotationPresent(MyAnnotation.class);
+ * assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType;
+ * }</code></pre>
+ *
+ * <p>
+ * 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>
+ *
+ * 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.
+ * Our ambition is that Mockito "just works" with final classes and methods.
+ * Previously they were considered <em>unmockable</em>, preventing the user from mocking.
+ * We already started discussing how to make this feature enabled by default.
+ * Currently, the feature is still optional as we wait for more feedback from the community.
+ * <p>
+ * This feature is turned off by default because it is based on completely different mocking mechanism
+ * that requires more feedback from the community.
+ *
+ * <p>
+ * This alternative mock maker which uses
+ * a combination of both Java instrumentation API and sub-classing rather than creating a new class to represent
+ * a mock. This way, it becomes possible to mock final types and methods.
+ *
+ * <p>
+ * This mock maker is <strong>turned off by default</strong> because it is based on completely different mocking mechanism
+ * that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism,
+ * just create in the classpath a file <code>/mockito-extensions/org.mockito.plugins.MockMaker</code>
+ * containing the value <code>mock-maker-inline</code>.
+ *
+ * <p>
+ * Some noteworthy notes about this mock maker:
+ * <ul>
+ * <li>Mocking final types and enums is incompatible with mock settings like :
+ * <ul>
+ * <li>explicitly serialization support <code>withSettings().serializable()</code></li>
+ * <li>extra-interfaces <code>withSettings().extraInterfaces()</code></li>
+ * </ul>
+ * </li>
+ * <li>Some methods cannot be mocked
+ * <ul>
+ * <li>Package-visible methods of <code>java.*</code></li>
+ * <li><code>native</code> methods</li>
+ * </ul>
+ * </li>
+ * <li>This mock maker has been designed around Java Agent runtime attachment ; this require a compatible JVM,
+ * that is part of the JDK (or Java 9 VM). When running on a non-JDK VM prior to Java 9, it is however possible to
+ * manually add the <a href="http://bytebuddy.net">Byte Buddy Java agent jar</a> using the <code>-javaagent</code>
+ * parameter upon starting the JVM.
+ * </li>
+ * </ul>
+ *
+ * <p>
+ * If you are interested in more details of this feature please read the javadoc of
+ * <code>org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker</code>
+ */
+@SuppressWarnings("unchecked")
+public class Mockito extends ArgumentMatchers {
+
+ static final MockitoCore MOCKITO_CORE = new MockitoCore();
+
+ /**
+ * 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.)
+ */
+ public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;
+
+ /**
+ * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
+ * <p>
+ * {@link Answer} can be used to define the return values of unstubbed invocations.
+ * <p>
+ * This implementation can be helpful when working with legacy code.
+ * Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.
+ * 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.
+ * <p>
+ * <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 3.0.0
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
+ *
+ * //calling unstubbed method here:
+ * Stuff stuff = mock.getStuff();
+ *
+ * //using object returned by unstubbed call:
+ * stuff.doSomething();
+ *
+ * //Above doesn't yield NullPointerException this time!
+ * //Instead, SmartNullPointerException is thrown.
+ * //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.
+ * </code></pre>
+ */
+ public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;
+
+ /**
+ * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
+ * <p>
+ * {@link Answer} can be used to define the return values of unstubbed invocations.
+ * <p>
+ * 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.
+ * <p>
+ */
+ public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;
+
+ /**
+ * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
+ * <p>
+ * Example that shows how deep stub works:
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
+ *
+ * // note that we're stubbing a chain of methods here: getBar().getName()
+ * when(mock.getBar().getName()).thenReturn("deep");
+ *
+ * // note that we're chaining method calls: getBar().getName()
+ * assertEquals("deep", mock.getBar().getName());
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * <strong>WARNING: </strong>
+ * This feature should rarely be required for regular clean code! Leave it for legacy code.
+ * Mocking a mock to return a mock, to return a mock, (...), to return something meaningful
+ * hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
+ * </p>
+ *
+ * <p>
+ * Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.
+ * </p>
+ *
+ * <p>
+ * Please note that this answer will return existing mocks that matches the stub. This
+ * behavior is ok with deep stubs and allows verification to work on the last mock of the chain.
+ * <pre class="code"><code class="java">
+ * when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");
+ *
+ * mock.getBar("candy bar").getThingy().getName();
+ *
+ * assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());
+ * verify(mock.getBar("candy bar").getThingy()).getName();
+ * verify(mock.getBar(anyString()).getThingy()).getName();
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * Verification only works with the last mock in the chain. You can use verification modes.
+ * <pre class="code"><code class="java">
+ * when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");
+ * when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");
+ * when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");
+ *
+ * person.getAddress("the docks").getStreet().getName();
+ * person.getAddress("the docks").getStreet().getLongName();
+ * person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();
+ * person.getAddress("the docks").getStreet(Locale.CHINESE).getName();
+ *
+ * // note that we are actually referring to the very last mock in the stubbing chain.
+ * InOrder inOrder = inOrder(
+ * person.getAddress("the docks").getStreet(),
+ * person.getAddress("the docks").getStreet(Locale.CHINESE),
+ * person.getAddress("the docks").getStreet(Locale.ITALIAN)
+ * );
+ * inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();
+ * inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();
+ * inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();
+ * inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * How deep stub work internally?
+ * <pre class="code"><code class="java">
+ * //this:
+ * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
+ * when(mock.getBar().getName(), "deep");
+ *
+ * //is equivalent of
+ * Foo foo = mock(Foo.class);
+ * Bar bar = mock(Bar.class);
+ * when(foo.getBar()).thenReturn(bar);
+ * when(bar.getName()).thenReturn("deep");
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * This feature will not work when any return type of methods included in the chain cannot be mocked
+ * (for example: is a primitive or a final class). This is because of java type system.
+ * </p>
+ */
+ public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;
+
+ /**
+ * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
+ * <p>
+ * {@link Answer} can be used to define the return values of unstubbed invocations.
+ * <p>
+ * This implementation can be helpful when working with legacy code.
+ * When this implementation is used, unstubbed methods will delegate to the real implementation.
+ * This is a way to create a partial mock object that calls real methods by default.
+ * <p>
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
+ *
+ * // this calls the real implementation of Foo.getSomething()
+ * value = mock.getSomething();
+ *
+ * when(mock.getSomething()).thenReturn(fakeValue);
+ *
+ * // now fakeValue is returned
+ * value = mock.getSomething();
+ * </code></pre>
+ */
+ public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
+
+ /**
+ * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.
+ *
+ * Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal
+ * to the class or a superclass.
+ *
+ * <p><b>Keep in mind this answer uses the return type of a method.
+ * If this type is assignable to the class of the mock, it will return the mock.
+ * Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>
+ *
+ * Consider a HttpBuilder used in a HttpRequesterWithHeaders.
+ *
+ * <pre class="code"><code class="java">
+ * public class HttpRequesterWithHeaders {
+ *
+ * private HttpBuilder builder;
+ *
+ * public HttpRequesterWithHeaders(HttpBuilder builder) {
+ * this.builder = builder;
+ * }
+ *
+ * public String request(String uri) {
+ * return builder.withUrl(uri)
+ * .withHeader("Content-type: application/json")
+ * .withHeader("Authorization: Bearer")
+ * .request();
+ * }
+ * }
+ *
+ * private static class HttpBuilder {
+ *
+ * private String uri;
+ * private List<String> headers;
+ *
+ * public HttpBuilder() {
+ * this.headers = new ArrayList<String>();
+ * }
+ *
+ * public HttpBuilder withUrl(String uri) {
+ * this.uri = uri;
+ * return this;
+ * }
+ *
+ * public HttpBuilder withHeader(String header) {
+ * this.headers.add(header);
+ * return this;
+ * }
+ *
+ * public String request() {
+ * return uri + headers.toString();
+ * }
+ * }
+ * </code></pre>
+ *
+ * The following test will succeed
+ *
+ * <pre><code>
+ * @Test
+ * public void use_full_builder_with_terminating_method() {
+ * HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);
+ * HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);
+ * String response = "StatusCode: 200";
+ *
+ * when(builder.request()).thenReturn(response);
+ *
+ * assertThat(requester.request("URI")).isEqualTo(response);
+ * }
+ * </code></pre>
+ */
+ public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;
+
+ /**
+ * Creates mock object of given class or interface.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param classToMock class or interface to mock
+ * @return mock object
+ */
+ public static <T> T mock(Class<T> classToMock) {
+ return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
+ }
+
+ /**
+ * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
+ * <p>
+ * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.
+ * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.
+ * <p>
+ * <b>If you use <code>@Mock</code> annotation then you've got naming mocks for free!</b> <code>@Mock</code> uses field name as mock name. {@link Mock Read more.}
+ * <p>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param classToMock class or interface to mock
+ * @param name of the mock
+ * @return mock object
+ */
+ public static <T> T mock(Class<T> classToMock, String name) {
+ return mock(classToMock, withSettings()
+ .name(name)
+ .defaultAnswer(RETURNS_DEFAULTS));
+ }
+
+ /**
+ * Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.
+ * Can be used to find out if given object is a Mockito mock
+ * or to find out if a given mock is a spy or mock.
+ * <p>
+ * In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
+ * e.g. invocations, stubbing info, etc.
+ *
+ * @param toInspect - object to inspect. null input is allowed.
+ * @return A {@link org.mockito.MockingDetails} instance.
+ * @since 1.9.5
+ */
+ public static MockingDetails mockingDetails(Object toInspect) {
+ return MOCKITO_CORE.mockingDetails(toInspect);
+ }
+
+ /**
+ * Creates mock with a specified strategy for its answers to interactions.
+ * It's quite an advanced feature and typically you don't need it to write decent tests.
+ * However it can be helpful when working with legacy systems.
+ * <p>
+ * It is the default answer so it will be used <b>only when you don't</b> stub the method call.
+ *
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
+ * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
+ * </code></pre>
+ *
+ * <p>See examples in javadoc for {@link Mockito} class</p>
+ *
+ * @param classToMock class or interface to mock
+ * @param defaultAnswer default answer for unstubbed methods
+ *
+ * @return mock object
+ */
+ public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {
+ return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
+ }
+
+ /**
+ * Creates a mock with some non-standard settings.
+ * <p>
+ * The number of configuration points for a mock grows
+ * so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
+ * Hence {@link MockSettings}.
+ * <pre class="code"><code class="java">
+ * Listener mock = mock(Listener.class, withSettings()
+ * .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
+ * );
+ * </code></pre>
+ * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?
+ * Is the code under test so complicated that it requires non-standard mocks?
+ * Wouldn't you prefer to refactor the code under test so it is testable in a simple way?
+ * <p>
+ * See also {@link Mockito#withSettings()}
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param classToMock class or interface to mock
+ * @param mockSettings additional mock settings
+ * @return mock object
+ */
+ public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
+ return MOCKITO_CORE.mock(classToMock, mockSettings);
+ }
+
+ /**
+ * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed.
+ * <p>
+ * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.
+ * <p>
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //optionally, you can stub out some methods:
+ * when(spy.size()).thenReturn(100);
+ *
+ * //using the spy calls <b>real</b> methods
+ * spy.add("one");
+ * spy.add("two");
+ *
+ * //prints "one" - the first element of a list
+ * System.out.println(spy.get(0));
+ *
+ * //size() method was stubbed - 100 is printed
+ * System.out.println(spy.size());
+ *
+ * //optionally, you can verify
+ * verify(spy).add("one");
+ * verify(spy).add("two");
+ * </code></pre>
+ *
+ * <h4>Important gotcha on spying real objects!</h4>
+ * <ol>
+ * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
+ * Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
+ * family of methods for stubbing. Example:
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(spy.get(0)).thenReturn("foo");
+ *
+ * //You have to use doReturn() for stubbing
+ * doReturn("foo").when(spy).get(0);
+ * </code></pre>
+ * </li>
+ *
+ * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
+ * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
+ * and their effect on real instance state.
+ * The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
+ * you won't see any effects on the real instance.</li>
+ *
+ * <li>Watch out for final methods.
+ * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
+ * Also you won't be able to verify those method as well.
+ * </li>
+ * </ol>
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.
+ * It may troublesome for code that rely on the spy to have these annotations.</p>
+ *
+ *
+ * @param object
+ * to spy on
+ * @return a spy of the real object
+ */
+ public static <T> T spy(T object) {
+ return MOCKITO_CORE.mock((Class<T>) object.getClass(), withSettings()
+ .spiedInstance(object)
+ .defaultAnswer(CALLS_REAL_METHODS));
+ }
+
+ /**
+ * Please refer to the documentation of {@link #spy(Object)}.
+ * Overusing spies hints at code design smells.
+ * <p>
+ * This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.
+ * Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.
+ * This is particularly useful for spying on abstract classes because they cannot be instantiated.
+ * See also {@link MockSettings#useConstructor()}.
+ * <p>
+ * Examples:
+ * <pre class="code"><code class="java">
+ * SomeAbstract spy = spy(SomeAbstract.class);
+ *
+ * //Robust API, via settings builder:
+ * OtherAbstract spy = mock(OtherAbstract.class, withSettings()
+ * .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
+ *
+ * //Mocking a non-static inner abstract class:
+ * InnerAbstract spy = mock(InnerAbstract.class, withSettings()
+ * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
+ * </code></pre>
+ *
+ * @param classToSpy the class to spy
+ * @param <T> type of the spy
+ * @return a spy of the provided class
+ * @since 1.10.12
+ */
+ @Incubating
+ public static <T> T spy(Class<T> classToSpy) {
+ return MOCKITO_CORE.mock(classToSpy, withSettings()
+ .useConstructor()
+ .defaultAnswer(CALLS_REAL_METHODS));
+ }
+
+ /**
+ * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
+ * <p>
+ * Simply put: "<b>When</b> the x method is called <b>then</b> return y".
+ *
+ * <p>
+ * Examples:
+ *
+ * <pre class="code"><code class="java">
+ * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);
+ *
+ * //you can use flexible argument matchers, e.g:
+ * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);
+ *
+ * //setting exception to be thrown:
+ * when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
+ *
+ * //you can set different behavior for consecutive method calls.
+ * //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
+ * when(mock.someMethod("some arg"))
+ * .thenThrow(new RuntimeException())
+ * .thenReturn("foo");
+ *
+ * //Alternative, shorter version for consecutive stubbing:
+ * when(mock.someMethod("some arg"))
+ * .thenReturn("one", "two");
+ * //is the same as:
+ * when(mock.someMethod("some arg"))
+ * .thenReturn("one")
+ * .thenReturn("two");
+ *
+ * //shorter version for consecutive method calls throwing exceptions:
+ * when(mock.someMethod("some arg"))
+ * .thenThrow(new RuntimeException(), new NullPointerException();
+ *
+ * </code></pre>
+ *
+ * For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable...)}
+ * <p>
+ * Stubbing can be overridden: for example common stubbing can go to fixture
+ * setup but the test methods can override it.
+ * Please note that overridding stubbing is a potential code smell that points out too much stubbing.
+ * <p>
+ * Once stubbed, the method will always return stubbed value regardless
+ * of how many times it is called.
+ * <p>
+ * Last stubbing is more important - when you stubbed the same method with
+ * the same arguments many times.
+ * <p>
+ * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
+ * 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
+ * @param methodCall method to be stubbed
+ * @return OngoingStubbing object used to stub fluently.
+ * <strong>Do not</strong> create a reference to this returned object.
+ */
+ public static <T> OngoingStubbing<T> when(T methodCall) {
+ return MOCKITO_CORE.when(methodCall);
+ }
+
+ /**
+ * Verifies certain behavior <b>happened once</b>.
+ * <p>
+ * Alias to <code>verify(mock, times(1))</code> E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock).someMethod("some arg");
+ * </code></pre>
+ * Above is equivalent to:
+ * <pre class="code"><code class="java">
+ * verify(mock, times(1)).someMethod("some arg");
+ * </code></pre>
+ * <p>
+ * Arguments passed are compared using <code>equals()</code> method.
+ * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
+ * <p>
+ * Although it is possible to verify a stubbed invocation, usually <b>it's just redundant</b>.
+ * 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
+ *
+ * @param mock to be verified
+ * @return mock object itself
+ */
+ public static <T> T verify(T mock) {
+ return MOCKITO_CORE.verify(mock, times(1));
+ }
+
+ /**
+ * Verifies certain behavior happened at least once / exact number of times / never. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, times(5)).someMethod("was called five times");
+ *
+ * verify(mock, atLeast(2)).someMethod("was called at least two times");
+ *
+ * //you can use flexible argument matchers, e.g:
+ * verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>);
+ * </code></pre>
+ *
+ * <b>times(1) is the default</b> and can be omitted
+ * <p>
+ * Arguments passed are compared using <code>equals()</code> method.
+ * Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
+ * <p>
+ *
+ * @param mock to be verified
+ * @param mode times(x), atLeastOnce() or never()
+ *
+ * @return mock object itself
+ */
+ public static <T> T verify(T mock, VerificationMode mode) {
+ return MOCKITO_CORE.verify(mock, mode);
+ }
+
+ /**
+ * 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.
+ * <p>
+ * Instead of <code>#reset()</code> please consider writing simple, small and focused test methods over lengthy, over-specified tests.
+ * <b>First potential code smell is <code>reset()</code> in the middle of the test method.</b> This probably means you're testing too much.
+ * Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
+ * There are several threads about it on mockito mailing list.
+ * <p>
+ * The only reason we added <code>reset()</code> method is to
+ * make it possible to work with container-injected mocks.
+ * For more information see the FAQ (<a href="https://github.com/mockito/mockito/wiki/FAQ">here</a>).
+ * <p>
+ * <b>Don't harm yourself.</b> <code>reset()</code> in the middle of the test method is a code smell (you're probably testing too much).
+ * <pre class="code"><code class="java">
+ * List mock = mock(List.class);
+ * when(mock.size()).thenReturn(10);
+ * mock.add(1);
+ *
+ * reset(mock);
+ * //at this point the mock forgot any interactions & stubbing
+ * </code></pre>
+ *
+ * @param <T> The Type of the mocks
+ * @param mocks to be reset
+ */
+ public static <T> void reset(T ... mocks) {
+ MOCKITO_CORE.reset(mocks);
+ }
+
+ /**
+ * Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:
+ * <ul>
+ * <li>You are using a dependency injection framework to inject your mocks.</li>
+ * <li>The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.</li>
+ * </ul>
+ *
+ * <b>Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.</b>
+ * @param <T> The type of the mocks
+ * @param mocks The mocks to clear the invocations for
+ */
+ public static <T> void clearInvocations(T ... mocks) {
+ MOCKITO_CORE.clearInvocations(mocks);
+ }
+
+ /**
+ * Checks if any of given mocks has any unverified interaction.
+ * <p>
+ * You can use this method after you verified your mocks - to make sure that nothing
+ * else was invoked on your mocks.
+ * <p>
+ * See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
+ * <p>
+ * Stubbed invocations (if called) are also treated as interactions.
+ * <p>
+ * A word of <b>warning</b>:
+ * 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>.
+ * <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.
+ * Consider writing nice code that makes interactions only in test methods.
+ *
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * //interactions
+ * mock.doSomething();
+ * mock.doSomethingUnexpected();
+ *
+ * //verification
+ * verify(mock).doSomething();
+ *
+ * //following will fail because 'doSomethingUnexpected()' is unexpected
+ * verifyNoMoreInteractions(mock);
+ *
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param mocks to be verified
+ */
+ public static void verifyNoMoreInteractions(Object... mocks) {
+ MOCKITO_CORE.verifyNoMoreInteractions(mocks);
+ }
+
+ /**
+ * Verifies that no interactions happened on given mocks.
+ * <pre class="code"><code class="java">
+ * verifyZeroInteractions(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
+ *
+ * @param mocks to be verified
+ */
+ public static void verifyZeroInteractions(Object... mocks) {
+ MOCKITO_CORE.verifyNoMoreInteractions(mocks);
+ }
+
+ /**
+ * Use <code>doThrow()</code> when you want to stub the void method with an exception.
+ * <p>
+ * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
+ * does not like void methods inside brackets...
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException()).when(mock).someVoidMethod();
+ * </code></pre>
+ *
+ * @param toBeThrown to be thrown when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ public static Stubber doThrow(Throwable... toBeThrown) {
+ return MOCKITO_CORE.stubber().doThrow(toBeThrown);
+ }
+
+ /**
+ * Use <code>doThrow()</code> when you want to stub the void method with an exception.
+ * <p>
+ * A new exception instance will be created for each method invocation.
+ * <p>
+ * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
+ * does not like void methods inside brackets...
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * doThrow(RuntimeException.class).when(mock).someVoidMethod();
+ * </code></pre>
+ *
+ * @param toBeThrown to be thrown when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ * @since 2.1.0
+ */
+ public static Stubber doThrow(Class<? extends Throwable> toBeThrown) {
+ return MOCKITO_CORE.stubber().doThrow(toBeThrown);
+ }
+
+ /**
+ * Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use
+ * <code>doThrow()</code> when you want to stub the void method to throw several exception of specified class.
+ * <p>
+ * A new exception instance will be created for each method invocation.
+ * <p>
+ * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
+ * does not like void methods inside brackets...
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();
+ * </code></pre>
+ *
+ * @param toBeThrown to be thrown when the stubbed method is called
+ * @param toBeThrownNext next to be thrown when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ * @since 2.1.0
+ */
+ // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
+ @SuppressWarnings ({"unchecked", "varargs"})
+ public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) {
+ return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
+ }
+
+
+ /**
+ * Use <code>doCallRealMethod()</code> when you want to call the real implementation of a method.
+ * <p>
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ * <p>
+ * See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks.
+ * <b>Mockito.spy() is a recommended way of creating partial mocks.</b>
+ * The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * Foo mock = mock(Foo.class);
+ * doCallRealMethod().when(mock).someVoidMethod();
+ *
+ * // this will call the real implementation of Foo.someVoidMethod()
+ * mock.someVoidMethod();
+ * </code></pre>
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return stubber - to select a method for stubbing
+ * @since 1.9.5
+ */
+ public static Stubber doCallRealMethod() {
+ return MOCKITO_CORE.stubber().doCallRealMethod();
+ }
+
+ /**
+ * Use <code>doAnswer()</code> when you want to stub a void method with generic {@link Answer}.
+ * <p>
+ * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * doAnswer(new Answer() {
+ * public Object answer(InvocationOnMock invocation) {
+ * Object[] args = invocation.getArguments();
+ * Mock mock = invocation.getMock();
+ * return null;
+ * }})
+ * .when(mock).someMethod();
+ * </code></pre>
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param answer to answer when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ public static Stubber doAnswer(Answer answer) {
+ return MOCKITO_CORE.stubber().doAnswer(answer);
+ }
+
+ /**
+ * Use <code>doNothing()</code> for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b>
+ * However, there are rare situations when doNothing() comes handy:
+ * <p>
+ * <ol>
+ * <li>Stubbing consecutive calls on a void method:
+ * <pre class="code"><code class="java">
+ * doNothing().
+ * doThrow(new RuntimeException())
+ * .when(mock).someVoidMethod();
+ *
+ * //does nothing the first time:
+ * mock.someVoidMethod();
+ *
+ * //throws RuntimeException the next time:
+ * mock.someVoidMethod();
+ * </code></pre>
+ * </li>
+ * <li>When you spy real objects and you want the void method to do nothing:
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //let's make clear() do nothing
+ * doNothing().when(spy).clear();
+ *
+ * spy.add("one");
+ *
+ * //clear() does nothing, so the list still contains "one"
+ * spy.clear();
+ * </code></pre>
+ * </li>
+ * </ol>
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return stubber - to select a method for stubbing
+ */
+ public static Stubber doNothing() {
+ return MOCKITO_CORE.stubber().doNothing();
+ }
+
+ /**
+ * Use <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
+ * <p>
+ * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
+ * and more readable</b> (especially when stubbing consecutive calls).
+ * <p>
+ * Here are those rare occasions when doReturn() comes handy:
+ * <p>
+ *
+ * <ol>
+ * <li>When spying real objects and calling real methods on a spy brings side effects
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(spy.get(0)).thenReturn("foo");
+ *
+ * //You have to use doReturn() for stubbing:
+ * doReturn("foo").when(spy).get(0);
+ * </code></pre>
+ * </li>
+ *
+ * <li>Overriding a previous exception-stubbing:
+ * <pre class="code"><code class="java">
+ * when(mock.foo()).thenThrow(new RuntimeException());
+ *
+ * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
+ * when(mock.foo()).thenReturn("bar");
+ *
+ * //You have to use doReturn() for stubbing:
+ * doReturn("bar").when(mock).foo();
+ * </code></pre>
+ * </li>
+ * </ol>
+ *
+ * Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
+ * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
+ * overridding stubbing is a potential code smell that points out too much stubbing.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param toBeReturned to be returned when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ public static Stubber doReturn(Object toBeReturned) {
+ return MOCKITO_CORE.stubber().doReturn(toBeReturned);
+ }
+
+ /**
+ * Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
+ * <code>doReturn()</code> in those rare occasions when you cannot use {@link Mockito#when(Object)}.
+ * <p>
+ * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe
+ * and more readable</b> (especially when stubbing consecutive calls).
+ * <p>
+ * Here are those rare occasions when doReturn() comes handy:
+ * <p>
+ *
+ * <ol>
+ * <li>When spying real objects and calling real methods on a spy brings side effects
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(spy.get(0)).thenReturn("foo", "bar", "qix");
+ *
+ * //You have to use doReturn() for stubbing:
+ * doReturn("foo", "bar", "qix").when(spy).get(0);
+ * </code></pre>
+ * </li>
+ *
+ * <li>Overriding a previous exception-stubbing:
+ * <pre class="code"><code class="java">
+ * when(mock.foo()).thenThrow(new RuntimeException());
+ *
+ * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown.
+ * when(mock.foo()).thenReturn("bar", "foo", "qix");
+ *
+ * //You have to use doReturn() for stubbing:
+ * doReturn("bar", "foo", "qix").when(mock).foo();
+ * </code></pre>
+ * </li>
+ * </ol>
+ *
+ * Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
+ * Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
+ * overridding stubbing is a potential code smell that points out too much stubbing.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param toBeReturned to be returned when the stubbed method is called
+ * @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ * @since 2.1.0
+ */
+ @SuppressWarnings({"unchecked", "varargs"})
+ public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
+ return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
+ }
+
+ /**
+ * Creates {@link org.mockito.InOrder} object that allows verifying mocks in order.
+ *
+ * <pre class="code"><code class="java">
+ * InOrder inOrder = inOrder(firstMock, secondMock);
+ *
+ * inOrder.verify(firstMock).add("was called first");
+ * inOrder.verify(secondMock).add("was called second");
+ * </code></pre>
+ *
+ * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one
+ * but only those that you are interested in testing in order.
+ * <p>
+ * Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
+ * <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>.
+ * <p>
+ * As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param mocks to be verified in order
+ *
+ * @return InOrder object to be used to verify in order
+ */
+ public static InOrder inOrder(Object... mocks) {
+ return MOCKITO_CORE.inOrder(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>.
+ * 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>
+ * Bear in mind that Mockito does not recommend bombarding every test with <code>verifyNoMoreInteractions()</code>
+ * for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
+ * Other words: all <b>*stubbed*</b> methods of given mocks are marked <b>*verified*</b> so that they don't get in a way during verifyNoMoreInteractions().
+ * <p>
+ * This method <b>changes the input mocks</b>! This method returns input mocks just for convenience.
+ * <p>
+ * Ignored stubs will also be ignored for verification inOrder, including {@link org.mockito.InOrder#verifyNoMoreInteractions()}.
+ * See the second example.
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
+ * List mock1 = mock(List.class), mock2 = mock(List.class);
+ *
+ * //stubbing mocks:
+ * when(mock1.get(0)).thenReturn(10);
+ * when(mock2.get(0)).thenReturn(20);
+ *
+ * //using mocks by calling stubbed get(0) methods:
+ * System.out.println(mock1.get(0)); //prints 10
+ * System.out.println(mock2.get(0)); //prints 20
+ *
+ * //using mocks by calling clear() methods:
+ * mock1.clear();
+ * mock2.clear();
+ *
+ * //verification:
+ * verify(mock1).clear();
+ * verify(mock2).clear();
+ *
+ * //verifyNoMoreInteractions() fails because get() methods were not accounted for.
+ * try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
+ *
+ * //However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
+ * verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
+ *
+ * //Remember that ignoreStubs() <b>*changes*</b> the input mocks and returns them for convenience.
+ * </code></pre>
+ * Ignoring stubs can be used with <b>verification in order</b>:
+ * <pre class="code"><code class="java">
+ * List list = mock(List.class);
+ * when(mock.get(0)).thenReturn("foo");
+ *
+ * list.add(0);
+ * System.out.println(list.get(0)); //we don't want to verify this
+ * list.clear();
+ *
+ * InOrder inOrder = inOrder(ignoreStubs(list));
+ * inOrder.verify(list).add(0);
+ * inOrder.verify(list).clear();
+ * inOrder.verifyNoMoreInteractions();
+ * </code></pre>
+ *
+ * @since 1.9.0
+ * @param mocks input mocks that will be changed
+ * @return the same mocks that were passed in as parameters
+ */
+ public static Object[] ignoreStubs(Object... mocks) {
+ return MOCKITO_CORE.ignoreStubs(mocks);
+ }
+
+ /**
+ * Allows verifying exact number of invocations. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, times(2)).someMethod("some arg");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param wantedNumberOfInvocations wanted number of invocations
+ *
+ * @return verification mode
+ */
+ public static VerificationMode times(int wantedNumberOfInvocations) {
+ return VerificationModeFactory.times(wantedNumberOfInvocations);
+ }
+
+ /**
+ * Alias to <code>times(0)</code>, see {@link Mockito#times(int)}
+ * <p>
+ * Verifies that interaction did not happen. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, never()).someMethod();
+ * </code></pre>
+ *
+ * <p>
+ * If you want to verify there were NO interactions with the mock
+ * check out {@link Mockito#verifyZeroInteractions(Object...)}
+ * or {@link Mockito#verifyNoMoreInteractions(Object...)}
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return verification mode
+ */
+ public static VerificationMode never() {
+ return times(0);
+ }
+
+ /**
+ * Allows at-least-once verification. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, atLeastOnce()).someMethod("some arg");
+ * </code></pre>
+ * Alias to <code>atLeast(1)</code>.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return verification mode
+ */
+ public static VerificationMode atLeastOnce() {
+ return VerificationModeFactory.atLeastOnce();
+ }
+
+ /**
+ * Allows at-least-x verification. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, atLeast(3)).someMethod("some arg");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param minNumberOfInvocations minimum number of invocations
+ *
+ * @return verification mode
+ */
+ public static VerificationMode atLeast(int minNumberOfInvocations) {
+ return VerificationModeFactory.atLeast(minNumberOfInvocations);
+ }
+
+ /**
+ * Allows at-most-x verification. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, atMost(3)).someMethod("some arg");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param maxNumberOfInvocations max number of invocations
+ *
+ * @return verification mode
+ */
+ public static VerificationMode atMost(int maxNumberOfInvocations) {
+ return VerificationModeFactory.atMost(maxNumberOfInvocations);
+ }
+
+ /**
+ * Allows non-greedy verification in order. For example
+ * <pre class="code"><code class="java">
+ * inOrder.verify( mock, calls( 2 )).someMethod( "some arg" );
+ * </code></pre>
+ * <ul>
+ * <li>will not fail if the method is called 3 times, unlike times( 2 )</li>
+ * <li>will not mark the third invocation as verified, unlike atLeast( 2 )</li>
+ * </ul>
+ * This verification mode can only be used with in order verification.
+ * @param wantedNumberOfInvocations number of invocations to verify
+ * @return verification mode
+ */
+ public static VerificationMode calls( int wantedNumberOfInvocations ){
+ return VerificationModeFactory.calls( wantedNumberOfInvocations );
+ }
+
+ /**
+ * Allows checking if given method was the only one invoked. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, only()).someMethod();
+ * //above is a shorthand for following 2 lines of code:
+ * verify(mock).someMethod();
+ * verifyNoMoreInvocations(mock);
+ * </code></pre>
+ *
+ * <p>
+ * See also {@link Mockito#verifyNoMoreInteractions(Object...)}
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return verification mode
+ */
+ public static VerificationMode only() {
+ return VerificationModeFactory.only();
+ }
+
+ /**
+ * 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 has not already happened. May be useful for testing in concurrent
+ * conditions.
+ * <p>
+ * This differs from {@link Mockito#after after()} in that after() will wait the full period, unless
+ * the final test result is known early (e.g. if a never() fails), whereas timeout() will stop early as soon
+ * as verification passes, producing different behaviour when used with times(2), for example, which can pass
+ * and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would run until
+ * times(2) failed, and then fail.
+ * <p>
+ * This feature should be used rarely - figure out a better way of testing your multi-threaded system.
+ * <pre class="code"><code class="java">
+ * //passes when someMethod() is called within given time span
+ * verify(mock, timeout(100)).someMethod();
+ * //above is an alias to:
+ * verify(mock, timeout(100).times(1)).someMethod();
+ *
+ * //passes as soon as someMethod() has been called 2 times before the given timeout
+ * verify(mock, timeout(100).times(2)).someMethod();
+ *
+ * //equivalent: this also passes as soon as someMethod() has been called 2 times before the given timeout
+ * verify(mock, timeout(100).atLeast(2)).someMethod();
+ *
+ * //verifies someMethod() within given time span using given verification mode
+ * //useful only if you have your own custom verification modes.
+ * verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param millis - time span in milliseconds
+ *
+ * @return verification mode
+ */
+ public static VerificationWithTimeout timeout(long millis) {
+ return new Timeout(millis, VerificationModeFactory.times(1));
+ }
+
+ /**
+ * Allows verifying over a given period. It causes a verify to wait for a specified period of time for a desired
+ * interaction rather than failing immediately if has not already happened. May be useful for testing in concurrent
+ * conditions.
+ * <p>
+ * This differs from {@link Mockito#timeout timeout()} in that after() will wait the full period, whereas timeout()
+ * will stop early as soon as verification passes, producing different behaviour when used with times(2), for example,
+ * which can pass and then later fail. In that case, timeout would pass as soon as times(2) passes, whereas after would
+ * run the full time, which point it will fail, as times(2) has failed.
+ * <p>
+ * This feature should be used rarely - figure out a better way of testing your multi-threaded system.
+ * <p>
+ * Not yet implemented to work with InOrder verification.
+ * <pre class="code"><code class="java">
+ * //passes after 100ms, if someMethod() has only been called once at that time.
+ * verify(mock, after(100)).someMethod();
+ * //above is an alias to:
+ * verify(mock, after(100).times(1)).someMethod();
+ *
+ * //passes if someMethod() is called <b>*exactly*</b> 2 times after the given timespan
+ * verify(mock, after(100).times(2)).someMethod();
+ *
+ * //passes if someMethod() has not been called after the given timespan
+ * verify(mock, after(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(100, yourOwnVerificationMode)).someMethod();
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param millis - time span in milliseconds
+ *
+ * @return verification mode
+ */
+ public static VerificationAfterDelay after(long millis) {
+ return new After(millis, VerificationModeFactory.times(1));
+ }
+
+ /**
+ * 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>
+ * <p>
+ * In case of questions you may also post to mockito mailing list: <a href="http://groups.google.com/group/mockito">http://groups.google.com/group/mockito</a>
+ * <p>
+ * <code>validateMockitoUsage()</code> <b>explicitly validates</b> the framework state to detect invalid use of Mockito.
+ * However, this feature is optional <b>because Mockito validates the usage all the time...</b> but there is a gotcha so read on.
+ * <p>
+ * Examples of incorrect use:
+ * <pre class="code"><code class="java">
+ * //Oops, thenReturn() part is missing:
+ * when(mock.get());
+ *
+ * //Oops, verified method call is inside verify() where it should be on the outside:
+ * verify(mock.execute());
+ *
+ * //Oops, missing method to verify:
+ * verify(mock);
+ * </code></pre>
+ *
+ * Mockito throws exceptions if you misuse it so that you know if your tests are written correctly.
+ * The gotcha is that Mockito does the validation <b>next time</b> you use the framework (e.g. next time you verify, stub, call mock etc.).
+ * But even though the exception might be thrown in the next test,
+ * the exception <b>message contains a navigable stack trace element</b> with location of the defect.
+ * Hence you can click and find the place where Mockito was misused.
+ * <p>
+ * Sometimes though, you might want to validate the framework usage explicitly.
+ * For example, one of the users wanted to put <code>validateMockitoUsage()</code> in his <code>@After</code> method
+ * so that he knows immediately when he misused Mockito.
+ * Without it, he would have known about it not sooner than <b>next time</b> he used the framework.
+ * One more benefit of having <code>validateMockitoUsage()</code> in <code>@After</code> is that jUnit runner and rule will always fail in the test method with defect
+ * whereas ordinary 'next-time' validation might fail the <b>next</b> test method.
+ * But even though JUnit might report next test as red, don't worry about it
+ * and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito.
+ * <p>
+ * <b>Both built-in runner: {@link MockitoJUnitRunner} and rule: {@link MockitoRule}</b> do validateMockitoUsage() after each test method.
+ * <p>
+ * Bear in mind that <b>usually you don't have to <code>validateMockitoUsage()</code></b>
+ * and framework validation triggered on next-time basis should be just enough,
+ * mainly because of enhanced exception message with clickable location of defect.
+ * However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure
+ * (like your own runner or base class for all tests) because adding a special action to <code>@After</code> has zero cost.
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ */
+ public static void validateMockitoUsage() {
+ MOCKITO_CORE.validateMockitoUsage();
+ }
+
+ /**
+ * Allows mock creation with additional mock settings.
+ * <p>
+ * Don't use it too often.
+ * Consider writing simple tests that use simple mocks.
+ * Repeat after me: simple tests push simple, KISSy, readable & maintainable code.
+ * If you cannot write a test in a simple way - refactor the code under test.
+ * <p>
+ * Examples of mock settings:
+ * <pre class="code"><code class="java">
+ * //Creates mock with different default answer & name
+ * Foo mock = mock(Foo.class, withSettings()
+ * .defaultAnswer(RETURNS_SMART_NULLS)
+ * .name("cool mockie"));
+ *
+ * //Creates mock with different default answer, descriptive name and extra interfaces
+ * Foo mock = mock(Foo.class, withSettings()
+ * .defaultAnswer(RETURNS_SMART_NULLS)
+ * .name("cool mockie")
+ * .extraInterfaces(Bar.class));
+ * </code></pre>
+ * {@link MockSettings} has been introduced for two reasons.
+ * Firstly, to make it easy to add another mock settings when the demand comes.
+ * Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.
+ * <p>
+ * See javadoc for {@link MockSettings} to learn about possible mock settings.
+ * <p>
+ *
+ * @return mock settings instance with defaults.
+ */
+ public static MockSettings withSettings() {
+ return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
+ }
+
+ /**
+ * Adds a description to be printed if verification fails.
+ * <pre class="code"><code class="java">
+ * verify(mock, description("This will print on failure")).someMethod("some arg");
+ * </code></pre>
+ * @param description The description to print on failure.
+ * @return verification mode
+ * @since 2.1.0
+ */
+ public static VerificationMode description(String description) {
+ return times(1).description(description);
+ }
+
+ /**
+ * @deprecated - please use {@link MockingDetails#printInvocations()}.
+ */
+ @Deprecated
+ static MockitoDebugger debug() {
+ return new MockitoDebuggerImpl();
+ }
+
+ /**
+ * For advanced users or framework integrators. See {@link MockitoFramework} class.
+ *
+ * @since 2.1.0
+ */
+ @Incubating
+ public static MockitoFramework framework() {
+ return new DefaultMockitoFramework();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/MockitoAnnotations.java b/mockito-updated/src/org/mockito/MockitoAnnotations.java
new file mode 100644
index 0000000..6722cbb
--- /dev/null
+++ b/mockito-updated/src/org/mockito/MockitoAnnotations.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito;
+
+import org.mockito.configuration.AnnotationEngine;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.configuration.GlobalConfiguration;
+import org.mockito.runners.MockitoJUnitRunner;
+
+/**
+ * MockitoAnnotations.initMocks(this); initializes fields annotated with Mockito annotations.
+ * <p>
+ * <ul>
+ * <li>Allows shorthand creation of objects required for testing.</li>
+ * <li>Minimizes repetitive mock creation code.</li>
+ * <li>Makes the test class more readable.</li>
+ * <li>Makes the verification error easier to read because <b>field name</b> is used to identify the mock.</li>
+ * </ul>
+ *
+ * <pre class="code"><code class="java">
+ * public class ArticleManagerTest extends SampleBaseTestCase {
+ *
+ * @Mock private ArticleCalculator calculator;
+ * @Mock private ArticleDatabase database;
+ * @Mock private UserProvider userProvider;
+ *
+ * private ArticleManager manager;
+ *
+ * @Before public void setup() {
+ * manager = new ArticleManager(userProvider, database, calculator);
+ * }
+ * }
+ *
+ * public class SampleBaseTestCase {
+ *
+ * @Before public void initMocks() {
+ * MockitoAnnotations.initMocks(this);
+ * }
+ * }
+ * </code></pre>
+ * <p>
+ * Read also about other annotations @{@link Spy}, @{@link Captor}, @{@link InjectMocks}
+ * <p>
+ * <b><code>MockitoAnnotations.initMocks(this)</code></b> method has to called to initialize annotated fields.
+ * <p>
+ * In above example, <code>initMocks()</code> is called in @Before (JUnit4) method of test's base class.
+ * For JUnit3 <code>initMocks()</code> can go to <code>setup()</code> method of a base class.
+ * You can also put initMocks() in your JUnit runner (@RunWith) or use built-in runner: {@link MockitoJUnitRunner}
+ */
+public class MockitoAnnotations {
+
+ /**
+ * Initializes objects annotated with Mockito annotations for given testClass:
+ * @{@link org.mockito.Mock}, @{@link Spy}, @{@link Captor}, @{@link InjectMocks}
+ * <p>
+ * See examples in javadoc for {@link MockitoAnnotations} class.
+ */
+ public static void initMocks(Object testClass) {
+ if (testClass == null) {
+ throw new MockitoException("testClass cannot be null. For info how to use @Mock annotations see examples in javadoc for MockitoAnnotations class");
+ }
+
+ AnnotationEngine annotationEngine = new GlobalConfiguration().getAnnotationEngine();
+ annotationEngine.process(testClass.getClass(), testClass);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/MockitoDebugger.java b/mockito-updated/src/org/mockito/MockitoDebugger.java
new file mode 100644
index 0000000..46a4176
--- /dev/null
+++ b/mockito-updated/src/org/mockito/MockitoDebugger.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+/**
+ * @deprecated - please use {@link MockingDetails#printInvocations()}.
+ */
+@Deprecated
+public interface MockitoDebugger {
+
+ /**
+ * @deprecated - please use {@link MockingDetails#printInvocations()}.
+ */
+ @Deprecated
+ String printInvocations(Object ... mocks);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/MockitoFramework.java b/mockito-updated/src/org/mockito/MockitoFramework.java
new file mode 100644
index 0000000..1004f50
--- /dev/null
+++ b/mockito-updated/src/org/mockito/MockitoFramework.java
@@ -0,0 +1,56 @@
+package org.mockito;
+
+import org.mockito.listeners.MockitoListener;
+
+/**
+ * Mockito framework settings and lifecycle listeners, for advanced users or for integrating with other frameworks.
+ * <p>
+ * To get <code>MockitoFramework</code> instance use {@link Mockito#framework()}.
+ * <p>
+ * For more info on listeners see {@link #addListener(MockitoListener)}.
+ *
+ * @since 2.1.0
+ */
+@Incubating
+public interface MockitoFramework {
+
+ /**
+ * Adds listener to Mockito.
+ * For a list of supported listeners, see the interfaces that extend {@link MockitoListener}.
+ * <p>
+ * Listeners can be useful for engs that extend Mockito framework.
+ * They are used in the implementation of unused stubbings warnings ({@link org.mockito.quality.MockitoHint}).
+ * <p>
+ * Make sure you remove the listener when the job is complete, see {@link #removeListener(MockitoListener)}.
+ * Currently the listeners list is thread local so you need to remove listener from the same thread otherwise
+ * remove is ineffectual.
+ * In typical scenarios, it is not a problem, because adding & removing listeners typically happens in the same thread.
+ * <p>
+ * For usage examples, see Mockito codebase.
+ * If you have ideas and feature requests about Mockito listeners API
+ * we are very happy to hear about it via our issue tracker or mailing list.
+ *
+ * <pre class="code"><code class="java">
+ * Mockito.framework().addListener(myListener);
+ * </code></pre>
+ *
+ * @param listener to add
+ */
+ @Incubating
+ void addListener(MockitoListener listener);
+
+ /**
+ * When you add listener using {@link #addListener(MockitoListener)} make sure to remove it.
+ * Currently the listeners list is thread local so you need to remove listener from the same thread otherwise
+ * remove is ineffectual.
+ * In typical scenarios, it is not a problem, because adding & removing listeners typically happens in the same thread.
+ * <p>
+ * For usage examples, see Mockito codebase.
+ * If you have ideas and feature requests about Mockito listeners API
+ * we are very happy to hear about it via our issue tracker or mailing list.
+ *
+ * @param listener to remove
+ */
+ @Incubating
+ void removeListener(MockitoListener listener);
+}
diff --git a/mockito-updated/src/org/mockito/Spy.java b/mockito-updated/src/org/mockito/Spy.java
new file mode 100644
index 0000000..2af3439
--- /dev/null
+++ b/mockito-updated/src/org/mockito/Spy.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+/**
+ * Allows shorthand wrapping of field instances in an spy object.
+ *
+ * <p>
+ * Example:
+ *
+ * <pre class="code"><code class="java">
+ * public class Test{
+ * //Instance for spying is created by calling constructor explicitly:
+ * @Spy Foo spyOnFoo = new Foo("argument");
+ * //Instance for spying is created by mockito via reflection (only default constructors supported):
+ * @Spy Bar spyOnBar;
+ * @Before
+ * public void init(){
+ * MockitoAnnotations.initMocks(this);
+ * }
+ * ...
+ * }
+ * </code></pre>
+ * <p>
+ * Same as doing:
+ *
+ * <pre class="code"><code class="java">
+ * Foo spyOnFoo = Mockito.spy(new Foo("argument"));
+ * Bar spyOnBar = Mockito.spy(new Bar());
+ * </code></pre>
+ *
+ * <p>
+ * <strong>A field annotated with @Spy can be initialized explicitly at declaration point.
+ * Alternatively, if you don't provide the instance Mockito will try to find zero argument constructor (even private)
+ * and create an instance for you.
+ * <u>But Mockito cannot instantiate inner classes, local classes, abstract classes and interfaces.</u></strong>
+ *
+ * For example this class can be instantiated by Mockito :
+ * <pre class="code"><code class="java">public class Bar {
+ * private Bar() {}
+ * public Bar(String publicConstructorWithOneArg) {}
+ * }</code></pre>
+ * </p>
+ *
+ * <h4>Important gotcha on spying real objects!</h4>
+ * <ol>
+ * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.
+ * Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>
+ * family of methods for stubbing. Example:
+ *
+ * <pre class="code"><code class="java">
+ * List list = new LinkedList();
+ * List spy = spy(list);
+ *
+ * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
+ * when(spy.get(0)).thenReturn("foo");
+ *
+ * //You have to use doReturn() for stubbing
+ * doReturn("foo").when(spy).get(0);
+ * </code></pre>
+ * </li>
+ *
+ * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.
+ * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction
+ * and their effect on real instance state.
+ * The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,
+ * you won't see any effects on the real instance.</li>
+ *
+ * <li>Watch out for final methods.
+ * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.
+ * Also you won't be able to verify those method as well.
+ * </li>
+ * </ol>
+ *
+ * <p>
+ * <strong>One last warning :</strong> if you call <code>MockitoAnnotations.initMocks(this)</code> in a
+ * super class <strong>constructor</strong> then this will not work. It is because fields
+ * in subclass are only instantiated after super class constructor has returned.
+ * It's better to use @Before.
+ * <strong>Instead</strong> you can also put initMocks() in your JUnit runner (@RunWith) or use the built-in
+ * {@link org.mockito.runners.MockitoJUnitRunner}.
+ * </p>
+ *
+ * <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.
+ * It may troublesome for code that rely on the spy to have these annotations.</p>
+ *
+ * @see Mockito#spy(Object)
+ * @see Mock
+ * @see InjectMocks
+ * @see MockitoAnnotations#initMocks(Object)
+ * @see org.mockito.runners.MockitoJUnitRunner
+ * @since 1.8.3
+ */
+@Retention(RUNTIME)
+@Target(FIELD)
+@Documented
+public @interface Spy { }
diff --git a/mockito-updated/src/org/mockito/configuration/AnnotationEngine.java b/mockito-updated/src/org/mockito/configuration/AnnotationEngine.java
new file mode 100644
index 0000000..6ee4930
--- /dev/null
+++ b/mockito-updated/src/org/mockito/configuration/AnnotationEngine.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.configuration;
+
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Configures mock creation logic behind @Mock, @Captor and @Spy annotations
+ * <p>
+ * If you are interested then see implementations or source code of {@link MockitoAnnotations#initMocks(Object)}
+ */
+public interface AnnotationEngine {
+
+ /**
+ * Allows extending the interface to perform action on specific fields on the test class.
+ * <p>
+ * See the implementation of this method to figure out what is it for.
+ *
+ * @param clazz Class where to extract field information, check implementation for details
+ * @param testInstance Test instance
+ */
+ void process(Class<?> clazz, Object testInstance);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/configuration/DefaultMockitoConfiguration.java b/mockito-updated/src/org/mockito/configuration/DefaultMockitoConfiguration.java
new file mode 100644
index 0000000..ce5714d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/configuration/DefaultMockitoConfiguration.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.configuration;
+
+import org.mockito.internal.configuration.InjectingAnnotationEngine;
+import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
+import org.mockito.stubbing.Answer;
+
+/**
+ * DefaultConfiguration of Mockito framework
+ * <p>
+ * Currently it doesn't have many configuration options but it will probably change if future.
+ * <p>
+ * See javadocs for {@link IMockitoConfiguration} on info how to configure Mockito
+ */
+public class DefaultMockitoConfiguration implements IMockitoConfiguration {
+
+ public Answer<Object> getDefaultAnswer() {
+ return new ReturnsEmptyValues();
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.IMockitoConfiguration#getAnnotationEngine()
+ */
+ public AnnotationEngine getAnnotationEngine() {
+ return new InjectingAnnotationEngine();
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.configuration.IMockitoConfiguration#cleansStackTrace()
+ */
+ public boolean cleansStackTrace() {
+ return true;
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.configuration.IMockitoConfiguration#enableClassCache()
+ */
+ public boolean enableClassCache() {
+ return true;
+ }
+
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/configuration/IMockitoConfiguration.java b/mockito-updated/src/org/mockito/configuration/IMockitoConfiguration.java
new file mode 100644
index 0000000..cebd25f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/configuration/IMockitoConfiguration.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+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,
+ * 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.
+ * <p>
+ * 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.
+ * <p>
+ * <b>org.mockito.configuration.MockitoConfiguration</b> must implement IMockitoConfiguration or extend {@link DefaultMockitoConfiguration}
+ * <p>
+ * Mockito will store single instance of org.mockito.configuration.MockitoConfiguration per thread (using ThreadLocal).
+ * 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
+ */
+public interface IMockitoConfiguration {
+
+ /**
+ * Allows configuring the default answers of unstubbed invocations
+ * <p>
+ * See javadoc for {@link IMockitoConfiguration}
+ */
+ Answer<Object> getDefaultAnswer();
+
+ /**
+ * Configures annotations for mocks
+ * <p>
+ * See javadoc for {@link IMockitoConfiguration}
+ */
+ AnnotationEngine getAnnotationEngine();
+
+ /**
+ * This should be turned on unless you're a Mockito developer and you wish
+ * to have verbose (read: messy) stack traces that only few understand (eg:
+ * Mockito developers)
+ * <p>
+ * See javadoc for {@link IMockitoConfiguration}
+ *
+ * @return if Mockito should clean stack traces
+ */
+ boolean cleansStackTrace();
+
+ /**
+ * Allow objenesis to cache classes. If you're in an environment where classes
+ * are dynamically reloaded, you can disable this to avoid classcast exceptions.
+ */
+ boolean enableClassCache();
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/configuration/package.html b/mockito-updated/src/org/mockito/configuration/package.html
new file mode 100644
index 0000000..b4bec23
--- /dev/null
+++ b/mockito-updated/src/org/mockito/configuration/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Mockito configuration utilities
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/base/MockitoAssertionError.java b/mockito-updated/src/org/mockito/exceptions/base/MockitoAssertionError.java
new file mode 100644
index 0000000..893fd25
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/base/MockitoAssertionError.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.base;
+
+import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
+
+
+
+public class MockitoAssertionError extends AssertionError {
+
+ private static final long serialVersionUID = 1L;
+ private final StackTraceElement[] unfilteredStackTrace;
+
+ public MockitoAssertionError(String message) {
+ super(message);
+
+ unfilteredStackTrace = getStackTrace();
+
+ ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
+ filter.filter(this);
+ }
+
+ /**
+ * Creates a copy of the given assertion error with the custom failure message prepended.
+ * @param error The assertion error to copy
+ * @param message The custom message to prepend
+ * @since 2.1.0
+ */
+ public MockitoAssertionError(MockitoAssertionError error, String message) {
+ super(message + "\n" + error.getMessage());
+ super.setStackTrace(error.getStackTrace());
+ unfilteredStackTrace = error.getUnfilteredStackTrace();
+ }
+
+ public StackTraceElement[] getUnfilteredStackTrace() {
+ return unfilteredStackTrace;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/base/MockitoException.java b/mockito-updated/src/org/mockito/exceptions/base/MockitoException.java
new file mode 100644
index 0000000..3aa4362
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/base/MockitoException.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.base;
+
+import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
+
+
+/**
+ * Raised by mockito to emit an error either due to Mockito, or due to the User.
+ *
+ * <p>
+ * The stack trace is filtered from mockito calls if you are using {@link #getStackTrace()}.
+ * For debugging purpose though you can still access the full stacktrace using {@link #getUnfilteredStackTrace()}.
+ * However note that other calls related to the stackTrace will refer to the filter stacktrace.
+ * </p>
+ *
+ */
+public class MockitoException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ private StackTraceElement[] unfilteredStackTrace;
+
+ // TODO lazy filtered stacktrace initialization
+ public MockitoException(String message, Throwable t) {
+ super(message, t);
+ filterStackTrace();
+ }
+
+ public MockitoException(String message) {
+ super(message);
+ filterStackTrace();
+ }
+
+ private void filterStackTrace() {
+ unfilteredStackTrace = getStackTrace();
+
+ ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
+ filter.filter(this);
+ }
+
+ public StackTraceElement[] getUnfilteredStackTrace() {
+ return unfilteredStackTrace;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/base/MockitoSerializationIssue.java b/mockito-updated/src/org/mockito/exceptions/base/MockitoSerializationIssue.java
new file mode 100644
index 0000000..458b56d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/base/MockitoSerializationIssue.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.base;
+
+import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
+
+import java.io.ObjectStreamException;
+
+/**
+ * Raised by mockito to emit an error either due to Mockito, or due to the User.
+ *
+ * <p>
+ * The stack trace is filtered from mockito calls if you are using {@link #getStackTrace()}.
+ * For debugging purpose though you can still access the full stacktrace using {@link #getUnfilteredStackTrace()}.
+ * However note that other calls related to the stackTrace will refer to the filter stacktrace.
+ * </p>
+ *
+ * @since 1.10.0
+ */
+public class MockitoSerializationIssue extends ObjectStreamException {
+
+ private StackTraceElement[] unfilteredStackTrace;
+
+ public MockitoSerializationIssue(String message, Exception cause) {
+ super(message);
+ initCause(cause);
+ filterStackTrace();
+ }
+
+ private void filterStackTrace() {
+ unfilteredStackTrace = super.getStackTrace();
+
+ ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
+ filter.filter(this);
+ }
+
+ public StackTraceElement[] getUnfilteredStackTrace() {
+ return unfilteredStackTrace;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/base/package.html b/mockito-updated/src/org/mockito/exceptions/base/package.html
new file mode 100644
index 0000000..4f07e45
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/base/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Base classes for exceptions and errors, stack trace filtering/removing logic.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/CannotStubVoidMethodWithReturnValue.java b/mockito-updated/src/org/mockito/exceptions/misusing/CannotStubVoidMethodWithReturnValue.java
new file mode 100644
index 0000000..710f1e1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/CannotStubVoidMethodWithReturnValue.java
@@ -0,0 +1,9 @@
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class CannotStubVoidMethodWithReturnValue extends MockitoException {
+ public CannotStubVoidMethodWithReturnValue(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/CannotVerifyStubOnlyMock.java b/mockito-updated/src/org/mockito/exceptions/misusing/CannotVerifyStubOnlyMock.java
new file mode 100644
index 0000000..2c8a656
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/CannotVerifyStubOnlyMock.java
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class CannotVerifyStubOnlyMock extends MockitoException {
+
+ public CannotVerifyStubOnlyMock(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/FriendlyReminderException.java b/mockito-updated/src/org/mockito/exceptions/misusing/FriendlyReminderException.java
new file mode 100644
index 0000000..1201890
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/FriendlyReminderException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class FriendlyReminderException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public FriendlyReminderException(String message) {
+ super(message);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/InvalidUseOfMatchersException.java b/mockito-updated/src/org/mockito/exceptions/misusing/InvalidUseOfMatchersException.java
new file mode 100644
index 0000000..64623a3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/InvalidUseOfMatchersException.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class InvalidUseOfMatchersException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public InvalidUseOfMatchersException(String message) {
+ super(message);
+ }
+
+ public InvalidUseOfMatchersException() {
+ super("");
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/MissingMethodInvocationException.java b/mockito-updated/src/org/mockito/exceptions/misusing/MissingMethodInvocationException.java
new file mode 100644
index 0000000..ae77fb0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/MissingMethodInvocationException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class MissingMethodInvocationException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public MissingMethodInvocationException(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/MockitoConfigurationException.java b/mockito-updated/src/org/mockito/exceptions/misusing/MockitoConfigurationException.java
new file mode 100644
index 0000000..39a776d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/MockitoConfigurationException.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class MockitoConfigurationException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public MockitoConfigurationException(String message) {
+ super(message);
+ }
+
+ public MockitoConfigurationException(String message, Exception cause) {
+ super(message, cause);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/NotAMockException.java b/mockito-updated/src/org/mockito/exceptions/misusing/NotAMockException.java
new file mode 100644
index 0000000..d4fb917
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/NotAMockException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class NotAMockException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public NotAMockException(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/NullInsteadOfMockException.java b/mockito-updated/src/org/mockito/exceptions/misusing/NullInsteadOfMockException.java
new file mode 100644
index 0000000..5225f7c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/NullInsteadOfMockException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class NullInsteadOfMockException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public NullInsteadOfMockException(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/UnfinishedStubbingException.java b/mockito-updated/src/org/mockito/exceptions/misusing/UnfinishedStubbingException.java
new file mode 100644
index 0000000..3085161
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/UnfinishedStubbingException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class UnfinishedStubbingException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public UnfinishedStubbingException(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/UnfinishedVerificationException.java b/mockito-updated/src/org/mockito/exceptions/misusing/UnfinishedVerificationException.java
new file mode 100644
index 0000000..3d06840
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/UnfinishedVerificationException.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class UnfinishedVerificationException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public UnfinishedVerificationException(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java b/mockito-updated/src/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java
new file mode 100644
index 0000000..9895fbd
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/UnnecessaryStubbingException.java
@@ -0,0 +1,31 @@
+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:
+ * <pre class="code"><code class="java">
+ * //code under test:
+ * ...
+ * String result = translator.translate("one")
+ * ...
+ *
+ * //test:
+ * ...
+ * when(translator.translate("one")).thenReturn("jeden"); // <- stubbing realized during code execution
+ * when(translator.translate("two")).thenReturn("dwa"); // <- stubbing never realized
+ * ...
+ * </pre>
+ * Notice that one of the stubbed methods were never realized in the code under test, during test execution.
+ * The stray stubbing might be an oversight of the developer, the artifact of copy-paste
+ * or the effect not understanding the test/code.
+ * Either way, the developer ends up with unnecessary test code.
+ * In order to keep the codebase clean & maintainable it is necessary to remove unnecessary code.
+ * Otherwise tests are harder to read and reason about.
+ * <p>
+ * To find out more about detecting unused stubbings see {@link org.mockito.quality.MockitoHint}.
+ */
+public class UnnecessaryStubbingException extends RuntimeException {
+ public UnnecessaryStubbingException(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/WrongTypeOfReturnValue.java b/mockito-updated/src/org/mockito/exceptions/misusing/WrongTypeOfReturnValue.java
new file mode 100644
index 0000000..5fa2e29
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/WrongTypeOfReturnValue.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.exceptions.misusing;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class WrongTypeOfReturnValue extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public WrongTypeOfReturnValue(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/misusing/package.html b/mockito-updated/src/org/mockito/exceptions/misusing/package.html
new file mode 100644
index 0000000..64bfbc5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/misusing/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Exceptions thrown when Mockito is misused.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/package.html b/mockito-updated/src/org/mockito/exceptions/package.html
new file mode 100644
index 0000000..a2e03c3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Exception messages, exception hierarchies.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/stacktrace/StackTraceCleaner.java b/mockito-updated/src/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
new file mode 100644
index 0000000..8e42913
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/stacktrace/StackTraceCleaner.java
@@ -0,0 +1,26 @@
+package org.mockito.exceptions.stacktrace;
+
+/**
+ * Decides if particular StackTraceElement is excluded from the human-readable stack trace output.
+ * 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}).
+ * <p>
+ * 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}.
+ *
+ */
+public interface StackTraceCleaner {
+
+ /**
+ * Decides if element is included.
+ *
+ * @param candidate element of the actual stack trace
+ * @return whether the element should be excluded from cleaned stack trace.
+ */
+ boolean isIn(StackTraceElement candidate);
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/stacktrace/package.html b/mockito-updated/src/org/mockito/exceptions/stacktrace/package.html
new file mode 100644
index 0000000..2251473
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/stacktrace/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Stack trace filtering / cleaning public APIs.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/ArgumentsAreDifferent.java b/mockito-updated/src/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
new file mode 100644
index 0000000..41d01bb
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/ArgumentsAreDifferent.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.util.RemoveFirstLine;
+
+public class ArgumentsAreDifferent extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public ArgumentsAreDifferent(String message) {
+ super(message);
+ }
+
+ @Override
+ public String toString() {
+ return new RemoveFirstLine().of(super.toString());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/NeverWantedButInvoked.java b/mockito-updated/src/org/mockito/exceptions/verification/NeverWantedButInvoked.java
new file mode 100644
index 0000000..e8e3ba9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/NeverWantedButInvoked.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+
+public class NeverWantedButInvoked extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public NeverWantedButInvoked(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/NoInteractionsWanted.java b/mockito-updated/src/org/mockito/exceptions/verification/NoInteractionsWanted.java
new file mode 100644
index 0000000..e1aafb5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/NoInteractionsWanted.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+
+/**
+ * No interactions wanted. See exception's cause for location of undesired invocation.
+ */
+public class NoInteractionsWanted extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public NoInteractionsWanted(String message) {
+ super(message);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/SmartNullPointerException.java b/mockito-updated/src/org/mockito/exceptions/verification/SmartNullPointerException.java
new file mode 100644
index 0000000..539224c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/SmartNullPointerException.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class SmartNullPointerException extends MockitoException {
+
+ private static final long serialVersionUID = 1L;
+
+ public SmartNullPointerException(String message) {
+ super(message);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/TooLittleActualInvocations.java b/mockito-updated/src/org/mockito/exceptions/verification/TooLittleActualInvocations.java
new file mode 100644
index 0000000..01af460
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/TooLittleActualInvocations.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+
+public class TooLittleActualInvocations extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public TooLittleActualInvocations(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/TooManyActualInvocations.java b/mockito-updated/src/org/mockito/exceptions/verification/TooManyActualInvocations.java
new file mode 100644
index 0000000..e29ec7a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/TooManyActualInvocations.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+
+public class TooManyActualInvocations extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public TooManyActualInvocations(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/VerificationInOrderFailure.java b/mockito-updated/src/org/mockito/exceptions/verification/VerificationInOrderFailure.java
new file mode 100644
index 0000000..d27c30c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/VerificationInOrderFailure.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+
+public class VerificationInOrderFailure extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public VerificationInOrderFailure(String message) {
+ super(message);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/WantedButNotInvoked.java b/mockito-updated/src/org/mockito/exceptions/verification/WantedButNotInvoked.java
new file mode 100644
index 0000000..007d70c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/WantedButNotInvoked.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.util.RemoveFirstLine;
+
+public class WantedButNotInvoked extends MockitoAssertionError {
+
+ private static final long serialVersionUID = 1L;
+
+ public WantedButNotInvoked(String message) {
+ super(message);
+ }
+
+ @Override
+ public String toString() {
+ return new RemoveFirstLine().of(super.toString());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java b/mockito-updated/src/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java
new file mode 100644
index 0000000..cf1321f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/junit/ArgumentsAreDifferent.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.exceptions.verification.junit;
+
+import junit.framework.ComparisonFailure;
+import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
+import org.mockito.internal.util.RemoveFirstLine;
+
+
+public class ArgumentsAreDifferent extends ComparisonFailure {
+
+ 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 new RemoveFirstLine().of(super.toString());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/junit/package.html b/mockito-updated/src/org/mockito/exceptions/verification/junit/package.html
new file mode 100644
index 0000000..4b1a32e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/junit/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+JUnit integration to provide better support for junit runners in IDEs.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/exceptions/verification/package.html b/mockito-updated/src/org/mockito/exceptions/verification/package.html
new file mode 100644
index 0000000..6471a75
--- /dev/null
+++ b/mockito-updated/src/org/mockito/exceptions/verification/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Verification errors.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/hamcrest/MockitoHamcrest.java b/mockito-updated/src/org/mockito/hamcrest/MockitoHamcrest.java
new file mode 100644
index 0000000..e8e7a0e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/hamcrest/MockitoHamcrest.java
@@ -0,0 +1,176 @@
+package org.mockito.hamcrest;
+
+import org.hamcrest.Matcher;
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.hamcrest.HamcrestArgumentMatcher;
+
+import static org.mockito.internal.hamcrest.MatcherGenericTypeExtractor.genericTypeOfMatcher;
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+import static org.mockito.internal.util.Primitives.defaultValue;
+
+/**
+ * Allows matching arguments with hamcrest matchers.
+ * <b>Requires</b> <a href="http://hamcrest.org/JavaHamcrest/">hamcrest</a> on classpath,
+ * Mockito <b>does not</b> depend on hamcrest!
+ * Note the <b>NullPointerException</b> auto-unboxing caveat described below.
+ * <p/>
+ * Before implementing or reusing an existing hamcrest matcher please read
+ * how to deal with sophisticated argument matching in {@link ArgumentMatcher}.
+ * <p/>
+ * Mockito 2.1.0 was decoupled from Hamcrest to avoid version incompatibilities
+ * that have impacted our users in past. Mockito offers a dedicated API to match arguments
+ * via {@link ArgumentMatcher}.
+ * Hamcrest integration is provided so that users can take advantage of existing Hamcrest matchers.
+ * <p/>
+ * Example:
+ * <pre>
+ * import static org.mockito.hamcrest.MockitoHamcrest.argThat;
+ *
+ * //stubbing
+ * when(mock.giveMe(argThat(new MyHamcrestMatcher())));
+ *
+ * //verification
+ * verify(mock).giveMe(argThat(new MyHamcrestMatcher()));
+ * </pre>
+ * <b>NullPointerException</b> auto-unboxing caveat.
+ * In rare cases when matching primitive parameter types you <b>*must*</b> use relevant intThat(), floatThat(), etc. method.
+ * This way you will avoid <code>NullPointerException</code> during auto-unboxing.
+ * Due to how java works we don't really have a clean way of detecting this scenario and protecting the user from this problem.
+ * Hopefully, the javadoc describes the problem and solution well.
+ * If you have an idea how to fix the problem, let us know via the mailing list or the issue tracker.
+ *
+ * @since 2.1.0
+ */
+public class MockitoHamcrest {
+
+ /**
+ * Allows matching arguments with hamcrest matchers.
+ * <p/>
+ * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>null</code> or default value for primitive (0, false, etc.)
+ * @since 2.1.0
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T argThat(Matcher<T> matcher) {
+ reportMatcher(matcher);
+ return (T) defaultValue(genericTypeOfMatcher(matcher.getClass()));
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>char</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>char</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static char charThat(Matcher<Character> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>boolean</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>boolean</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>false</code>.
+ */
+ public static boolean booleanThat(Matcher<Boolean> matcher) {
+ reportMatcher(matcher);
+ return false;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>byte</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>byte</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static byte byteThat(Matcher<Byte> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>short</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>short</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static short shortThat(Matcher<Short> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>int</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>int</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static int intThat(Matcher<Integer> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>long</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>long</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static long longThat(Matcher<Long> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>float</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>float</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static float floatThat(Matcher<Float> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ /**
+ * Enables integrating hamcrest matchers that match primitive <code>double</code> arguments.
+ * Note that {@link #argThat} will not work with primitive <code>double</code> matchers due to <code>NullPointerException</code> auto-unboxing caveat.
+ * <p/>
+ * * See examples in javadoc for {@link MockitoHamcrest} class
+ *
+ * @param matcher decides whether argument matches
+ * @return <code>0</code>.
+ */
+ public static double doubleThat(Matcher<Double> matcher) {
+ reportMatcher(matcher);
+ return 0;
+ }
+
+ private static <T> void reportMatcher(Matcher<T> matcher) {
+ mockingProgress().getArgumentMatcherStorage().reportMatcher(new HamcrestArgumentMatcher<T>(matcher));
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/InOrderImpl.java b/mockito-updated/src/org/mockito/internal/InOrderImpl.java
new file mode 100644
index 0000000..ce37b23
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/InOrderImpl.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal;
+
+import org.mockito.InOrder;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.verification.InOrderContextImpl;
+import org.mockito.internal.verification.InOrderWrapper;
+import org.mockito.internal.verification.VerificationModeFactory;
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.internal.verification.api.VerificationInOrderMode;
+import org.mockito.invocation.Invocation;
+import org.mockito.verification.VerificationMode;
+import org.mockito.internal.verification.VerificationWrapper;
+import org.mockito.internal.verification.VerificationWrapperInOrderWrapper;
+
+import static org.mockito.internal.exceptions.Reporter.inOrderRequiresFamiliarMock;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Allows verifying in order. This class should not be exposed, hence default access.
+ */
+public class InOrderImpl implements InOrder, InOrderContext {
+
+ private final MockitoCore mockitoCore = new MockitoCore();
+ private final List<Object> mocksToBeVerifiedInOrder = new LinkedList<Object>();
+ private final InOrderContext inOrderContext = new InOrderContextImpl();
+
+ public List<Object> getMocksToBeVerifiedInOrder() {
+ return mocksToBeVerifiedInOrder;
+ }
+
+ public InOrderImpl(List<? extends Object> mocksToBeVerifiedInOrder) {
+ this.mocksToBeVerifiedInOrder.addAll(mocksToBeVerifiedInOrder);
+ }
+
+ public <T> T verify(T mock) {
+ return this.verify(mock, VerificationModeFactory.times(1));
+ }
+
+ public <T> T verify(T mock, VerificationMode mode) {
+ if (!mocksToBeVerifiedInOrder.contains(mock)) {
+ throw inOrderRequiresFamiliarMock();
+ }
+ if (mode instanceof VerificationWrapper) {
+ return mockitoCore.verify(mock, new VerificationWrapperInOrderWrapper((VerificationWrapper) mode, this));
+ } else if (!(mode instanceof VerificationInOrderMode)) {
+ throw new MockitoException(mode.getClass().getSimpleName() + " is not implemented to work with InOrder");
+ }
+ return mockitoCore.verify(mock, new InOrderWrapper((VerificationInOrderMode) mode, this));
+ }
+
+ public boolean isVerified(Invocation i) {
+ return inOrderContext.isVerified(i);
+ }
+
+ public void markVerified(Invocation i) {
+ inOrderContext.markVerified(i);
+ }
+
+ public void verifyNoMoreInteractions() {
+ mockitoCore.verifyNoMoreInteractionsInOrder(mocksToBeVerifiedInOrder, this);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/InternalMockHandler.java b/mockito-updated/src/org/mockito/internal/InternalMockHandler.java
new file mode 100644
index 0000000..d27333c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/InternalMockHandler.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal;
+
+import java.util.List;
+
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.invocation.MockHandler;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.Answer;
+
+public interface InternalMockHandler<T> extends MockHandler {
+
+ MockCreationSettings<T> getMockSettings();
+
+ void setAnswersForStubbing(List<Answer<?>> answers);
+
+ InvocationContainer getInvocationContainer();
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/MockitoCore.java b/mockito-updated/src/org/mockito/internal/MockitoCore.java
new file mode 100644
index 0000000..771f6ed
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/MockitoCore.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal;
+
+import static org.mockito.internal.exceptions.Reporter.missingMethodInvocation;
+import static org.mockito.internal.exceptions.Reporter.mocksHaveToBePassedToVerifyNoMoreInteractions;
+import static org.mockito.internal.exceptions.Reporter.mocksHaveToBePassedWhenCreatingInOrder;
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedToVerify;
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedToVerifyNoMoreInteractions;
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedWhenCreatingInOrder;
+import static org.mockito.internal.exceptions.Reporter.nullPassedToVerify;
+import static org.mockito.internal.exceptions.Reporter.nullPassedToVerifyNoMoreInteractions;
+import static org.mockito.internal.exceptions.Reporter.nullPassedWhenCreatingInOrder;
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+import static org.mockito.internal.util.MockUtil.createMock;
+import static org.mockito.internal.util.MockUtil.getMockHandler;
+import static org.mockito.internal.util.MockUtil.isMock;
+import static org.mockito.internal.util.MockUtil.resetMock;
+import static org.mockito.internal.util.MockUtil.typeMockabilityOf;
+import static org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions;
+
+import java.util.Arrays;
+import java.util.List;
+import org.mockito.InOrder;
+import org.mockito.MockSettings;
+import org.mockito.MockingDetails;
+import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockito.internal.creation.MockSettingsImpl;
+import org.mockito.internal.invocation.finder.VerifiableInvocationsFinder;
+import org.mockito.internal.progress.MockingProgress;
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.internal.stubbing.OngoingStubbingImpl;
+import org.mockito.internal.stubbing.StubberImpl;
+import org.mockito.internal.util.DefaultMockingDetails;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.internal.verification.MockAwareVerificationMode;
+import org.mockito.internal.verification.VerificationDataImpl;
+import org.mockito.internal.verification.VerificationModeFactory;
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.internal.verification.api.VerificationDataInOrder;
+import org.mockito.internal.verification.api.VerificationDataInOrderImpl;
+import org.mockito.invocation.Invocation;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.OngoingStubbing;
+import org.mockito.stubbing.Stubber;
+import org.mockito.verification.VerificationMode;
+
+@SuppressWarnings("unchecked")
+public class MockitoCore {
+
+ public boolean isTypeMockable(Class<?> typeToMock) {
+ return typeMockabilityOf(typeToMock).mockable();
+ }
+
+ public <T> T mock(Class<T> typeToMock, MockSettings settings) {
+ if (!MockSettingsImpl.class.isInstance(settings)) {
+ throw new IllegalArgumentException("Unexpected implementation of '" + settings.getClass().getCanonicalName() + "'\n" + "At the moment, you cannot provide your own implementations of that class.");
+ }
+ MockSettingsImpl impl = MockSettingsImpl.class.cast(settings);
+ MockCreationSettings<T> creationSettings = impl.confirm(typeToMock);
+ T mock = createMock(creationSettings);
+ mockingProgress().mockingStarted(mock, creationSettings);
+ return mock;
+ }
+
+ public <T> OngoingStubbing<T> when(T methodCall) {
+ MockingProgress mockingProgress = mockingProgress();
+ mockingProgress.stubbingStarted();
+ @SuppressWarnings("unchecked")
+ OngoingStubbing<T> stubbing = (OngoingStubbing<T>) mockingProgress.pullOngoingStubbing();
+ if (stubbing == null) {
+ mockingProgress.reset();
+ throw missingMethodInvocation();
+ }
+ return stubbing;
+ }
+
+ public <T> T verify(T mock, VerificationMode mode) {
+ if (mock == null) {
+ throw nullPassedToVerify();
+ }
+ if (!isMock(mock)) {
+ throw notAMockPassedToVerify(mock.getClass());
+ }
+ MockingProgress mockingProgress = mockingProgress();
+ VerificationMode actualMode = mockingProgress.maybeVerifyLazily(mode);
+ mockingProgress.verificationStarted(new MockAwareVerificationMode(mock, actualMode));
+ return mock;
+ }
+
+ public <T> void reset(T... mocks) {
+ MockingProgress mockingProgress = mockingProgress();
+ mockingProgress.validateState();
+ mockingProgress.reset();
+ mockingProgress.resetOngoingStubbing();
+
+ for (T m : mocks) {
+ resetMock(m);
+ }
+ }
+
+ public <T> void clearInvocations(T... mocks) {
+ MockingProgress mockingProgress = mockingProgress();
+ mockingProgress.validateState();
+ mockingProgress.reset();
+ mockingProgress.resetOngoingStubbing();
+
+ for (T m : mocks) {
+ getMockHandler(m).getInvocationContainer().clearInvocations();
+ }
+ }
+
+ public void verifyNoMoreInteractions(Object... mocks) {
+ assertMocksNotEmpty(mocks);
+ mockingProgress().validateState();
+ for (Object mock : mocks) {
+ try {
+ if (mock == null) {
+ throw nullPassedToVerifyNoMoreInteractions();
+ }
+ InvocationContainer invocations = getMockHandler(mock).getInvocationContainer();
+ VerificationDataImpl data = new VerificationDataImpl(invocations, null);
+ noMoreInteractions().verify(data);
+ } catch (NotAMockException e) {
+ throw notAMockPassedToVerifyNoMoreInteractions();
+ }
+ }
+ }
+
+ public void verifyNoMoreInteractionsInOrder(List<Object> mocks, InOrderContext inOrderContext) {
+ mockingProgress().validateState();
+ VerificationDataInOrder data = new VerificationDataInOrderImpl(inOrderContext, VerifiableInvocationsFinder.find(mocks), null);
+ VerificationModeFactory.noMoreInteractions().verifyInOrder(data);
+ }
+
+ private void assertMocksNotEmpty(Object[] mocks) {
+ if (mocks == null || mocks.length == 0) {
+ throw mocksHaveToBePassedToVerifyNoMoreInteractions();
+ }
+ }
+
+ public InOrder inOrder(Object... mocks) {
+ if (mocks == null || mocks.length == 0) {
+ throw mocksHaveToBePassedWhenCreatingInOrder();
+ }
+ for (Object mock : mocks) {
+ if (mock == null) {
+ throw nullPassedWhenCreatingInOrder();
+ }
+ if (!isMock(mock)) {
+ throw notAMockPassedWhenCreatingInOrder();
+ }
+ }
+ return new InOrderImpl(Arrays.asList(mocks));
+ }
+
+ public Stubber stubber() {
+ MockingProgress mockingProgress = mockingProgress();
+ mockingProgress.stubbingStarted();
+ mockingProgress.resetOngoingStubbing();
+ return new StubberImpl();
+ }
+
+ public void validateMockitoUsage() {
+ mockingProgress().validateState();
+ }
+
+ /**
+ * For testing purposes only. Is not the part of main API.
+ *
+ * @return last invocation
+ */
+ public Invocation getLastInvocation() {
+ OngoingStubbingImpl ongoingStubbing = ((OngoingStubbingImpl) mockingProgress().pullOngoingStubbing());
+ List<Invocation> allInvocations = ongoingStubbing.getRegisteredInvocations();
+ return allInvocations.get(allInvocations.size() - 1);
+ }
+
+ public Object[] ignoreStubs(Object... mocks) {
+ for (Object m : mocks) {
+ InvocationContainer invocationContainer = getMockHandler(m).getInvocationContainer();
+ List<Invocation> ins = invocationContainer.getInvocations();
+ for (Invocation in : ins) {
+ if (in.stubInfo() != null) {
+ in.ignoreForVerification();
+ }
+ }
+ }
+ return mocks;
+ }
+
+ public MockingDetails mockingDetails(Object toInspect) {
+ return new DefaultMockingDetails(toInspect);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/CaptorAnnotationProcessor.java b/mockito-updated/src/org/mockito/internal/configuration/CaptorAnnotationProcessor.java
new file mode 100644
index 0000000..0ccbfbc
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/CaptorAnnotationProcessor.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.reflection.GenericMaster;
+
+import java.lang.reflect.Field;
+
+/**
+ * Instantiate {@link ArgumentCaptor} a field annotated by @Captor.
+ */
+public class CaptorAnnotationProcessor implements FieldAnnotationProcessor<Captor> {
+ public Object process(Captor annotation, Field field) {
+ Class<?> type = field.getType();
+ if (!ArgumentCaptor.class.isAssignableFrom(type)) {
+ throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '"
+ + field.getName() + "' has wrong type\n"
+ + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.");
+ }
+ Class<?> cls = new GenericMaster().getGenericType(field);
+ return ArgumentCaptor.forClass(cls);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/ClassPathLoader.java b/mockito-updated/src/org/mockito/internal/configuration/ClassPathLoader.java
new file mode 100644
index 0000000..67b2040
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/ClassPathLoader.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.mockito.configuration.IMockitoConfiguration;
+import org.mockito.exceptions.misusing.MockitoConfigurationException;
+import org.mockito.plugins.MockMaker;
+
+
+/**
+ * Loads configuration or extension points available in the classpath.
+ *
+ * <p>
+ * <ul>
+ * <li>
+ * Can load the mockito configuration. The user who want to provide his own mockito configuration
+ * should write the class <code>org.mockito.configuration.MockitoConfiguration</code> that implements
+ * {@link IMockitoConfiguration}. For example :
+ * <pre class="code"><code class="java">
+ * package org.mockito.configuration;
+ *
+ * //...
+ *
+ * public class MockitoConfiguration implements IMockitoConfiguration {
+ * boolean enableClassCache() { return false; }
+ *
+ * // ...
+ * }
+ * </code></pre>
+ * </li>
+ * <li>
+ * Can load available mockito extensions. Currently Mockito only have one extension point the
+ * {@link MockMaker}. This extension point allows a user to provide his own bytecode engine to build mocks.
+ * <br>Suppose you wrote an extension to create mocks with some <em>Awesome</em> library, in order to tell
+ * Mockito to use it you need to put in your classpath
+ * <ol style="list-style-type: lower-alpha">
+ * <li>The implementation itself, for example <code>org.awesome.mockito.AwesomeMockMaker</code>.</li>
+ * <li>A file named <code>org.mockito.plugins.MockMaker</code> in a folder named
+ * <code>mockito-extensions</code>, the content of this file need to have <strong>one</strong> line with
+ * the qualified name <code>org.awesome.mockito.AwesomeMockMaker</code>.</li>
+ * </ol>
+ * </li>
+ * </ul>
+ * </p>
+ */
+public class ClassPathLoader {
+
+ public static final String MOCKITO_CONFIGURATION_CLASS_NAME = "org.mockito.configuration.MockitoConfiguration";
+
+ /**
+ * @return configuration loaded from classpath or null
+ */
+ @SuppressWarnings({"unchecked"})
+ public IMockitoConfiguration loadConfiguration() {
+ // Trying to get config from classpath
+ Class<?> configClass;
+ try {
+ configClass = Class.forName(MOCKITO_CONFIGURATION_CLASS_NAME);
+ } catch (ClassNotFoundException e) {
+ //that's ok, it means there is no global config, using default one.
+ return null;
+ }
+
+ try {
+ return (IMockitoConfiguration) configClass.newInstance();
+ } catch (ClassCastException e) {
+ throw new MockitoConfigurationException("MockitoConfiguration class must implement " + IMockitoConfiguration.class.getName() + " interface.", e);
+ } catch (Exception e) {
+ throw new MockitoConfigurationException("Unable to instantiate " + MOCKITO_CONFIGURATION_CLASS_NAME +" class. Does it have a safe, no-arg constructor?", e);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/DefaultAnnotationEngine.java b/mockito-updated/src/org/mockito/internal/configuration/DefaultAnnotationEngine.java
new file mode 100644
index 0000000..de21fab
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/DefaultAnnotationEngine.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.configuration.AnnotationEngine;
+import org.mockito.exceptions.base.MockitoException;
+
+import static org.mockito.internal.exceptions.Reporter.moreThanOneAnnotationNotAllowed;
+import static org.mockito.internal.util.reflection.FieldSetter.setField;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Initializes fields annotated with @{@link org.mockito.Mock} or @{@link org.mockito.Captor}.
+ *
+ * <p>
+ * The {@link #process(Class, Object)} method implementation <strong>does not</strong> process super classes!
+ *
+ * @see MockitoAnnotations
+ */
+@SuppressWarnings("unchecked")
+public class DefaultAnnotationEngine implements AnnotationEngine {
+ private final Map<Class<? extends Annotation>, FieldAnnotationProcessor<?>> annotationProcessorMap = new HashMap<Class<? extends Annotation>, FieldAnnotationProcessor<?>>();
+
+ public DefaultAnnotationEngine() {
+ registerAnnotationProcessor(Mock.class, new MockAnnotationProcessor());
+ registerAnnotationProcessor(Captor.class, new CaptorAnnotationProcessor());
+ }
+
+ private Object createMockFor(Annotation annotation, Field field) {
+ return forAnnotation(annotation).process(annotation, field);
+ }
+
+ private <A extends Annotation> FieldAnnotationProcessor<A> forAnnotation(A annotation) {
+ if (annotationProcessorMap.containsKey(annotation.annotationType())) {
+ return (FieldAnnotationProcessor<A>) annotationProcessorMap.get(annotation.annotationType());
+ }
+ return new FieldAnnotationProcessor<A>() {
+ public Object process(A annotation, Field field) {
+ return null;
+ }
+ };
+ }
+
+ private <A extends Annotation> void registerAnnotationProcessor(Class<A> annotationClass, FieldAnnotationProcessor<A> fieldAnnotationProcessor) {
+ annotationProcessorMap.put(annotationClass, fieldAnnotationProcessor);
+ }
+
+ @Override
+ public void process(Class<?> clazz, Object testInstance) {
+ Field[] fields = clazz.getDeclaredFields();
+ for (Field field : fields) {
+ boolean alreadyAssigned = false;
+ for(Annotation annotation : field.getAnnotations()) {
+ Object mock = createMockFor(annotation, field);
+ if (mock != null) {
+ throwIfAlreadyAssigned(field, alreadyAssigned);
+ alreadyAssigned = true;
+ try {
+ setField(testInstance, field,mock);
+ } catch (Exception e) {
+ throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
+ + annotation, e);
+ }
+ }
+ }
+ }
+ }
+
+ void throwIfAlreadyAssigned(Field field, boolean alreadyAssigned) {
+ if (alreadyAssigned) {
+ throw moreThanOneAnnotationNotAllowed(field.getName());
+ }
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/DefaultInjectionEngine.java b/mockito-updated/src/org/mockito/internal/configuration/DefaultInjectionEngine.java
new file mode 100644
index 0000000..e5e98a1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/DefaultInjectionEngine.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import java.lang.reflect.Field;
+import java.util.Set;
+
+import org.mockito.internal.configuration.injection.MockInjection;
+
+/**
+ * Inject mock/spies dependencies for fields annotated with @InjectMocks
+ * <p/>
+ * See {@link org.mockito.MockitoAnnotations}
+ */
+public class DefaultInjectionEngine {
+
+ public void injectMocksOnFields(Set<Field> needingInjection, Set<Object> mocks, Object testClassInstance) {
+ MockInjection.onFields(needingInjection, testClassInstance)
+ .withMocks(mocks)
+ .tryConstructorInjection()
+ .tryPropertyOrFieldInjection()
+ .handleSpyAnnotation()
+ .apply();
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/FieldAnnotationProcessor.java b/mockito-updated/src/org/mockito/internal/configuration/FieldAnnotationProcessor.java
new file mode 100644
index 0000000..28f70b4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/FieldAnnotationProcessor.java
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+
+/**
+ * Simple annotation processor interface.
+ */
+public interface FieldAnnotationProcessor<A extends Annotation> {
+ Object process(A annotation, Field field);
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/GlobalConfiguration.java b/mockito-updated/src/org/mockito/internal/configuration/GlobalConfiguration.java
new file mode 100644
index 0000000..c8a94e8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/GlobalConfiguration.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.mockito.configuration.AnnotationEngine;
+import org.mockito.configuration.DefaultMockitoConfiguration;
+import org.mockito.configuration.IMockitoConfiguration;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+
+/**
+ * Thread-safe wrapper on user-defined org.mockito.configuration.MockitoConfiguration implementation
+ */
+public class GlobalConfiguration implements IMockitoConfiguration, Serializable {
+ private static final long serialVersionUID = -2860353062105505938L;
+
+ private static final ThreadLocal<IMockitoConfiguration> GLOBAL_CONFIGURATION = new ThreadLocal<IMockitoConfiguration>();
+
+ //back door for testing
+ IMockitoConfiguration getIt() {
+ return GLOBAL_CONFIGURATION.get();
+ }
+
+ public GlobalConfiguration() {
+ //Configuration should be loaded only once but I cannot really test it
+ if (GLOBAL_CONFIGURATION.get() == null) {
+ GLOBAL_CONFIGURATION.set(createConfig());
+ }
+ }
+
+ private IMockitoConfiguration createConfig() {
+ IMockitoConfiguration defaultConfiguration = new DefaultMockitoConfiguration();
+ IMockitoConfiguration config = new ClassPathLoader().loadConfiguration();
+ if (config != null) {
+ return config;
+ } else {
+ return defaultConfiguration;
+ }
+ }
+
+ public static void validate() {
+ new GlobalConfiguration();
+ }
+
+ public AnnotationEngine getAnnotationEngine() {
+ return GLOBAL_CONFIGURATION.get().getAnnotationEngine();
+ }
+
+ public boolean cleansStackTrace() {
+ return GLOBAL_CONFIGURATION.get().cleansStackTrace();
+ }
+
+ public boolean enableClassCache() {
+ return GLOBAL_CONFIGURATION.get().enableClassCache();
+ }
+
+ public Answer<Object> getDefaultAnswer() {
+ return GLOBAL_CONFIGURATION.get().getDefaultAnswer();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/configuration/InjectingAnnotationEngine.java b/mockito-updated/src/org/mockito/internal/configuration/InjectingAnnotationEngine.java
new file mode 100644
index 0000000..4dc1eb8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/InjectingAnnotationEngine.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.mockito.*;
+import org.mockito.configuration.AnnotationEngine;
+import org.mockito.internal.configuration.injection.scanner.InjectMocksScanner;
+import org.mockito.internal.configuration.injection.scanner.MockScanner;
+
+import java.lang.reflect.Field;
+import java.util.HashSet;
+import java.util.Set;
+
+import static org.mockito.internal.util.collections.Sets.newMockSafeHashSet;
+
+/**
+ * See {@link MockitoAnnotations}
+ */
+@SuppressWarnings({"deprecation", "unchecked"})
+public class InjectingAnnotationEngine implements AnnotationEngine {
+ private final AnnotationEngine delegate = new DefaultAnnotationEngine();
+ private final AnnotationEngine spyAnnotationEngine = new SpyAnnotationEngine();
+
+ /**
+ * Process the fields of the test instance and create Mocks, Spies, Captors and inject them on fields
+ * annotated @InjectMocks.
+ *
+ * <p>
+ * This code process the test class and the super classes.
+ * <ol>
+ * <li>First create Mocks, Spies, Captors.</li>
+ * <li>Then try to inject them.</li>
+ * </ol>
+ *
+ * @param clazz Not used
+ * @param testInstance The instance of the test, should not be null.
+ *
+ * @see org.mockito.configuration.AnnotationEngine#process(Class, Object)
+ */
+ 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();
+ }
+ }
+
+ private void processIndependentAnnotations(final Class<?> clazz, final Object testInstance) {
+ Class<?> classContext = clazz;
+ while (classContext != Object.class) {
+ //this will create @Mocks, @Captors, etc:
+ delegate.process(classContext, testInstance);
+ //this will create @Spies:
+ spyAnnotationEngine.process(classContext, testInstance);
+
+ classContext = classContext.getSuperclass();
+ }
+ }
+
+
+ /**
+ * Initializes mock/spies dependencies for objects annotated with
+ * @InjectMocks for given testClassInstance.
+ * <p>
+ * See examples in javadoc for {@link MockitoAnnotations} class.
+ *
+ * @param testClassInstance
+ * Test class, usually <code>this</code>
+ */
+ 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);
+ }
+
+ protected void onInjection(Object testClassInstance, Class<?> clazz, Set<Field> mockDependentFields, Set<Object> mocks) {
+
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/MockAnnotationProcessor.java b/mockito-updated/src/org/mockito/internal/configuration/MockAnnotationProcessor.java
new file mode 100644
index 0000000..40cb992
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/MockAnnotationProcessor.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import org.mockito.Mock;
+import org.mockito.MockSettings;
+import org.mockito.Mockito;
+
+import java.lang.reflect.Field;
+
+/**
+ * Instantiates a mock on a field annotated by {@link Mock}
+ */
+public class MockAnnotationProcessor implements FieldAnnotationProcessor<Mock> {
+ public Object process(Mock annotation, Field field) {
+ MockSettings mockSettings = Mockito.withSettings();
+ if (annotation.extraInterfaces().length > 0) { // never null
+ mockSettings.extraInterfaces(annotation.extraInterfaces());
+ }
+ if ("".equals(annotation.name())) {
+ mockSettings.name(field.getName());
+ } else {
+ mockSettings.name(annotation.name());
+ }
+ if(annotation.serializable()){
+ mockSettings.serializable();
+ }
+
+ // see @Mock answer default value
+ mockSettings.defaultAnswer(annotation.answer());
+ return Mockito.mock(field.getType(), mockSettings);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/SpyAnnotationEngine.java b/mockito-updated/src/org/mockito/internal/configuration/SpyAnnotationEngine.java
new file mode 100644
index 0000000..b23ac79
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/SpyAnnotationEngine.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration;
+
+import static org.mockito.Mockito.withSettings;
+import static org.mockito.internal.exceptions.Reporter.unsupportedCombinationOfAnnotations;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Modifier;
+
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockSettings;
+import org.mockito.Mockito;
+import org.mockito.Spy;
+import org.mockito.configuration.AnnotationEngine;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.MockUtil;
+
+/**
+ * Process fields annotated with @Spy.
+ * <p/>
+ * <p>
+ * Will try transform the field in a spy as with <code>Mockito.spy()</code>.
+ * </p>
+ * <p/>
+ * <p>
+ * If the field is not initialized, will try to initialize it, with a no-arg constructor.
+ * </p>
+ * <p/>
+ * <p>
+ * If the field is also annotated with the <strong>compatible</strong> @InjectMocks then the field will be ignored,
+ * The injection engine will handle this specific case.
+ * </p>
+ * <p/>
+ * <p>This engine will fail, if the field is also annotated with incompatible Mockito annotations.
+ */
+@SuppressWarnings({"unchecked"})
+public class SpyAnnotationEngine implements AnnotationEngine {
+
+ @Override
+ public void process(Class<?> context, Object testInstance) {
+ Field[] fields = context.getDeclaredFields();
+ for (Field field : fields) {
+ if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) {
+ assertNoIncompatibleAnnotations(Spy.class, field, Mock.class, Captor.class);
+ field.setAccessible(true);
+ 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.
+ Mockito.reset(instance);
+ } else if (instance != null) {
+ field.set(testInstance, Mockito.mock(instance.getClass(), withSettings()
+ .spiedInstance(instance)
+ .defaultAnswer(Mockito.CALLS_REAL_METHODS)
+ .name(field.getName())));
+ } else {
+ field.set(testInstance, newSpyInstance(testInstance, field));
+ }
+ } catch (Exception e) {
+ throw new MockitoException("Unable to initialize @Spy annotated field '" + field.getName() + "'.\n" + e.getMessage(), e);
+ }
+ }
+ }
+ }
+
+ 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 static Object newSpyInstance(Object testInstance, Field field)
+ throws InstantiationException, IllegalAccessException, InvocationTargetException {
+ MockSettings settings = withSettings()
+ .defaultAnswer(Mockito.CALLS_REAL_METHODS)
+ .name(field.getName());
+ Class<?> type = field.getType();
+ if (type.isInterface()) {
+ return Mockito.mock(type, settings.useConstructor());
+ }
+ if (!Modifier.isStatic(type.getModifiers())) {
+ Class<?> enclosing = type.getEnclosingClass();
+ if (enclosing != null) {
+ if (!enclosing.isInstance(testInstance)) {
+ throw new MockitoException("@Spy annotation can only initialize inner classes declared in the test. "
+ + "Inner class: '" + type.getSimpleName() + "', "
+ + "outer class: '" + enclosing.getSimpleName() + "'.");
+ }
+ return Mockito.mock(type, settings
+ .useConstructor()
+ .outerInstance(testInstance));
+ }
+ }
+ Constructor<?> constructor;
+ try {
+ constructor = type.getDeclaredConstructor();
+ } catch (NoSuchMethodException e) {
+ throw new MockitoException("Please ensure that the type '" + type.getSimpleName() + "' has 0-arg constructor.");
+ }
+
+ if (Modifier.isPrivate(constructor.getModifiers())) {
+ constructor.setAccessible(true);
+ return Mockito.mock(type, settings
+ .spiedInstance(constructor.newInstance()));
+ } else {
+ return Mockito.mock(type, settings.useConstructor());
+ }
+ }
+
+ //TODO duplicated elsewhere
+ private 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(), annotation.getClass().getSimpleName());
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/ConstructorInjection.java b/mockito-updated/src/org/mockito/internal/configuration/injection/ConstructorInjection.java
new file mode 100644
index 0000000..ffece34
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/ConstructorInjection.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.configuration.injection;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.reflection.FieldInitializationReport;
+import org.mockito.internal.util.reflection.FieldInitializer;
+import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver;
+
+import static org.mockito.internal.exceptions.Reporter.fieldInitialisationThrewException;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Injection strategy based on constructor.
+ *
+ * <p>
+ * The strategy will search for the constructor with most parameters
+ * and try to resolve mocks by type.
+ * </p>
+ *
+ * <blockquote>
+ * TODO on missing mock type, shall it abandon or create "noname" mocks.
+ * TODO and what if the arg type is not mockable.
+ * </blockquote>
+ *
+ * <p>
+ * For now the algorithm tries to create anonymous mocks if an argument type is missing.
+ * If not possible the algorithm abandon resolution.
+ * </p>
+ */
+public class ConstructorInjection extends MockInjectionStrategy {
+
+ public ConstructorInjection() { }
+
+ public boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {
+ try {
+ SimpleArgumentResolver simpleArgumentResolver = new SimpleArgumentResolver(mockCandidates);
+ FieldInitializationReport report = new FieldInitializer(fieldOwner, field, simpleArgumentResolver).initialize();
+
+ return report.fieldWasInitializedUsingContructorArgs();
+ } catch (MockitoException e) {
+ if(e.getCause() instanceof InvocationTargetException) {
+ Throwable realCause = e.getCause().getCause();
+ throw fieldInitialisationThrewException(field, realCause);
+ }
+ // other causes should be fine
+ return false;
+ }
+
+ }
+
+ /**
+ * Returns mocks that match the argument type, if not possible assigns null.
+ */
+ static class SimpleArgumentResolver implements ConstructorArgumentResolver {
+ final Set<Object> objects;
+
+ public SimpleArgumentResolver(Set<Object> objects) {
+ this.objects = objects;
+ }
+
+ public Object[] resolveTypeInstances(Class<?>... argTypes) {
+ List<Object> argumentInstances = new ArrayList<Object>(argTypes.length);
+ for (Class<?> argType : argTypes) {
+ argumentInstances.add(objectThatIsAssignableFrom(argType));
+ }
+ return argumentInstances.toArray();
+ }
+
+ private Object objectThatIsAssignableFrom(Class<?> argType) {
+ for (Object object : objects) {
+ if(argType.isAssignableFrom(object.getClass())) return object;
+ }
+ return null;
+ }
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/MockInjection.java b/mockito-updated/src/org/mockito/internal/configuration/injection/MockInjection.java
new file mode 100644
index 0000000..ef5312c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/MockInjection.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.configuration.injection;
+
+import java.lang.reflect.Field;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import static org.mockito.internal.util.Checks.checkItemsNotNull;
+import static org.mockito.internal.util.Checks.checkNotNull;
+import static org.mockito.internal.util.collections.Sets.newMockSafeHashSet;
+
+/**
+ * Internal injection configuration utility.
+ *
+ * <p>
+ * Allow the user of this class to configure the way the injection of mocks will happen.
+ * </p>
+ *
+ */
+public class MockInjection {
+
+ /**
+ * Create a new configuration setup for a field
+ *
+ *
+ * @param field Field needing mock injection
+ * @param ofInstance Instance owning the <code>field</code>
+ * @return New configuration builder
+ */
+ public static OngoingMockInjection onField(Field field, Object ofInstance) {
+ return new OngoingMockInjection(field, ofInstance);
+ }
+
+ /**
+ * Create a new configuration setup for fields
+ *
+ *
+ * @param fields Fields needing mock injection
+ * @param ofInstance Instance owning the <code>field</code>
+ * @return New configuration builder
+ */
+ public static OngoingMockInjection onFields(Set<Field> fields, Object ofInstance) {
+ return new OngoingMockInjection(fields, ofInstance);
+ }
+
+ /**
+ * Ongoing configuration of the mock injector.
+ */
+ public static class OngoingMockInjection {
+ private final Set<Field> fields = new HashSet<Field>();
+ private final Set<Object> mocks = newMockSafeHashSet();
+ private final Object fieldOwner;
+ private final MockInjectionStrategy injectionStrategies = MockInjectionStrategy.nop();
+ private final MockInjectionStrategy postInjectionStrategies = MockInjectionStrategy.nop();
+
+ private OngoingMockInjection(Field field, Object fieldOwner) {
+ this(Collections.singleton(field), fieldOwner);
+ }
+
+ private OngoingMockInjection(Set<Field> fields, Object fieldOwner) {
+ this.fieldOwner = checkNotNull(fieldOwner, "fieldOwner");
+ this.fields.addAll(checkItemsNotNull(fields, "fields"));
+ }
+
+ public OngoingMockInjection withMocks(Set<Object> mocks) {
+ this.mocks.addAll(checkNotNull(mocks, "mocks"));
+ return this;
+ }
+
+ public OngoingMockInjection tryConstructorInjection() {
+ injectionStrategies.thenTry(new ConstructorInjection());
+ return this;
+ }
+
+ public OngoingMockInjection tryPropertyOrFieldInjection() {
+ injectionStrategies.thenTry(new PropertyAndSetterInjection());
+ return this;
+ }
+
+ public OngoingMockInjection handleSpyAnnotation() {
+ postInjectionStrategies.thenTry(new SpyOnInjectedFieldsHandler());
+ return this;
+ }
+
+ public void apply() {
+ for (Field field : fields) {
+ injectionStrategies.process(field, fieldOwner, mocks);
+ postInjectionStrategies.process(field, fieldOwner, mocks);
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/MockInjectionStrategy.java b/mockito-updated/src/org/mockito/internal/configuration/injection/MockInjectionStrategy.java
new file mode 100644
index 0000000..5b56eb0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/MockInjectionStrategy.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.configuration.injection;
+
+import java.lang.reflect.Field;
+import java.util.Set;
+
+/**
+ * Injector strategy contract
+ */
+public abstract class MockInjectionStrategy {
+
+ /**
+ * NOP Strategy that will always try the next strategy.
+ */
+ public static MockInjectionStrategy nop() {
+ return new MockInjectionStrategy() {
+ protected boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {
+ return false;
+ }
+ };
+ }
+
+
+ private MockInjectionStrategy nextStrategy;
+
+ /**
+ * Enqueue next injection strategy.
+ *
+ * <p>
+ * The implementation should take care of the actual calling if required.
+ * </p>
+ *
+ * @param strategy Queued strategy.
+ * @return The passed strategy instance to allow chaining.
+ */
+ public MockInjectionStrategy thenTry(MockInjectionStrategy strategy) {
+ if(nextStrategy != null) {
+ nextStrategy.thenTry(strategy);
+ } else {
+ nextStrategy = strategy;
+ }
+ return strategy;
+ }
+
+ /**
+ * Actually inject mockCandidates on field.
+ *
+ * <p>
+ * Actual algorithm is defined in the implementations of {@link #processInjection(Field, Object, Set)}.
+ * However if injection occurred successfully, the process should return <code>true</code>,
+ * and <code>false</code> otherwise.
+ * </p>
+ *
+ * <p>
+ * The code takes care of calling the next strategy if available and if of course if required
+ * </p>
+ *
+ * @param onField Field needing injection.
+ * @param fieldOwnedBy The owning instance of the field.
+ * @param mockCandidates A set of mock candidate, that might be injected.
+ * @return <code>true</code> if successful, <code>false</code> otherwise.
+ */
+ public boolean process(Field onField, Object fieldOwnedBy, Set<Object> mockCandidates) {
+ if(processInjection(onField, fieldOwnedBy, mockCandidates)) {
+ return true;
+ }
+ return relayProcessToNextStrategy(onField, fieldOwnedBy, mockCandidates);
+ }
+
+ /**
+ * Process actual injection.
+ *
+ * <p>
+ * Don't call this method directly, instead call {@link #process(Field, Object, Set)}
+ * </p>
+ *
+ * @param field Field needing injection
+ * @param fieldOwner Field owner instance.
+ * @param mockCandidates Pool of mocks to inject.
+ * @return <code>true</code> if injection occurred, <code>false</code> otherwise
+ */
+ protected abstract boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates);
+
+ private boolean relayProcessToNextStrategy(Field field, Object fieldOwner, Set<Object> mockCandidates) {
+ return nextStrategy != null && nextStrategy.process(field, fieldOwner, mockCandidates);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java b/mockito-updated/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
new file mode 100644
index 0000000..5b52a71
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/PropertyAndSetterInjection.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.configuration.injection;
+
+import static org.mockito.internal.exceptions.Reporter.cannotInitializeForInjectMocksAnnotation;
+import static org.mockito.internal.exceptions.Reporter.fieldInitialisationThrewException;
+import static org.mockito.internal.util.collections.Sets.newMockSafeHashSet;
+import static org.mockito.internal.util.reflection.SuperTypesLastSorter.sortSuperTypesLast;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.configuration.injection.filter.MockCandidateFilter;
+import org.mockito.internal.configuration.injection.filter.NameBasedCandidateFilter;
+import org.mockito.internal.configuration.injection.filter.TerminalMockCandidateFilter;
+import org.mockito.internal.configuration.injection.filter.TypeBasedCandidateFilter;
+import org.mockito.internal.util.collections.ListUtil;
+import org.mockito.internal.util.reflection.FieldInitializationReport;
+import org.mockito.internal.util.reflection.FieldInitializer;
+import org.mockito.internal.util.reflection.SuperTypesLastSorter;
+
+/**
+ * Inject mocks using first setters then fields, if no setters available.
+ *
+ * <p>
+ * <u>Algorithm :<br></u>
+ * for each field annotated by @InjectMocks
+ * <ul>
+ * <li>initialize field annotated by @InjectMocks
+ * <li>for each fields of a class in @InjectMocks type hierarchy
+ * <ul>
+ * <li>make a copy of mock candidates
+ * <li>order fields from sub-type to super-type, then by field name
+ * <li>for the list of fields in a class try two passes of :
+ * <ul>
+ * <li>find mock candidate by type
+ * <li>if more than <b>*one*</b> candidate find mock candidate on name
+ * <li>if one mock candidate then
+ * <ul>
+ * <li>set mock by property setter if possible
+ * <li>else set mock by field injection
+ * </ul>
+ * <li>remove mock from mocks copy (mocks are just injected once in a class)
+ * <li>remove injected field from list of class fields
+ * </ul>
+ * <li>else don't fail, user will then provide dependencies
+ * </ul>
+ * </ul>
+ * </p>
+ *
+ * <p>
+ * <u>Note:</u> If the field needing injection is not initialized, the strategy tries
+ * to create one using a no-arg constructor of the field type.
+ * </p>
+ */
+public class PropertyAndSetterInjection extends MockInjectionStrategy {
+
+ private final MockCandidateFilter mockCandidateFilter =
+ new TypeBasedCandidateFilter(
+ new NameBasedCandidateFilter(
+ new TerminalMockCandidateFilter()));
+
+ private final ListUtil.Filter<Field> notFinalOrStatic = new ListUtil.Filter<Field>() {
+ public boolean isOut(Field object) {
+ return Modifier.isFinal(object.getModifiers()) || Modifier.isStatic(object.getModifiers());
+ }
+ };
+
+
+ public boolean processInjection(Field injectMocksField, Object injectMocksFieldOwner, Set<Object> mockCandidates) {
+ FieldInitializationReport report = initializeInjectMocksField(injectMocksField, injectMocksFieldOwner);
+
+ // for each field in the class hierarchy
+ boolean injectionOccurred = false;
+ Class<?> fieldClass = report.fieldClass();
+ Object fieldInstanceNeedingInjection = report.fieldInstance();
+ while (fieldClass != Object.class) {
+ injectionOccurred |= injectMockCandidates(fieldClass, fieldInstanceNeedingInjection, newMockSafeHashSet(mockCandidates));
+ fieldClass = fieldClass.getSuperclass();
+ }
+ return injectionOccurred;
+ }
+
+ private FieldInitializationReport initializeInjectMocksField(Field field, Object fieldOwner) {
+ try {
+ return new FieldInitializer(fieldOwner, field).initialize();
+ } catch (MockitoException e) {
+ if(e.getCause() instanceof InvocationTargetException) {
+ Throwable realCause = e.getCause().getCause();
+ throw fieldInitialisationThrewException(field, realCause);
+ }
+ throw cannotInitializeForInjectMocksAnnotation(field.getName(),e.getMessage());
+ }
+ }
+
+
+ private boolean injectMockCandidates(Class<?> awaitingInjectionClazz, Object injectee, Set<Object> mocks) {
+ boolean injectionOccurred;
+ List<Field> orderedCandidateInjecteeFields = orderedInstanceFieldsFrom(awaitingInjectionClazz);
+ // pass 1
+ injectionOccurred = injectMockCandidatesOnFields(mocks, injectee, false, orderedCandidateInjecteeFields);
+ // pass 2
+ injectionOccurred |= injectMockCandidatesOnFields(mocks, injectee, injectionOccurred, orderedCandidateInjecteeFields);
+ return injectionOccurred;
+ }
+
+ private boolean injectMockCandidatesOnFields(Set<Object> mocks,
+ Object injectee,
+ boolean injectionOccurred,
+ List<Field> orderedCandidateInjecteeFields) {
+ for (Iterator<Field> it = orderedCandidateInjecteeFields.iterator(); it.hasNext(); ) {
+ Field candidateField = it.next();
+ Object injected = mockCandidateFilter.filterCandidate(mocks, candidateField, orderedCandidateInjecteeFields, injectee)
+ .thenInject();
+ if (injected != null) {
+ injectionOccurred |= true;
+ mocks.remove(injected);
+ it.remove();
+ }
+ }
+ return injectionOccurred;
+ }
+
+ private List<Field> orderedInstanceFieldsFrom(Class<?> awaitingInjectionClazz) {
+ List<Field> declaredFields = Arrays.asList(awaitingInjectionClazz.getDeclaredFields());
+ declaredFields = ListUtil.filter(declaredFields, notFinalOrStatic);
+
+ return sortSuperTypesLast(declaredFields);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java b/mockito-updated/src/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java
new file mode 100644
index 0000000..3dc0351
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.configuration.injection;
+
+import org.mockito.Mockito;
+import org.mockito.Spy;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.internal.util.reflection.FieldReader;
+
+import java.lang.reflect.Field;
+import java.util.Set;
+
+import static org.mockito.Mockito.withSettings;
+import static org.mockito.internal.util.reflection.FieldSetter.setField;
+
+/**
+ * Handler for field annotated with @InjectMocks and @Spy.
+ *
+ * <p>
+ * The handler assumes that field initialization AND injection already happened.
+ * So if the field is still null, then nothing will happen there.
+ * </p>
+ */
+public class SpyOnInjectedFieldsHandler extends MockInjectionStrategy {
+
+ @Override
+ protected boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {
+ FieldReader fieldReader = new FieldReader(fieldOwner, field);
+
+ // TODO refoctor : code duplicated in SpyAnnotationEngine
+ if(!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) {
+ try {
+ Object instance = fieldReader.read();
+ if (MockUtil.isMock(instance)) {
+ // A. instance has been spied earlier
+ // B. protect against multiple use of MockitoAnnotations.initMocks()
+ Mockito.reset(instance);
+ } else {
+ Object mock = Mockito.mock(instance.getClass(), withSettings()
+ .spiedInstance(instance)
+ .defaultAnswer(Mockito.CALLS_REAL_METHODS)
+ .name(field.getName()));
+ setField(fieldOwner, field, mock);
+ }
+ } catch (Exception e) {
+ throw new MockitoException("Problems initiating spied field " + field.getName(), e);
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
new file mode 100644
index 0000000..454d3be
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/MockCandidateFilter.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.filter;
+
+import java.lang.reflect.Field;
+import java.util.Collection;
+import java.util.List;
+
+public interface MockCandidateFilter {
+ OngoingInjector filterCandidate(
+ Collection<Object> mocks,
+ Field candidateFieldToBeInjected,
+ List<Field> allRemainingCandidateFields,
+ Object injectee
+ );
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
new file mode 100644
index 0000000..dc50e9d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.filter;
+
+import static org.mockito.internal.util.MockUtil.getMockName;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+public class NameBasedCandidateFilter implements MockCandidateFilter {
+ private final MockCandidateFilter next;
+
+ public NameBasedCandidateFilter(MockCandidateFilter next) {
+ this.next = next;
+ }
+
+ public OngoingInjector filterCandidate(final Collection<Object> mocks,
+ final Field candidateFieldToBeInjected,
+ final List<Field> allRemainingCandidateFields,
+ final Object injectee) {
+ if (mocks.size() == 1
+ && anotherCandidateMatchesMockName(mocks, candidateFieldToBeInjected, allRemainingCandidateFields)) {
+ return OngoingInjector.nop;
+ }
+
+ return next.filterCandidate(tooMany(mocks) ? selectMatchingName(mocks, candidateFieldToBeInjected) : mocks,
+ candidateFieldToBeInjected,
+ allRemainingCandidateFields,
+ injectee);
+ }
+
+ private boolean tooMany(Collection<Object> mocks) {
+ return mocks.size() > 1;
+ }
+
+ private List<Object> selectMatchingName(Collection<Object> mocks, Field candidateFieldToBeInjected) {
+ List<Object> mockNameMatches = new ArrayList<Object>();
+ for (Object mock : mocks) {
+ if (candidateFieldToBeInjected.getName().equals(getMockName(mock).toString())) {
+ mockNameMatches.add(mock);
+ }
+ }
+ return mockNameMatches;
+ }
+
+ /*
+ * In this case we have to check whether we have conflicting naming
+ * fields. E.g. 2 fields of the same type, but we have to make sure
+ * we match on the correct name.
+ *
+ * Therefore we have to go through all other fields and make sure
+ * whenever we find a field that does match its name with the mock
+ * name, we should take that field instead.
+ */
+ private boolean anotherCandidateMatchesMockName(final Collection<Object> mocks,
+ final Field candidateFieldToBeInjected,
+ final List<Field> allRemainingCandidateFields) {
+ String mockName = getMockName(mocks.iterator().next()).toString();
+
+ for (Field otherCandidateField : allRemainingCandidateFields) {
+ if (!otherCandidateField.equals(candidateFieldToBeInjected)
+ && otherCandidateField.getType().equals(candidateFieldToBeInjected.getType())
+ && otherCandidateField.getName().equals(mockName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/filter/OngoingInjector.java b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/OngoingInjector.java
new file mode 100644
index 0000000..4550e1f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/OngoingInjector.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.filter;
+
+/**
+ * Allow the ongoing injection of a mock candidate.
+ */
+public interface OngoingInjector {
+
+ /**
+ * Inject the mock.
+ *
+ * <p>
+ * Please check the actual implementation.
+ * </p>
+ *
+ * @return the mock that was injected, <code>null</code> otherwise.
+ */
+ Object thenInject();
+
+ /**
+ * Injector that will do nothing, and will return <code>null</code> as no mocks will be injected
+ */
+ OngoingInjector nop = new OngoingInjector() {
+ public Object thenInject() {
+ return null;
+ }
+ };
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java
new file mode 100644
index 0000000..3a66c7e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/TerminalMockCandidateFilter.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.filter;
+
+import org.mockito.internal.util.reflection.BeanPropertySetter;
+
+import java.lang.reflect.Field;
+import java.util.Collection;
+import java.util.List;
+
+import static org.mockito.internal.exceptions.Reporter.cannotInjectDependency;
+import static org.mockito.internal.util.reflection.FieldSetter.setField;
+
+/**
+ * This node returns an actual injecter which will be either :
+ *
+ * <ul>
+ * <li>an {@link OngoingInjector} that do nothing if a candidate couldn't be found</li>
+ * <li>an {@link OngoingInjector} that will try to inject the candidate trying first the property setter then if not possible try the field access</li>
+ * </ul>
+ */
+public class TerminalMockCandidateFilter implements MockCandidateFilter {
+ public OngoingInjector filterCandidate(final Collection<Object> mocks,
+ final Field candidateFieldToBeInjected,
+ final List<Field> allRemainingCandidateFields,
+ final Object injectee) {
+ if(mocks.size() == 1) {
+ final Object matchingMock = mocks.iterator().next();
+
+ return new OngoingInjector() {
+ public Object thenInject() {
+ try {
+ if (!new BeanPropertySetter(injectee, candidateFieldToBeInjected).set(matchingMock)) {
+ setField(injectee, candidateFieldToBeInjected,matchingMock);
+ }
+ } catch (RuntimeException e) {
+ throw cannotInjectDependency(candidateFieldToBeInjected, matchingMock, e);
+ }
+ return matchingMock;
+ }
+ };
+ }
+
+ return OngoingInjector.nop;
+
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
new file mode 100644
index 0000000..7284399
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/filter/TypeBasedCandidateFilter.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.filter;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+public class TypeBasedCandidateFilter implements MockCandidateFilter {
+
+ private final MockCandidateFilter next;
+
+ public TypeBasedCandidateFilter(MockCandidateFilter next) {
+ this.next = next;
+ }
+
+ public OngoingInjector filterCandidate(final Collection<Object> mocks,
+ final Field candidateFieldToBeInjected,
+ final List<Field> allRemainingCandidateFields,
+ final Object injectee) {
+ List<Object> mockTypeMatches = new ArrayList<Object>();
+ for (Object mock : mocks) {
+ if (candidateFieldToBeInjected.getType().isAssignableFrom(mock.getClass())) {
+ mockTypeMatches.add(mock);
+ }
+ }
+
+ return next.filterCandidate(mockTypeMatches, candidateFieldToBeInjected, allRemainingCandidateFields, injectee);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java b/mockito-updated/src/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java
new file mode 100644
index 0000000..57d5113
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/scanner/InjectMocksScanner.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.scanner;
+
+import org.mockito.Captor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+
+import static org.mockito.internal.exceptions.Reporter.unsupportedCombinationOfAnnotations;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Scan field for injection.
+ */
+public class InjectMocksScanner {
+ private final Class<?> clazz;
+
+ /**
+ * Create a new InjectMocksScanner for the given clazz on the given instance
+ *
+ * @param clazz Current class in the hierarchy of the test
+ */
+ public InjectMocksScanner(Class<?> clazz) {
+ this.clazz = clazz;
+ }
+
+
+ /**
+ * Add the fields annotated by @{@link InjectMocks}
+ *
+ * @param mockDependentFields Set of fields annotated by @{@link InjectMocks}
+ */
+ public void addTo(Set<Field> mockDependentFields) {
+ mockDependentFields.addAll(scan());
+ }
+
+ /**
+ * Scan fields annotated by @InjectMocks
+ *
+ * @return Fields that depends on Mock
+ */
+ @SuppressWarnings("unchecked")
+ private Set<Field> scan() {
+ Set<Field> mockDependentFields = new HashSet<Field>();
+ Field[] fields = clazz.getDeclaredFields();
+ for (Field field : fields) {
+ if (null != field.getAnnotation(InjectMocks.class)) {
+ assertNoAnnotations(field, Mock.class, Captor.class);
+ mockDependentFields.add(field);
+ }
+ }
+
+ return mockDependentFields;
+ }
+
+ private static void assertNoAnnotations(Field field, Class<? extends Annotation>... annotations) {
+ for (Class<? extends Annotation> annotation : annotations) {
+ if (field.isAnnotationPresent(annotation)) {
+ throw unsupportedCombinationOfAnnotations(annotation.getSimpleName(), InjectMocks.class.getSimpleName());
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/injection/scanner/MockScanner.java b/mockito-updated/src/org/mockito/internal/configuration/injection/scanner/MockScanner.java
new file mode 100644
index 0000000..f455ada
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/injection/scanner/MockScanner.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.configuration.injection.scanner;
+
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.internal.util.reflection.FieldReader;
+
+import java.lang.reflect.Field;
+import java.util.Set;
+
+import static org.mockito.internal.util.collections.Sets.newMockSafeHashSet;
+
+/**
+ * Scan mocks, and prepare them if needed.
+ */
+public class MockScanner {
+ private final Object instance;
+ private final Class<?> clazz;
+
+ /**
+ * Creates a MockScanner.
+ *
+ * @param instance The test instance
+ * @param clazz The class in the type hierarchy of this instance.
+ */
+ public MockScanner(Object instance, Class<?> clazz) {
+ this.instance = instance;
+ this.clazz = clazz;
+ }
+
+ /**
+ * Add the scanned and prepared mock instance to the given collection.
+ *
+ * <p>
+ * The preparation of mocks consists only in defining a MockName if not already set.
+ * </p>
+ *
+ * @param mocks Set of mocks
+ */
+ public void addPreparedMocks(Set<Object> mocks) {
+ mocks.addAll(scan());
+ }
+
+ /**
+ * Scan and prepare mocks for the given <code>testClassInstance</code> and <code>clazz</code> in the type hierarchy.
+ *
+ * @return A prepared set of mock
+ */
+ private Set<Object> scan() {
+ Set<Object> mocks = newMockSafeHashSet();
+ for (Field field : clazz.getDeclaredFields()) {
+ // mock or spies only
+ FieldReader fieldReader = new FieldReader(instance, field);
+
+ Object mockInstance = preparedMock(fieldReader.read(), field);
+ if (mockInstance != null) {
+ mocks.add(mockInstance);
+ }
+ }
+ return mocks;
+ }
+
+ private Object preparedMock(Object instance, Field field) {
+ if (isAnnotatedByMockOrSpy(field)) {
+ return instance;
+ }
+ if (isMockOrSpy(instance)) {
+ MockUtil.maybeRedefineMockName(instance, field.getName());
+ return instance;
+ }
+ return null;
+ }
+
+ private boolean isAnnotatedByMockOrSpy(Field field) {
+ return field.isAnnotationPresent(Spy.class) || field.isAnnotationPresent(Mock.class);
+ }
+
+ private boolean isMockOrSpy(Object instance) {
+ return MockUtil.isMock(instance)
+ || MockUtil.isSpy(instance);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/package.html b/mockito-updated/src/org/mockito/internal/configuration/package.html
new file mode 100644
index 0000000..5d4669a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Mockito configuration
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/configuration/plugins/DefaultPluginSwitch.java b/mockito-updated/src/org/mockito/internal/configuration/plugins/DefaultPluginSwitch.java
new file mode 100644
index 0000000..85c9490
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/plugins/DefaultPluginSwitch.java
@@ -0,0 +1,9 @@
+package org.mockito.internal.configuration.plugins;
+
+import org.mockito.plugins.PluginSwitch;
+
+class DefaultPluginSwitch implements PluginSwitch {
+ public boolean isEnabled(String pluginClassName) {
+ return true;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginFileReader.java b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginFileReader.java
new file mode 100644
index 0000000..7a149bf
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginFileReader.java
@@ -0,0 +1,26 @@
+package org.mockito.internal.configuration.plugins;
+
+import org.mockito.internal.util.io.IOUtil;
+
+import java.io.InputStream;
+
+class PluginFileReader {
+
+ String readPluginClass(InputStream input) {
+ for(String line: IOUtil.readLines(input)) {
+ String stripped = stripCommentAndWhitespace(line);
+ if (stripped.length() > 0) {
+ return stripped;
+ }
+ }
+ return null;
+ }
+
+ private static String stripCommentAndWhitespace(String line) {
+ int hash = line.indexOf('#');
+ if (hash != -1) {
+ line = line.substring(0, hash);
+ }
+ return line.trim();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginFinder.java b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginFinder.java
new file mode 100644
index 0000000..431c86e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginFinder.java
@@ -0,0 +1,41 @@
+package org.mockito.internal.configuration.plugins;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.io.IOUtil;
+import org.mockito.plugins.PluginSwitch;
+
+import java.io.InputStream;
+import java.net.URL;
+
+class PluginFinder {
+
+ private final PluginSwitch pluginSwitch;
+
+ public PluginFinder(PluginSwitch pluginSwitch) {
+ this.pluginSwitch = pluginSwitch;
+ }
+
+ String findPluginClass(Iterable<URL> resources) {
+ for (URL resource : resources) {
+ InputStream s = null;
+ try {
+ s = resource.openStream();
+ String pluginClassName = new PluginFileReader().readPluginClass(s);
+ if (pluginClassName == null) {
+ //For backwards compatibility
+ //If the resource does not have plugin class name we're ignoring it
+ continue;
+ }
+ if (!pluginSwitch.isEnabled(pluginClassName)) {
+ continue;
+ }
+ return pluginClassName;
+ } catch(Exception e) {
+ throw new MockitoException("Problems reading plugin implementation from: " + resource, e);
+ } finally {
+ IOUtil.closeQuietly(s);
+ }
+ }
+ return null;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginLoader.java b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginLoader.java
new file mode 100644
index 0000000..ddcd3ec
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginLoader.java
@@ -0,0 +1,86 @@
+package org.mockito.internal.configuration.plugins;
+
+import org.mockito.internal.util.collections.Iterables;
+import org.mockito.plugins.PluginSwitch;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+
+class PluginLoader {
+
+ private final PluginSwitch pluginSwitch;
+
+ private final Map<String, String> alias;
+
+ public PluginLoader(PluginSwitch pluginSwitch) {
+ this.pluginSwitch = pluginSwitch;
+ this.alias = new HashMap<String, String>();
+ }
+
+ /**
+ * Adds an alias for a class name to this plugin loader. Instead of the fully qualified type name,
+ * the alias can be used as a convenience name for a known plugin.
+ */
+ PluginLoader withAlias(String name, String type) {
+ alias.put(name, type);
+ return this;
+ }
+
+ /**
+ * Scans the classpath for given pluginType. If not found, default class is used.
+ */
+ <T> T loadPlugin(Class<T> pluginType, String defaultPluginClassName) {
+ T plugin = loadImpl(pluginType);
+ if (plugin != null) {
+ return plugin;
+ }
+
+ try {
+ // Default implementation. Use our own ClassLoader instead of the context
+ // ClassLoader, as the default implementation is assumed to be part of
+ // Mockito and may not be available via the context ClassLoader.
+ return pluginType.cast(Class.forName(defaultPluginClassName).newInstance());
+ } catch (Exception e) {
+ throw new IllegalStateException("Internal problem occurred, please report it. " +
+ "Mockito is unable to load the default implementation of class that is a part of Mockito distribution. " +
+ "Failed to load " + pluginType, e);
+ }
+ }
+
+ /**
+ * Equivalent to {@link java.util.ServiceLoader#load} but without requiring
+ * Java 6 / Android 2.3 (Gingerbread).
+ */
+ private <T> T loadImpl(Class<T> service) {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ if (loader == null) {
+ loader = ClassLoader.getSystemClassLoader();
+ }
+ Enumeration<URL> resources;
+ try {
+ resources = loader.getResources("mockito-extensions/" + service.getName());
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to load " + service, e);
+ }
+
+ try {
+ String foundPluginClass = new PluginFinder(pluginSwitch).findPluginClass(Iterables.toIterable(resources));
+ if (foundPluginClass != null) {
+ String aliasType = alias.get(foundPluginClass);
+ if (aliasType != null) {
+ foundPluginClass = aliasType;
+ }
+ Class<?> pluginClass = loader.loadClass(foundPluginClass);
+ Object plugin = pluginClass.newInstance();
+ return service.cast(plugin);
+ }
+ return null;
+ } catch (Exception e) {
+ throw new IllegalStateException(
+ "Failed to load " + service + " implementation declared in " + resources, e);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginRegistry.java b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginRegistry.java
new file mode 100644
index 0000000..3ecf980
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/plugins/PluginRegistry.java
@@ -0,0 +1,50 @@
+package org.mockito.internal.configuration.plugins;
+
+import org.mockito.plugins.InstantiatorProvider;
+import org.mockito.plugins.MockMaker;
+import org.mockito.plugins.PluginSwitch;
+import org.mockito.plugins.StackTraceCleanerProvider;
+
+class PluginRegistry {
+
+ private final PluginSwitch pluginSwitch = new PluginLoader(new DefaultPluginSwitch())
+ .loadPlugin(PluginSwitch.class, DefaultPluginSwitch.class.getName());
+
+ private final MockMaker mockMaker = new PluginLoader(pluginSwitch)
+ .withAlias("mock-maker-inline", "org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker")
+ .loadPlugin(MockMaker.class, "org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker");
+
+ private final StackTraceCleanerProvider stackTraceCleanerProvider = new PluginLoader(pluginSwitch)
+ .loadPlugin(StackTraceCleanerProvider.class, "org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider");
+
+ private final InstantiatorProvider instantiatorProvider = new PluginLoader(pluginSwitch)
+ .loadPlugin(InstantiatorProvider.class, "org.mockito.internal.creation.instance.DefaultInstantiatorProvider");
+
+ /**
+ * The implementation of the stack trace cleaner
+ */
+ StackTraceCleanerProvider getStackTraceCleanerProvider() {
+ //TODO we should throw some sensible exception if this is null.
+ return stackTraceCleanerProvider;
+ }
+
+ /**
+ * Returns the implementation of the mock maker available for the current runtime.
+ *
+ * <p>Returns {@link org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker} if no
+ * {@link org.mockito.plugins.MockMaker} extension exists or is visible in the current classpath.</p>
+ */
+ MockMaker getMockMaker() {
+ return mockMaker;
+ }
+
+ /**
+ * Returns the instantiator provider available for the current runtime.
+ *
+ * <p>Returns {@link org.mockito.internal.creation.instance.DefaultInstantiatorProvider} if no
+ * {@link org.mockito.plugins.InstantiatorProvider} extension exists or is visible in the current classpath.</p>
+ */
+ InstantiatorProvider getInstantiatorProvider() {
+ return instantiatorProvider;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/configuration/plugins/Plugins.java b/mockito-updated/src/org/mockito/internal/configuration/plugins/Plugins.java
new file mode 100644
index 0000000..463002b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/configuration/plugins/Plugins.java
@@ -0,0 +1,40 @@
+package org.mockito.internal.configuration.plugins;
+
+import org.mockito.plugins.InstantiatorProvider;
+import org.mockito.plugins.MockMaker;
+import org.mockito.plugins.StackTraceCleanerProvider;
+
+/**
+ * Access to Mockito behavior that can be reconfigured by plugins
+ */
+public class Plugins {
+
+ private static final PluginRegistry registry = new PluginRegistry();
+
+ /**
+ * The implementation of the stack trace cleaner
+ */
+ public static StackTraceCleanerProvider getStackTraceCleanerProvider() {
+ return registry.getStackTraceCleanerProvider();
+ }
+
+ /**
+ * Returns the implementation of the mock maker available for the current runtime.
+ *
+ * <p>Returns default mock maker if no
+ * {@link org.mockito.plugins.MockMaker} extension exists or is visible in the current classpath.</p>
+ */
+ public static MockMaker getMockMaker() {
+ return registry.getMockMaker();
+ }
+
+ /**
+ * Returns the instantiator provider available for the current runtime.
+ *
+ * <p>Returns {@link org.mockito.internal.creation.instance.DefaultInstantiatorProvider} if no
+ * {@link org.mockito.plugins.InstantiatorProvider} extension exists or is visible in the current classpath.</p>
+ */
+ public static InstantiatorProvider getInstantiatorProvider() {
+ return registry.getInstantiatorProvider();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/creation/DelegatingMethod.java b/mockito-updated/src/org/mockito/internal/creation/DelegatingMethod.java
new file mode 100644
index 0000000..034694f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/DelegatingMethod.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.creation;
+
+import org.mockito.internal.invocation.MockitoMethod;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+public class DelegatingMethod implements MockitoMethod {
+
+ private final Method method;
+
+ public DelegatingMethod(Method method) {
+ assert method != null : "Method cannot be null";
+ this.method = method;
+ }
+
+ public Class<?>[] getExceptionTypes() {
+ return method.getExceptionTypes();
+ }
+
+ public Method getJavaMethod() {
+ return method;
+ }
+
+ public String getName() {
+ return method.getName();
+ }
+
+ public Class<?>[] getParameterTypes() {
+ return method.getParameterTypes();
+ }
+
+ public Class<?> getReturnType() {
+ return method.getReturnType();
+ }
+
+ public boolean isVarArgs() {
+ return method.isVarArgs();
+ }
+
+ public boolean isAbstract() {
+ return (method.getModifiers() & Modifier.ABSTRACT) != 0;
+ }
+
+ /**
+ * @return True if the input object is a DelegatingMethod which has an internal Method which is equal to the internal Method of this DelegatingMethod,
+ * or if the input object is a Method which is equal to the internal Method of this DelegatingMethod.
+ */
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o instanceof DelegatingMethod) {
+ DelegatingMethod that = (DelegatingMethod) o;
+ return method.equals(that.method);
+ } else {
+ return method.equals(o);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return method.hashCode();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/creation/MockSettingsImpl.java b/mockito-updated/src/org/mockito/internal/creation/MockSettingsImpl.java
new file mode 100644
index 0000000..0b76174
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/MockSettingsImpl.java
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.creation;
+
+import org.mockito.MockSettings;
+
+import static org.mockito.internal.exceptions.Reporter.*;
+import org.mockito.internal.creation.settings.CreationSettings;
+import org.mockito.internal.debugging.VerboseMockInvocationLogger;
+import org.mockito.internal.util.MockCreationValidator;
+import org.mockito.internal.util.MockNameImpl;
+import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.mock.MockName;
+import org.mockito.mock.SerializableMode;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.mockito.internal.util.collections.Sets.newSet;
+
+@SuppressWarnings("unchecked")
+public class MockSettingsImpl<T> extends CreationSettings<T> implements MockSettings, MockCreationSettings<T> {
+
+ private static final long serialVersionUID = 4475297236197939569L;
+ private boolean useConstructor;
+ private Object outerClassInstance;
+
+ public MockSettings serializable() {
+ return serializable(SerializableMode.BASIC);
+ }
+
+ public MockSettings serializable(SerializableMode mode) {
+ this.serializableMode = mode;
+ return this;
+ }
+
+ public MockSettings extraInterfaces(Class<?>... extraInterfaces) {
+ if (extraInterfaces == null || extraInterfaces.length == 0) {
+ throw extraInterfacesRequiresAtLeastOneInterface();
+ }
+
+ for (Class<?> i : extraInterfaces) {
+ if (i == null) {
+ throw extraInterfacesDoesNotAcceptNullParameters();
+ } else if (!i.isInterface()) {
+ throw extraInterfacesAcceptsOnlyInterfaces(i);
+ }
+ }
+ this.extraInterfaces = newSet(extraInterfaces);
+ return this;
+ }
+
+ public MockName getMockName() {
+ return mockName;
+ }
+
+ public Set<Class<?>> getExtraInterfaces() {
+ return extraInterfaces;
+ }
+
+ public Object getSpiedInstance() {
+ return spiedInstance;
+ }
+
+ public MockSettings name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public MockSettings spiedInstance(Object spiedInstance) {
+ this.spiedInstance = spiedInstance;
+ return this;
+ }
+
+ public MockSettings defaultAnswer(Answer defaultAnswer) {
+ this.defaultAnswer = defaultAnswer;
+ if (defaultAnswer == null) {
+ throw defaultAnswerDoesNotAcceptNullParameter();
+ }
+ return this;
+ }
+
+ public Answer<Object> getDefaultAnswer() {
+ return defaultAnswer;
+ }
+
+ public MockSettingsImpl<T> stubOnly() {
+ this.stubOnly = true;
+ return this;
+ }
+
+ public MockSettings useConstructor() {
+ this.useConstructor = true;
+ return this;
+ }
+
+ public MockSettings outerInstance(Object outerClassInstance) {
+ this.outerClassInstance = outerClassInstance;
+ return this;
+ }
+
+ public boolean isUsingConstructor() {
+ return useConstructor;
+ }
+
+ public Object getOuterClassInstance() {
+ return outerClassInstance;
+ }
+
+ public boolean isStubOnly() {
+ return this.stubOnly;
+ }
+
+ public MockSettings verboseLogging() {
+ if (!invocationListenersContainsType(VerboseMockInvocationLogger.class)) {
+ invocationListeners(new VerboseMockInvocationLogger());
+ }
+ return this;
+ }
+
+ public MockSettings invocationListeners(InvocationListener... listeners) {
+ if (listeners == null || listeners.length == 0) {
+ throw invocationListenersRequiresAtLeastOneListener();
+ }
+ for (InvocationListener listener : listeners) {
+ if (listener == null) {
+ throw invocationListenerDoesNotAcceptNullParameters();
+ }
+ this.invocationListeners.add(listener);
+ }
+ return this;
+ }
+
+ private boolean invocationListenersContainsType(Class<?> clazz) {
+ for (InvocationListener listener : invocationListeners) {
+ if (listener.getClass().equals(clazz)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public List<InvocationListener> getInvocationListeners() {
+ return this.invocationListeners;
+ }
+
+ public boolean hasInvocationListeners() {
+ return !invocationListeners.isEmpty();
+ }
+
+ public Class<T> getTypeToMock() {
+ return typeToMock;
+ }
+
+ public MockCreationSettings<T> confirm(Class<T> typeToMock) {
+ return validatedSettings(typeToMock, this);
+ }
+
+ private static <T> CreationSettings<T> validatedSettings(Class<T> typeToMock, CreationSettings<T> source) {
+ MockCreationValidator validator = new MockCreationValidator();
+
+ validator.validateType(typeToMock);
+ validator.validateExtraInterfaces(typeToMock, source.getExtraInterfaces());
+ validator.validateMockedType(typeToMock, source.getSpiedInstance());
+
+ //TODO SF - add this validation and also add missing coverage
+// validator.validateDelegatedInstance(classToMock, settings.getDelegatedInstance());
+
+ validator.validateConstructorUse(source.isUsingConstructor(), source.getSerializableMode());
+
+ //TODO SF - I don't think we really need CreationSettings type
+ CreationSettings<T> settings = new CreationSettings<T>(source);
+ settings.setMockName(new MockNameImpl(source.getName(), typeToMock));
+ settings.setTypeToMock(typeToMock);
+ settings.setExtraInterfaces(prepareExtraInterfaces(source));
+ return settings;
+ }
+
+ private static Set<Class<?>> prepareExtraInterfaces(CreationSettings settings) {
+ Set<Class<?>> interfaces = new HashSet<Class<?>>(settings.getExtraInterfaces());
+ if(settings.isSerializable()) {
+ interfaces.add(Serializable.class);
+ }
+ return interfaces;
+ }
+
+}
+
diff --git a/mockito-updated/src/org/mockito/internal/creation/instance/ConstructorInstantiator.java b/mockito-updated/src/org/mockito/internal/creation/instance/ConstructorInstantiator.java
new file mode 100644
index 0000000..c97b5f5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/instance/ConstructorInstantiator.java
@@ -0,0 +1,74 @@
+package org.mockito.internal.creation.instance;
+
+import static org.mockito.internal.util.StringJoiner.join;
+import java.lang.reflect.Constructor;
+import org.mockito.internal.util.reflection.AccessibilityChanger;
+
+public class ConstructorInstantiator implements Instantiator {
+
+ private final Object outerClassInstance;
+
+ public ConstructorInstantiator(Object outerClassInstance) {
+ this.outerClassInstance = outerClassInstance;
+ }
+
+ public <T> T newInstance(Class<T> cls) {
+ if (outerClassInstance == null) {
+ return noArgConstructor(cls);
+ }
+ return withParams(cls, outerClassInstance);
+ }
+
+ private static <T> T withParams(Class<T> cls, Object... params) {
+ try {
+ //this is kind of over-engineered because we don't need to support more params
+ //however, I know we will be needing it :)
+ for (Constructor<?> constructor : cls.getDeclaredConstructors()) {
+ Class<?>[] types = constructor.getParameterTypes();
+ if (paramsMatch(types, params)) {
+ return invokeConstructor(constructor, params);
+ }
+ }
+ } catch (Exception e) {
+ throw paramsException(cls, e);
+ }
+ throw paramsException(cls, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> T invokeConstructor(Constructor<?> constructor, Object... params) throws java.lang.InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
+ AccessibilityChanger accessibility = new AccessibilityChanger();
+ accessibility.enableAccess(constructor);
+ return (T) constructor.newInstance(params);
+ }
+
+ private static <T> InstantiationException paramsException(Class<T> cls, Exception e) {
+ return new InstantiationException(join(
+ "Unable to create instance of '" + cls.getSimpleName() + "'.",
+ "Please ensure that the outer instance has correct type and that the target class has 0-arg constructor.")
+ , e);
+ }
+
+ private static boolean paramsMatch(Class<?>[] types, Object[] params) {
+ if (params.length != types.length) {
+ return false;
+ }
+ for (int i = 0; i < params.length; i++) {
+ if (!types[i].isInstance(params[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static <T> T noArgConstructor(Class<T> cls) {
+ try {
+ return invokeConstructor(cls.getDeclaredConstructor());
+ } catch (Throwable t) {
+ throw new InstantiationException(join(
+ "Unable to create instance of '" + cls.getSimpleName() + "'.",
+ "Please ensure it has 0-arg constructor which invokes cleanly."),
+ t);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java b/mockito-updated/src/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java
new file mode 100644
index 0000000..4df65ce
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/instance/DefaultInstantiatorProvider.java
@@ -0,0 +1,17 @@
+package org.mockito.internal.creation.instance;
+
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.plugins.InstantiatorProvider;
+
+public class DefaultInstantiatorProvider implements InstantiatorProvider {
+
+ private final static Instantiator INSTANCE = new ObjenesisInstantiator();
+
+ public Instantiator getInstantiator(MockCreationSettings<?> settings) {
+ if (settings != null && settings.isUsingConstructor()) {
+ return new ConstructorInstantiator(settings.getOuterClassInstance());
+ } else {
+ return INSTANCE;
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/creation/instance/InstantiationException.java b/mockito-updated/src/org/mockito/internal/creation/instance/InstantiationException.java
new file mode 100644
index 0000000..bdfbcf6
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/instance/InstantiationException.java
@@ -0,0 +1,10 @@
+package org.mockito.internal.creation.instance;
+
+import org.mockito.exceptions.base.MockitoException;
+
+public class InstantiationException extends MockitoException {
+
+ public InstantiationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/creation/instance/Instantiator.java b/mockito-updated/src/org/mockito/internal/creation/instance/Instantiator.java
new file mode 100644
index 0000000..0e2bf57
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/instance/Instantiator.java
@@ -0,0 +1,13 @@
+package org.mockito.internal.creation.instance;
+
+/**
+ * Provides instances of classes.
+ */
+public interface Instantiator {
+
+ /**
+ * Creates instance of given class
+ */
+ <T> T newInstance(Class<T> cls) throws InstantiationException;
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/creation/instance/ObjenesisInstantiator.java b/mockito-updated/src/org/mockito/internal/creation/instance/ObjenesisInstantiator.java
new file mode 100644
index 0000000..1ca0003
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/instance/ObjenesisInstantiator.java
@@ -0,0 +1,16 @@
+package org.mockito.internal.creation.instance;
+
+import org.mockito.internal.configuration.GlobalConfiguration;
+import org.objenesis.ObjenesisStd;
+
+class ObjenesisInstantiator implements Instantiator {
+
+ //TODO: in order to provide decent exception message when objenesis is not found,
+ //have a constructor in this class that tries to instantiate ObjenesisStd and if it fails then show decent exception that dependency is missing
+ //TODO: for the same reason catch and give better feedback when hamcrest core is not found.
+ private final ObjenesisStd objenesis = new ObjenesisStd(new GlobalConfiguration().enableClassCache());
+
+ public <T> T newInstance(Class<T> cls) {
+ return objenesis.newInstance(cls);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/creation/package.html b/mockito-updated/src/org/mockito/internal/creation/package.html
new file mode 100644
index 0000000..533a36a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Mock object creation.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/creation/settings/CreationSettings.java b/mockito-updated/src/org/mockito/internal/creation/settings/CreationSettings.java
new file mode 100644
index 0000000..dbca6f5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/settings/CreationSettings.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.creation.settings;
+
+import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.mock.MockName;
+import org.mockito.mock.SerializableMode;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+public class CreationSettings<T> implements MockCreationSettings<T>, Serializable {
+ private static final long serialVersionUID = -6789800638070123629L;
+
+ protected Class<T> typeToMock;
+ protected Set<Class<?>> extraInterfaces = new LinkedHashSet<Class<?>>();
+ protected String name;
+ protected Object spiedInstance;
+ protected Answer<Object> defaultAnswer;
+ protected MockName mockName;
+ protected SerializableMode serializableMode = SerializableMode.NONE;
+ protected List<InvocationListener> invocationListeners = new ArrayList<InvocationListener>();
+ protected boolean stubOnly;
+ private boolean useConstructor;
+ private Object outerClassInstance;
+
+ public CreationSettings() {}
+
+ @SuppressWarnings("unchecked")
+ public CreationSettings(CreationSettings copy) {
+ this.typeToMock = copy.typeToMock;
+ this.extraInterfaces = copy.extraInterfaces;
+ this.name = copy.name;
+ this.spiedInstance = copy.spiedInstance;
+ this.defaultAnswer = copy.defaultAnswer;
+ this.mockName = copy.mockName;
+ this.serializableMode = copy.serializableMode;
+ this.invocationListeners = copy.invocationListeners;
+ this.stubOnly = copy.stubOnly;
+ this.useConstructor = copy.isUsingConstructor();
+ this.outerClassInstance = copy.getOuterClassInstance();
+ }
+
+ public Class<T> getTypeToMock() {
+ return typeToMock;
+ }
+
+ public CreationSettings<T> setTypeToMock(Class<T> typeToMock) {
+ this.typeToMock = typeToMock;
+ return this;
+ }
+
+ public Set<Class<?>> getExtraInterfaces() {
+ return extraInterfaces;
+ }
+
+ public CreationSettings<T> setExtraInterfaces(Set<Class<?>> extraInterfaces) {
+ this.extraInterfaces = extraInterfaces;
+ return this;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Object getSpiedInstance() {
+ return spiedInstance;
+ }
+
+ public Answer<Object> getDefaultAnswer() {
+ return defaultAnswer;
+ }
+
+ public MockName getMockName() {
+ return mockName;
+ }
+
+ public CreationSettings<T> setMockName(MockName mockName) {
+ this.mockName = mockName;
+ return this;
+ }
+
+ public boolean isSerializable() {
+ return serializableMode != SerializableMode.NONE;
+ }
+
+ public CreationSettings<T> setSerializableMode(SerializableMode serializableMode) {
+ this.serializableMode = serializableMode;
+ return this;
+ }
+
+ public SerializableMode getSerializableMode() {
+ return serializableMode;
+ }
+
+ public List<InvocationListener> getInvocationListeners() {
+ return invocationListeners;
+ }
+
+ public boolean isUsingConstructor() {
+ return useConstructor;
+ }
+
+ public Object getOuterClassInstance() {
+ return outerClassInstance;
+ }
+
+ public boolean isStubOnly() {
+ return stubOnly;
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/creation/util/MockitoMethodProxy.java b/mockito-updated/src/org/mockito/internal/creation/util/MockitoMethodProxy.java
new file mode 100644
index 0000000..a77d1b6
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/util/MockitoMethodProxy.java
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.creation.util;
+
+//TODO SF Replace with RealMethod and get rid of (possibly).
+public interface MockitoMethodProxy {
+ Object invokeSuper(Object target, Object[] arguments);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/creation/util/package.html b/mockito-updated/src/org/mockito/internal/creation/util/package.html
new file mode 100644
index 0000000..fb6ba2d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/creation/util/package.html
@@ -0,0 +1,5 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+<body>Stuff that does not have a good package yet</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/debugging/FindingsListener.java b/mockito-updated/src/org/mockito/internal/debugging/FindingsListener.java
new file mode 100644
index 0000000..1aa623b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/FindingsListener.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+public interface FindingsListener {
+ void foundStubCalledWithDifferentArgs(Invocation unused, InvocationMatcher unstubbed);
+
+ void foundUnusedStub(Invocation unused);
+
+ void foundUnstubbed(InvocationMatcher unstubbed);
+}
diff --git a/mockito-updated/src/org/mockito/internal/debugging/InvocationsPrinter.java b/mockito-updated/src/org/mockito/internal/debugging/InvocationsPrinter.java
new file mode 100644
index 0000000..b0df32a
--- /dev/null
+++ b/mockito-updated/src/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/mockito-updated/src/org/mockito/internal/debugging/Localized.java b/mockito-updated/src/org/mockito/internal/debugging/Localized.java
new file mode 100644
index 0000000..d1e2678
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/Localized.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.debugging;
+
+
+import org.mockito.invocation.Location;
+
+public class Localized<T> {
+
+ private final T object;
+ private final Location location;
+
+ public Localized(T object) {
+ this.object = object;
+ location = new LocationImpl();
+ }
+
+ public T getObject() {
+ return object;
+ }
+
+ public Location getLocation() {
+ return location;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/debugging/LocationImpl.java b/mockito-updated/src/org/mockito/internal/debugging/LocationImpl.java
new file mode 100644
index 0000000..c661ced
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/LocationImpl.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import java.io.Serializable;
+import org.mockito.internal.exceptions.stacktrace.StackTraceFilter;
+import org.mockito.invocation.Location;
+
+public class LocationImpl implements Location, Serializable {
+
+ private static final long serialVersionUID = -9054861157390980624L;
+ private final Throwable stackTraceHolder;
+ private final StackTraceFilter stackTraceFilter;
+
+ public LocationImpl() {
+ this(new StackTraceFilter());
+ }
+
+ public LocationImpl(StackTraceFilter stackTraceFilter) {
+ this.stackTraceFilter = stackTraceFilter;
+ stackTraceHolder = new Throwable();
+ }
+
+ @Override
+ public String toString() {
+ //TODO SF perhaps store the results after invocation?
+ StackTraceElement[] filtered = stackTraceFilter.filter(stackTraceHolder.getStackTrace(), false);
+ if (filtered.length == 0) {
+ return "-> at <<unknown line>>";
+ }
+ return "-> at " + filtered[0].toString();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/debugging/LoggingListener.java b/mockito-updated/src/org/mockito/internal/debugging/LoggingListener.java
new file mode 100644
index 0000000..863ee8e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/LoggingListener.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import static org.mockito.internal.util.StringJoiner.join;
+
+public class LoggingListener implements FindingsListener {
+ private final boolean warnAboutUnstubbed;
+
+ private final List<String> argMismatchStubs = new LinkedList<String>();
+ private final List<String> unusedStubs = new LinkedList<String>();
+ private final List<String> unstubbedCalls = new LinkedList<String>();
+
+ public LoggingListener(boolean warnAboutUnstubbed) {
+ this.warnAboutUnstubbed = warnAboutUnstubbed;
+ }
+
+ public void foundStubCalledWithDifferentArgs(Invocation unused, InvocationMatcher unstubbed) {
+ //TODO there is not good reason we should get Invocation and InvocationMatcher here
+ // we should pass 2 InvocationMatchers and testing is easier
+ // it's also confusing that unstubbed invocation is passed as InvocationMatcher (should be rather Invocation)
+
+ //this information comes in pairs
+ String index = Integer.toString(indexOfNextPair(argMismatchStubs.size()));
+ //making sure indentation is correct
+ String padding = index.replaceAll("\\d", " ");
+ argMismatchStubs.add(index + ". Stubbed " + unused.getLocation());
+ argMismatchStubs.add(padding + " Invoked " + unstubbed.getInvocation().getLocation());
+ }
+
+ static int indexOfNextPair(int collectionSize) {
+ return (collectionSize / 2) + 1;
+ }
+
+ public void foundUnusedStub(Invocation unused) {
+ unusedStubs.add((unusedStubs.size() + 1) + ". " + unused.getLocation());
+ }
+
+ public void foundUnstubbed(InvocationMatcher unstubbed) {
+ if (warnAboutUnstubbed) {
+ unstubbedCalls.add((unstubbedCalls.size() + 1) + ". " + unstubbed.getInvocation().getLocation());
+ }
+ }
+
+ public String getStubbingInfo() {
+ if (argMismatchStubs.isEmpty() && unusedStubs.isEmpty() && unstubbedCalls.isEmpty()) {
+ return "";
+ }
+
+ List<String> lines = new LinkedList<String>();
+ lines.add("[Mockito] Additional stubbing information (see javadoc for StubbingInfo class):");
+
+ if (!argMismatchStubs.isEmpty()) {
+ lines.add("[Mockito]");
+ lines.add("[Mockito] Argument mismatch between stubbing and actual invocation (is stubbing correct in the test?):");
+ lines.add("[Mockito]");
+ addOrderedList(lines, argMismatchStubs);
+ }
+
+ if (!unusedStubs.isEmpty()) {
+ lines.add("[Mockito]");
+ lines.add("[Mockito] Unused stubbing (perhaps can be removed from the test?):");
+ lines.add("[Mockito]");
+ addOrderedList(lines, unusedStubs);
+ }
+
+ if (!unstubbedCalls.isEmpty()) {
+ lines.add("[Mockito]");
+ lines.add("[Mockito] Unstubbed method invocations (perhaps missing stubbing in the test?):");
+ lines.add("[Mockito]");
+ addOrderedList(lines, unstubbedCalls);
+ }
+ return join("", lines);
+ }
+
+ private void addOrderedList(List<String> target, List<String> additions) {
+ for (String a : additions) {
+ target.add("[Mockito] " + a);
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/debugging/MockitoDebuggerImpl.java b/mockito-updated/src/org/mockito/internal/debugging/MockitoDebuggerImpl.java
new file mode 100644
index 0000000..35e7e7b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/MockitoDebuggerImpl.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import org.mockito.MockitoDebugger;
+import org.mockito.internal.invocation.UnusedStubsFinder;
+import org.mockito.internal.invocation.finder.AllInvocationsFinder;
+import org.mockito.invocation.Invocation;
+
+import java.util.List;
+
+import static java.util.Arrays.asList;
+
+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));
+ out += line("********************************");
+ out += line("*** Mockito interactions log ***");
+ out += line("********************************");
+ for(Invocation i:invocations) {
+ out += line(i.toString());
+ out += line(" invoked: " + i.getLocation());
+ if (i.stubInfo() != null) {
+ out += line(" stubbed: " + i.stubInfo().stubbedAt().toString());
+ }
+ }
+
+ invocations = unusedStubsFinder.find(asList(mocks));
+ if (invocations.isEmpty()) {
+ return print(out);
+ }
+ out += line("********************************");
+ out += line("*** Unused stubs ***");
+ out += line("********************************");
+
+ for(Invocation i:invocations) {
+ out += line(i.toString());
+ out += line(" stubbed: " + i.getLocation());
+ }
+ return print(out);
+ }
+
+ private String line(String text) {
+ return text + "\n";
+ }
+
+ private String print(String out) {
+ System.out.println(out);
+ return out;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/debugging/VerboseMockInvocationLogger.java b/mockito-updated/src/org/mockito/internal/debugging/VerboseMockInvocationLogger.java
new file mode 100644
index 0000000..0712fb7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/VerboseMockInvocationLogger.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.debugging;
+
+import java.io.PrintStream;
+import org.mockito.invocation.DescribedInvocation;
+import org.mockito.listeners.InvocationListener;
+import org.mockito.listeners.MethodInvocationReport;
+
+/**
+ * Logs all invocations to standard output.
+ *
+ * Used for debugging interactions with a mock.
+ */
+public class VerboseMockInvocationLogger implements InvocationListener {
+
+ // visible for testing
+ final PrintStream printStream;
+
+ private int mockInvocationsCounter = 0;
+
+ public VerboseMockInvocationLogger() {
+ this(System.out);
+ }
+
+ public VerboseMockInvocationLogger(PrintStream printStream) {
+ this.printStream = printStream;
+ }
+
+ public void reportInvocation(MethodInvocationReport methodInvocationReport) {
+ printHeader();
+ printStubInfo(methodInvocationReport);
+ printInvocation(methodInvocationReport.getInvocation());
+ printReturnedValueOrThrowable(methodInvocationReport);
+ printFooter();
+ }
+
+ private void printReturnedValueOrThrowable(MethodInvocationReport methodInvocationReport) {
+ if (methodInvocationReport.threwException()) {
+ String message = methodInvocationReport.getThrowable().getMessage() == null ? "" : " with message " + methodInvocationReport.getThrowable().getMessage();
+ printlnIndented("has thrown: " + methodInvocationReport.getThrowable().getClass() + message);
+ } else {
+ String type = (methodInvocationReport.getReturnedValue() == null) ? "" : " (" + methodInvocationReport.getReturnedValue().getClass().getName() + ")";
+ printlnIndented("has returned: \"" + methodInvocationReport.getReturnedValue() + "\"" + type);
+ }
+ }
+
+ private void printStubInfo(MethodInvocationReport methodInvocationReport) {
+ if (methodInvocationReport.getLocationOfStubbing() != null) {
+ printlnIndented("stubbed: " + methodInvocationReport.getLocationOfStubbing());
+ }
+ }
+
+ private void printHeader() {
+ mockInvocationsCounter++;
+ printStream.println("############ Logging method invocation #" + mockInvocationsCounter + " on mock/spy ########");
+ }
+
+ private void printInvocation(DescribedInvocation invocation) {
+ printStream.println(invocation.toString());
+// printStream.println("Handling method call on a mock/spy.");
+ printlnIndented("invoked: " + invocation.getLocation().toString());
+ }
+
+ private void printFooter() {
+ printStream.println("");
+ }
+
+ private void printlnIndented(String message) {
+ printStream.println(" " + message);
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/debugging/WarningsCollector.java b/mockito-updated/src/org/mockito/internal/debugging/WarningsCollector.java
new file mode 100644
index 0000000..e941886
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/WarningsCollector.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.invocation.UnusedStubsFinder;
+import org.mockito.internal.invocation.finder.AllInvocationsFinder;
+import org.mockito.invocation.Invocation;
+
+import java.util.LinkedList;
+import java.util.List;
+
+@Deprecated
+public class WarningsCollector {
+
+ private final List<Object> createdMocks;
+
+ public WarningsCollector() {
+ createdMocks = new LinkedList<Object>();
+ }
+
+ public String getWarnings() {
+ List<Invocation> unused = new UnusedStubsFinder().find(createdMocks);
+ List<Invocation> all = AllInvocationsFinder.find(createdMocks);
+ List<InvocationMatcher> allInvocationMatchers = InvocationMatcher.createFrom(all);
+
+ return new WarningsPrinterImpl(unused, allInvocationMatchers, false).print();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/debugging/WarningsFinder.java b/mockito-updated/src/org/mockito/internal/debugging/WarningsFinder.java
new file mode 100644
index 0000000..bd562b1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/WarningsFinder.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+public class WarningsFinder {
+ private final List<Invocation> baseUnusedStubs;
+ private final List<InvocationMatcher> baseAllInvocations;
+
+ public WarningsFinder(List<Invocation> unusedStubs, List<InvocationMatcher> allInvocations) {
+ this.baseUnusedStubs = unusedStubs;
+ this.baseAllInvocations = allInvocations;
+ }
+
+ public void find(FindingsListener findingsListener) {
+ List<Invocation> unusedStubs = new LinkedList<Invocation>(this.baseUnusedStubs);
+ List<InvocationMatcher> allInvocations = new LinkedList<InvocationMatcher>(this.baseAllInvocations);
+
+ Iterator<Invocation> unusedIterator = unusedStubs.iterator();
+ while(unusedIterator.hasNext()) {
+ Invocation unused = unusedIterator.next();
+ Iterator<InvocationMatcher> unstubbedIterator = allInvocations.iterator();
+ while(unstubbedIterator.hasNext()) {
+ InvocationMatcher unstubbed = unstubbedIterator.next();
+ if(unstubbed.hasSimilarMethod(unused)) {
+ findingsListener.foundStubCalledWithDifferentArgs(unused, unstubbed);
+ unusedIterator.remove();
+ unstubbedIterator.remove();
+ }
+ }
+ }
+
+ for (Invocation i : unusedStubs) {
+ findingsListener.foundUnusedStub(i);
+ }
+
+ for (InvocationMatcher i : allInvocations) {
+ findingsListener.foundUnstubbed(i);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/debugging/WarningsPrinterImpl.java b/mockito-updated/src/org/mockito/internal/debugging/WarningsPrinterImpl.java
new file mode 100644
index 0000000..d9a8d03
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/WarningsPrinterImpl.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.debugging;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+import java.util.List;
+
+public class WarningsPrinterImpl {
+
+ private final boolean warnAboutUnstubbed;
+ private final WarningsFinder finder;
+
+ public WarningsPrinterImpl(List<Invocation> unusedStubs, List<InvocationMatcher> allInvocations, boolean warnAboutUnstubbed) {
+ this(warnAboutUnstubbed, new WarningsFinder(unusedStubs, allInvocations));
+ }
+
+ WarningsPrinterImpl(boolean warnAboutUnstubbed, WarningsFinder finder) {
+ this.warnAboutUnstubbed = warnAboutUnstubbed;
+ this.finder = finder;
+ }
+
+ public String print() {
+ LoggingListener listener = new LoggingListener(warnAboutUnstubbed);
+ finder.find(listener);
+ return listener.getStubbingInfo();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/debugging/package.html b/mockito-updated/src/org/mockito/internal/debugging/package.html
new file mode 100644
index 0000000..13cee40
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/debugging/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Whatever helps in debugging failed tests
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/ExceptionIncludingMockitoWarnings.java b/mockito-updated/src/org/mockito/internal/exceptions/ExceptionIncludingMockitoWarnings.java
new file mode 100644
index 0000000..d4f3e0e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/ExceptionIncludingMockitoWarnings.java
@@ -0,0 +1,13 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.exceptions;
+
+public class ExceptionIncludingMockitoWarnings extends RuntimeException {
+ private static final long serialVersionUID = -5925150219446765679L;
+
+ public ExceptionIncludingMockitoWarnings(String message, Throwable throwable) {
+ super(message, throwable);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/MockitoLimitations.java b/mockito-updated/src/org/mockito/internal/exceptions/MockitoLimitations.java
new file mode 100644
index 0000000..bc6d9ba
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/MockitoLimitations.java
@@ -0,0 +1,7 @@
+package org.mockito.internal.exceptions;
+
+public class MockitoLimitations {
+
+ public final static String NON_PUBLIC_PARENT = "Mocking methods declared on non-public parent classes is not supported.";
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/Reporter.java b/mockito-updated/src/org/mockito/internal/exceptions/Reporter.java
new file mode 100644
index 0000000..807bdee
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/Reporter.java
@@ -0,0 +1,845 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.exceptions;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.exceptions.misusing.*;
+import org.mockito.exceptions.verification.*;
+import org.mockito.internal.debugging.LocationImpl;
+import org.mockito.internal.exceptions.util.ScenarioPrinter;
+import org.mockito.internal.junit.JUnitTool;
+import org.mockito.internal.matchers.LocalizedMatcher;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.internal.util.StringJoiner;
+import org.mockito.invocation.DescribedInvocation;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.invocation.Location;
+import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockName;
+import org.mockito.mock.SerializableMode;
+
+import java.lang.reflect.Field;
+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.StringJoiner.join;
+
+/**
+ * Reports verification and misusing errors.
+ * <p>
+ * One of the key points of mocking library is proper verification/exception
+ * messages. All messages in one place makes it easier to tune and amend them.
+ * <p>
+ * Reporter can be injected and therefore is easily testable.
+ * <p>
+ * Generally, exception messages are full of line breaks to make them easy to
+ * read (xunit plugins take only fraction of screen on modern IDEs).
+ */
+public class Reporter {
+
+ private Reporter() {
+ }
+
+ public static MockitoException checkedExceptionInvalid(Throwable t) {
+ return new MockitoException(join(
+ "Checked exception is invalid for this method!",
+ "Invalid: " + t
+ ));
+ }
+
+ public static MockitoException cannotStubWithNullThrowable() {
+ return new MockitoException(join(
+ "Cannot stub with null throwable!"
+ ));
+
+ }
+
+ public static MockitoException unfinishedStubbing(Location location) {
+ return new UnfinishedStubbingException(join(
+ "Unfinished stubbing detected here:",
+ location,
+ "",
+ "E.g. thenReturn() may be missing.",
+ "Examples of correct stubbing:",
+ " when(mock.isOk()).thenReturn(true);",
+ " when(mock.isOk()).thenThrow(exception);",
+ " doThrow(exception).when(mock).someVoidMethod();",
+ "Hints:",
+ " 1. missing thenReturn()",
+ " 2. you are trying to stub a final method, which is not supported",
+ " 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed",
+ ""
+ ));
+ }
+
+ public static MockitoException incorrectUseOfApi() {
+ return new MockitoException(join(
+ "Incorrect use of API detected here:",
+ new LocationImpl(),
+ "",
+ "You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.",
+ "Examples of correct usage:",
+ " when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);",
+ " when(mock.isOk()).thenReturn(true, false).thenThrow(exception);",
+ ""
+ ));
+ }
+
+ public static MockitoException missingMethodInvocation() {
+ return new MissingMethodInvocationException(join(
+ "when() requires an argument which has to be 'a method call on a mock'.",
+ "For example:",
+ " when(mock.getArticles()).thenReturn(articles);",
+ "",
+ "Also, this error might show up because:",
+ "1. you stub either of: final/private/equals()/hashCode() methods.",
+ " Those methods *cannot* be stubbed/verified.",
+ " " + MockitoLimitations.NON_PUBLIC_PARENT,
+ "2. inside when() you don't call method on mock but on some other object.",
+ ""
+ ));
+ }
+
+ public static MockitoException unfinishedVerificationException(Location location) {
+ return new UnfinishedVerificationException(join(
+ "Missing method call for verify(mock) here:",
+ location,
+ "",
+ "Example of correct verification:",
+ " verify(mock).doSomething()",
+ "",
+ "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.",
+ "Those methods *cannot* be stubbed/verified.",
+ MockitoLimitations.NON_PUBLIC_PARENT,
+ ""
+ ));
+ }
+
+ public static MockitoException notAMockPassedToVerify(Class<?> type) {
+ return new NotAMockException(join(
+ "Argument passed to verify() is of type " + type.getSimpleName() + " and is not a mock!",
+ "Make sure you place the parenthesis correctly!",
+ "See the examples of correct verifications:",
+ " verify(mock).someMethod();",
+ " verify(mock, times(10)).someMethod();",
+ " verify(mock, atLeastOnce()).someMethod();"
+ ));
+ }
+
+ public static MockitoException nullPassedToVerify() {
+ return new NullInsteadOfMockException(join(
+ "Argument passed to verify() should be a mock but is null!",
+ "Examples of correct verifications:",
+ " verify(mock).someMethod();",
+ " verify(mock, times(10)).someMethod();",
+ " verify(mock, atLeastOnce()).someMethod();",
+ " not: verify(mock.someMethod());",
+ "Also, if you use @Mock annotation don't miss initMocks()"
+ ));
+ }
+
+ public static MockitoException notAMockPassedToWhenMethod() {
+ return new NotAMockException(join(
+ "Argument passed to when() is not a mock!",
+ "Example of correct stubbing:",
+ " doThrow(new RuntimeException()).when(mock).someMethod();"
+ ));
+ }
+
+ public static MockitoException nullPassedToWhenMethod() {
+ return new NullInsteadOfMockException(join(
+ "Argument passed to when() is null!",
+ "Example of correct stubbing:",
+ " doThrow(new RuntimeException()).when(mock).someMethod();",
+ "Also, if you use @Mock annotation don't miss initMocks()"
+ ));
+ }
+
+ public static MockitoException mocksHaveToBePassedToVerifyNoMoreInteractions() {
+ return new MockitoException(join(
+ "Method requires argument(s)!",
+ "Pass mocks that should be verified, e.g:",
+ " verifyNoMoreInteractions(mockOne, mockTwo);",
+ " verifyZeroInteractions(mockOne, mockTwo);",
+ ""
+ ));
+ }
+
+ public static MockitoException notAMockPassedToVerifyNoMoreInteractions() {
+ return new NotAMockException(join(
+ "Argument(s) passed is not a mock!",
+ "Examples of correct verifications:",
+ " verifyNoMoreInteractions(mockOne, mockTwo);",
+ " verifyZeroInteractions(mockOne, mockTwo);",
+ ""
+ ));
+ }
+
+ public static MockitoException nullPassedToVerifyNoMoreInteractions() {
+ return new NullInsteadOfMockException(join(
+ "Argument(s) passed is null!",
+ "Examples of correct verifications:",
+ " verifyNoMoreInteractions(mockOne, mockTwo);",
+ " verifyZeroInteractions(mockOne, mockTwo);"
+ ));
+ }
+
+ public static MockitoException notAMockPassedWhenCreatingInOrder() {
+ return new NotAMockException(join(
+ "Argument(s) passed is not a mock!",
+ "Pass mocks that require verification in order.",
+ "For example:",
+ " InOrder inOrder = inOrder(mockOne, mockTwo);"
+ ));
+ }
+
+ public static MockitoException nullPassedWhenCreatingInOrder() {
+ return new NullInsteadOfMockException(join(
+ "Argument(s) passed is null!",
+ "Pass mocks that require verification in order.",
+ "For example:",
+ " InOrder inOrder = inOrder(mockOne, mockTwo);"
+ ));
+ }
+
+ public static MockitoException mocksHaveToBePassedWhenCreatingInOrder() {
+ return new MockitoException(join(
+ "Method requires argument(s)!",
+ "Pass mocks that require verification in order.",
+ "For example:",
+ " InOrder inOrder = inOrder(mockOne, mockTwo);"
+ ));
+ }
+
+ public static MockitoException inOrderRequiresFamiliarMock() {
+ return new MockitoException(join(
+ "InOrder can only verify mocks that were passed in during creation of InOrder.",
+ "For example:",
+ " InOrder inOrder = inOrder(mockOne);",
+ " inOrder.verify(mockOne).doStuff();"
+ ));
+ }
+
+ public static MockitoException invalidUseOfMatchers(int expectedMatchersCount, List<LocalizedMatcher> recordedMatchers) {
+ return new InvalidUseOfMatchersException(join(
+ "Invalid use of argument matchers!",
+ expectedMatchersCount + " matchers expected, " + recordedMatchers.size() + " recorded:" +
+ locationsOf(recordedMatchers),
+ "",
+ "This exception may occur if matchers are combined with raw values:",
+ " //incorrect:",
+ " someMethod(anyObject(), \"raw String\");",
+ "When using matchers, all arguments have to be provided by matchers.",
+ "For example:",
+ " //correct:",
+ " someMethod(anyObject(), eq(\"String by matcher\"));",
+ "",
+ "For more info see javadoc for Matchers class.",
+ ""
+ ));
+ }
+
+ public static MockitoException incorrectUseOfAdditionalMatchers(String additionalMatcherName, int expectedSubMatchersCount, Collection<LocalizedMatcher> matcherStack) {
+ return new InvalidUseOfMatchersException(join(
+ "Invalid use of argument matchers inside additional matcher " + additionalMatcherName + " !",
+ new LocationImpl(),
+ "",
+ expectedSubMatchersCount + " sub matchers expected, " + matcherStack.size() + " recorded:",
+ locationsOf(matcherStack),
+ "",
+ "This exception may occur if matchers are combined with raw values:",
+ " //incorrect:",
+ " someMethod(AdditionalMatchers.and(isNotNull(), \"raw String\");",
+ "When using matchers, all arguments have to be provided by matchers.",
+ "For example:",
+ " //correct:",
+ " someMethod(AdditionalMatchers.and(isNotNull(), eq(\"raw String\"));",
+ "",
+ "For more info see javadoc for Matchers and AdditionalMatchers classes.",
+ ""
+ ));
+ }
+
+ public static MockitoException stubPassedToVerify() {
+ return new CannotVerifyStubOnlyMock(join(
+ "Argument passed to verify() is a stubOnly() mock, not a full blown mock!",
+ "If you intend to verify invocations on a mock, don't use stubOnly() in its MockSettings."
+ ));
+ }
+
+ public static MockitoException reportNoSubMatchersFound(String additionalMatcherName) {
+ return new InvalidUseOfMatchersException(join(
+ "No matchers found for additional matcher " + additionalMatcherName,
+ new LocationImpl(),
+ ""
+ ));
+ }
+
+
+ private static Object locationsOf(Collection<LocalizedMatcher> matchers) {
+ List<String> description = new ArrayList<String>();
+ for (LocalizedMatcher matcher : matchers)
+ description.add(matcher.getLocation().toString());
+ 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,
+ ""
+ );
+
+ return JUnitTool.createArgumentsAreDifferentException(message, wanted, actual);
+ }
+
+ public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted) {
+ return new WantedButNotInvoked(createWantedButNotInvokedMessage(wanted));
+ }
+
+ public static MockitoAssertionError wantedButNotInvoked(DescribedInvocation wanted, List<? extends DescribedInvocation> invocations) {
+ String allInvocations;
+ if (invocations.isEmpty()) {
+ allInvocations = "Actually, there were zero interactions with this mock.\n";
+ } else {
+ StringBuilder sb = new StringBuilder(
+ "\nHowever, there " + were_exactly_x_interactions(invocations.size()) + " with this mock:\n");
+ for (DescribedInvocation i : invocations) {
+ sb.append(i.toString())
+ .append("\n")
+ .append(i.getLocation())
+ .append("\n\n");
+ }
+ allInvocations = sb.toString();
+ }
+
+ String message = createWantedButNotInvokedMessage(wanted);
+ return new WantedButNotInvoked(message + allInvocations);
+ }
+
+ private static String createWantedButNotInvokedMessage(DescribedInvocation wanted) {
+ return join(
+ "Wanted but not invoked:",
+ wanted.toString(),
+ new LocationImpl(),
+ ""
+ );
+ }
+
+ public static MockitoAssertionError wantedButNotInvokedInOrder(DescribedInvocation wanted, DescribedInvocation previous) {
+ return new VerificationInOrderFailure(join(
+ "Verification in order failure",
+ "Wanted but not invoked:",
+ wanted.toString(),
+ new LocationImpl(),
+ "Wanted anywhere AFTER following interaction:",
+ previous.toString(),
+ previous.getLocation(),
+ ""
+ ));
+ }
+
+ public static MockitoAssertionError tooManyActualInvocations(int wantedCount, int actualCount, DescribedInvocation wanted, Location firstUndesired) {
+ String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, firstUndesired);
+ return new TooManyActualInvocations(message);
+ }
+
+ private static String createTooManyInvocationsMessage(int wantedCount, int actualCount, DescribedInvocation wanted,
+ Location firstUndesired) {
+ return join(
+ wanted.toString(),
+ "Wanted " + pluralize(wantedCount) + ":",
+ new LocationImpl(),
+ "But was " + pluralize(actualCount) + ". Undesired invocation:",
+ firstUndesired,
+ ""
+ );
+ }
+
+ public static MockitoAssertionError neverWantedButInvoked(DescribedInvocation wanted, Location firstUndesired) {
+ return new NeverWantedButInvoked(join(
+ wanted.toString(),
+ "Never wanted here:",
+ new LocationImpl(),
+ "But invoked here:",
+ firstUndesired,
+ ""
+ ));
+ }
+
+ public static MockitoAssertionError tooManyActualInvocationsInOrder(int wantedCount, int actualCount, DescribedInvocation wanted, Location firstUndesired) {
+ String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, firstUndesired);
+ 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";
+
+ return join(
+ wanted.toString(),
+ "Wanted " + discrepancy.getPluralizedWantedCount() + (discrepancy.getWantedCount() == 0 ? "." : ":"),
+ new LocationImpl(),
+ "But was " + discrepancy.getPluralizedActualCount() + (discrepancy.getActualCount() == 0 ? "." : ":"),
+ ending
+ );
+ }
+
+ public static MockitoAssertionError tooLittleActualInvocations(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, Location lastActualLocation) {
+ String message = createTooLittleInvocationsMessage(discrepancy, wanted, lastActualLocation);
+
+ return new TooLittleActualInvocations(message);
+ }
+
+ public static MockitoAssertionError tooLittleActualInvocationsInOrder(org.mockito.internal.reporting.Discrepancy discrepancy, DescribedInvocation wanted, Location lastActualLocation) {
+ String message = createTooLittleInvocationsMessage(discrepancy, wanted, lastActualLocation);
+
+ return new VerificationInOrderFailure(join(
+ "Verification in order failure:" + message
+ ));
+ }
+
+ public static MockitoAssertionError noMoreInteractionsWanted(Invocation undesired, List<VerificationAwareInvocation> invocations) {
+ ScenarioPrinter scenarioPrinter = new ScenarioPrinter();
+ String scenario = scenarioPrinter.print(invocations);
+
+ return new NoInteractionsWanted(join(
+ "No interactions wanted here:",
+ new LocationImpl(),
+ "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",
+ undesired.getLocation(),
+ scenario
+ ));
+ }
+
+ public static MockitoAssertionError noMoreInteractionsWantedInOrder(Invocation undesired) {
+ return new VerificationInOrderFailure(join(
+ "No interactions wanted here:",
+ new LocationImpl(),
+ "But found this interaction on mock '" + safelyGetMockName(undesired.getMock()) + "':",
+ undesired.getLocation()
+ ));
+ }
+
+ public static MockitoException cannotMockClass(Class<?> clazz, String reason) {
+ return new MockitoException(join(
+ "Cannot mock/spy " + clazz.toString(),
+ "Mockito cannot mock/spy because :",
+ " - " + reason
+ ));
+ }
+
+ public static MockitoException cannotStubVoidMethodWithAReturnValue(String methodName) {
+ return new CannotStubVoidMethodWithReturnValue(join(
+ "'" + methodName + "' is a *void method* and it *cannot* be stubbed with a *return value*!",
+ "Voids are usually stubbed with Throwables:",
+ " doThrow(exception).when(mock).someVoidMethod();",
+ "***",
+ "If you're unsure why you're getting above error read on.",
+ "Due to the nature of the syntax above problem might occur because:",
+ "1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.",
+ "2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.",
+ "3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",
+ " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",
+ "4. " + MockitoLimitations.NON_PUBLIC_PARENT,
+ ""
+ ));
+ }
+
+ public static MockitoException onlyVoidMethodsCanBeSetToDoNothing() {
+ return new MockitoException(join(
+ "Only void methods can doNothing()!",
+ "Example of correct use of doNothing():",
+ " doNothing().",
+ " doThrow(new RuntimeException())",
+ " .when(mock).someVoidMethod();",
+ "Above means:",
+ "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called"
+ ));
+ }
+
+ public static MockitoException wrongTypeOfReturnValue(String expectedType, String actualType, String methodName) {
+ return new WrongTypeOfReturnValue(join(
+ actualType + " cannot be returned by " + methodName + "()",
+ methodName + "() should return " + expectedType,
+ "***",
+ "If you're unsure why you're getting above error read on.",
+ "Due to the nature of the syntax above problem might occur because:",
+ "1. This exception *might* occur in wrongly written multi-threaded tests.",
+ " Please refer to Mockito FAQ on limitations of concurrency testing.",
+ "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",
+ " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",
+ ""
+ ));
+ }
+
+ public static MockitoException wrongTypeReturnedByDefaultAnswer(Object mock, String expectedType, String actualType, String methodName) {
+ return new WrongTypeOfReturnValue(join(
+ "Default answer returned a result with the wrong type:",
+ actualType + " cannot be returned by " + methodName + "()",
+ methodName + "() should return " + expectedType,
+ "",
+ "The default answer of " + safelyGetMockName(mock) + " that was configured on the mock is probably incorrectly implemented.",
+ ""
+ ));
+ }
+
+
+ public static MockitoAssertionError wantedAtMostX(int maxNumberOfInvocations, int foundSize) {
+ return new MockitoAssertionError(join("Wanted at most " + pluralize(maxNumberOfInvocations) + " but was " + foundSize));
+ }
+
+ public static MockitoException misplacedArgumentMatcher(List<LocalizedMatcher> lastMatchers) {
+ return new InvalidUseOfMatchersException(join(
+ "Misplaced argument matcher detected here:",
+ locationsOf(lastMatchers),
+ "",
+ "You cannot use argument matchers outside of verification or stubbing.",
+ "Examples of correct usage of argument matchers:",
+ " when(mock.get(anyInt())).thenReturn(null);",
+ " doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());",
+ " verify(mock).someMethod(contains(\"foo\"))",
+ "",
+ "Also, this error might show up because you use argument matchers with methods that cannot be mocked.",
+ "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().",
+ MockitoLimitations.NON_PUBLIC_PARENT,
+ ""
+ ));
+ }
+
+ public static MockitoException smartNullPointerException(String invocation, Location location) {
+ return new SmartNullPointerException(join(
+ "You have a NullPointerException here:",
+ new LocationImpl(),
+ "because this method call was *not* stubbed correctly:",
+ location,
+ invocation,
+ ""
+ ));
+ }
+
+ public static MockitoException noArgumentValueWasCaptured() {
+ return new MockitoException(join(
+ "No argument value was captured!",
+ "You might have forgotten to use argument.capture() in verify()...",
+ "...or you used capture() in stubbing but stubbed method was not called.",
+ "Be aware that it is recommended to use capture() only with verify()",
+ "",
+ "Examples of correct argument capturing:",
+ " ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);",
+ " verify(mock).doSomething(argument.capture());",
+ " assertEquals(\"John\", argument.getValue().getName());",
+ ""
+ ));
+ }
+
+ public static MockitoException extraInterfacesDoesNotAcceptNullParameters() {
+ return new MockitoException(join(
+ "extraInterfaces() does not accept null parameters."
+ ));
+ }
+
+ public static MockitoException extraInterfacesAcceptsOnlyInterfaces(Class<?> wrongType) {
+ return new MockitoException(join(
+ "extraInterfaces() accepts only interfaces.",
+ "You passed following type: " + wrongType.getSimpleName() + " which is not an interface."
+ ));
+ }
+
+ public static MockitoException extraInterfacesCannotContainMockedType(Class<?> wrongType) {
+ return new MockitoException(join(
+ "extraInterfaces() does not accept the same type as the mocked type.",
+ "You mocked following type: " + wrongType.getSimpleName(),
+ "and you passed the same very interface to the extraInterfaces()"
+ ));
+ }
+
+ public static MockitoException extraInterfacesRequiresAtLeastOneInterface() {
+ return new MockitoException(join(
+ "extraInterfaces() requires at least one interface."
+ ));
+ }
+
+ public static MockitoException mockedTypeIsInconsistentWithSpiedInstanceType(Class<?> mockedType, Object spiedInstance) {
+ return new MockitoException(join(
+ "Mocked type must be the same as the type of your spied instance.",
+ "Mocked type must be: " + spiedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),
+ " //correct spying:",
+ " spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );",
+ " //incorrect - types don't match:",
+ " spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );"
+ ));
+ }
+
+ public static MockitoException cannotCallAbstractRealMethod() {
+ return new MockitoException(join(
+ "Cannot call abstract real method on java object!",
+ "Calling real methods is only possible when mocking non abstract method.",
+ " //correct example:",
+ " when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();"
+ ));
+ }
+
+ public static MockitoException cannotVerifyToString() {
+ return new MockitoException(join(
+ "Mockito cannot verify toString()",
+ "toString() is too often used behind of scenes (i.e. during String concatenation, in IDE debugging views). " +
+ "Verifying it may give inconsistent or hard to understand results. " +
+ "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)",
+ "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases."
+ ));
+ }
+
+ public static MockitoException moreThanOneAnnotationNotAllowed(String fieldName) {
+ return new MockitoException("You cannot have more than one Mockito annotation on a field!\n" +
+ "The field '" + fieldName + "' has multiple Mockito annotations.\n" +
+ "For info how to use annotations see examples in javadoc for MockitoAnnotations class.");
+ }
+
+ public static MockitoException unsupportedCombinationOfAnnotations(String undesiredAnnotationOne, String undesiredAnnotationTwo) {
+ return new MockitoException("This combination of annotations is not permitted on a single field:\n" +
+ "@" + undesiredAnnotationOne + " and @" + undesiredAnnotationTwo);
+ }
+
+ public static MockitoException cannotInitializeForSpyAnnotation(String fieldName, Exception details) {
+ return new MockitoException(join("Cannot instantiate a @Spy for '" + fieldName + "' field.",
+ "You haven't provided the instance for spying at field declaration so I tried to construct the instance.",
+ "However, I failed because: " + details.getMessage(),
+ "Examples of correct usage of @Spy:",
+ " @Spy List mock = new LinkedList();",
+ " @Spy Foo foo; //only if Foo has parameterless constructor",
+ " //also, don't forget about MockitoAnnotations.initMocks();",
+ ""), details);
+ }
+
+ public static MockitoException cannotInitializeForInjectMocksAnnotation(String fieldName, String causeMessage) {
+ return new MockitoException(join("Cannot instantiate @InjectMocks field named '" + fieldName + "'! Cause: "+causeMessage,
+ "You haven't provided the instance at field declaration so I tried to construct the instance.",
+ "Examples of correct usage of @InjectMocks:",
+ " @InjectMocks Service service = new Service();",
+ " @InjectMocks Service service;",
+ " //and... don't forget about some @Mocks for injection :)",
+ ""));
+ }
+
+ public static MockitoException atMostAndNeverShouldNotBeUsedWithTimeout() {
+ return new FriendlyReminderException(join("",
+ "Don't panic! I'm just a friendly reminder!",
+ "timeout() should not be used with atMost() or never() because...",
+ "...it does not make much sense - the test would have passed immediately in concurency",
+ "We kept this method only to avoid compilation errors when upgrading Mockito.",
+ "In future release we will remove timeout(x).atMost(y) from the API.",
+ "If you want to find out more please refer to issue 235",
+ ""));
+ }
+
+ public static MockitoException fieldInitialisationThrewException(Field field, Throwable details) {
+ return new MockitoException(join(
+ "Cannot instantiate @InjectMocks field named '" + field.getName() + "' of type '" + field.getType() + "'.",
+ "You haven't provided the instance at field declaration so I tried to construct the instance.",
+ "However the constructor or the initialization block threw an exception : " + details.getMessage(),
+ ""), details);
+
+ }
+
+ public static MockitoException invocationListenerDoesNotAcceptNullParameters() {
+ return new MockitoException("invocationListeners() does not accept null parameters");
+ }
+
+ public static MockitoException invocationListenersRequiresAtLeastOneListener() {
+ return new MockitoException("invocationListeners() requires at least one listener");
+ }
+
+ public static MockitoException invocationListenerThrewException(InvocationListener listener, Throwable listenerThrowable) {
+ return new MockitoException(StringJoiner.join(
+ "The invocation listener with type " + listener.getClass().getName(),
+ "threw an exception : " + listenerThrowable.getClass().getName() + listenerThrowable.getMessage()), listenerThrowable);
+ }
+
+ public static MockitoException cannotInjectDependency(Field field, Object matchingMock, Exception details) {
+ return new MockitoException(join(
+ "Mockito couldn't inject mock dependency '" + safelyGetMockName(matchingMock) + "' on field ",
+ "'" + field + "'",
+ "whose type '" + field.getDeclaringClass().getCanonicalName() + "' was annotated by @InjectMocks in your test.",
+ "Also I failed because: " + exceptionCauseMessageIfAvailable(details),
+ ""
+ ), details);
+ }
+
+ private static String exceptionCauseMessageIfAvailable(Exception details) {
+ if (details.getCause() == null) {
+ return details.getMessage();
+ }
+ return details.getCause().getMessage();
+ }
+
+ public static MockitoException mockedTypeIsInconsistentWithDelegatedInstanceType(Class<?> mockedType, Object delegatedInstance) {
+ return new MockitoException(join(
+ "Mocked type must be the same as the type of your delegated instance.",
+ "Mocked type must be: " + delegatedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(),
+ " //correct delegate:",
+ " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new ArrayList()<- );",
+ " //incorrect - types don't match:",
+ " spy = mock( ->List.class<- , withSettings().delegatedInstance( ->new HashSet()<- );"
+ ));
+ }
+
+ public static MockitoException spyAndDelegateAreMutuallyExclusive() {
+ return new MockitoException(join(
+ "Settings should not define a spy instance and a delegated instance at the same time."
+ ));
+ }
+
+ public static MockitoException invalidArgumentRangeAtIdentityAnswerCreationTime() {
+ return new MockitoException(join(
+ "Invalid argument index.",
+ "The index need to be a positive number that indicates the position of the argument to return.",
+ "However it is possible to use the -1 value to indicates that the last argument should be",
+ "returned."));
+ }
+
+ public static MockitoException invalidArgumentPositionRangeAtInvocationTime(InvocationOnMock invocation, boolean willReturnLastParameter, int argumentIndex) {
+ return new MockitoException(join(
+ "Invalid argument index for the current invocation of method : ",
+ " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
+ "",
+ (willReturnLastParameter ?
+ "Last parameter wanted" :
+ "Wanted parameter at position " + argumentIndex) + " but " + possibleArgumentTypesOf(invocation),
+ "The index need to be a positive number that indicates a valid position of the argument in the invocation.",
+ "However it is possible to use the -1 value to indicates that the last argument should be returned.",
+ ""
+ ));
+ }
+
+ private static StringBuilder possibleArgumentTypesOf(InvocationOnMock invocation) {
+ Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
+ if (parameterTypes.length == 0) {
+ return new StringBuilder("the method has no arguments.\n");
+ }
+
+ StringBuilder stringBuilder = new StringBuilder("the possible argument indexes for this method are :\n");
+ for (int i = 0, parameterTypesLength = parameterTypes.length; i < parameterTypesLength; i++) {
+ stringBuilder.append(" [").append(i);
+
+ if (invocation.getMethod().isVarArgs() && i == parameterTypesLength - 1) {
+ stringBuilder.append("+] ").append(parameterTypes[i].getComponentType().getSimpleName()).append(" <- Vararg").append("\n");
+ } else {
+ stringBuilder.append("] ").append(parameterTypes[i].getSimpleName()).append("\n");
+ }
+ }
+ return stringBuilder;
+ }
+
+ public static MockitoException wrongTypeOfArgumentToReturn(InvocationOnMock invocation, String expectedType, Class<?> actualType, int argumentIndex) {
+ return new WrongTypeOfReturnValue(join(
+ "The argument of type '" + actualType.getSimpleName() + "' cannot be returned because the following ",
+ "method should return the type '" + expectedType + "'",
+ " -> " + safelyGetMockName(invocation.getMock()) + "." + invocation.getMethod().getName() + "()",
+ "",
+ "The reason for this error can be :",
+ "1. The wanted argument position is incorrect.",
+ "2. The answer is used on the wrong interaction.",
+ "",
+ "Position of the wanted argument is " + argumentIndex + " and " + possibleArgumentTypesOf(invocation),
+ "***",
+ "However if you're still unsure why you're getting above error read on.",
+ "Due to the nature of the syntax above problem might occur because:",
+ "1. This exception *might* occur in wrongly written multi-threaded tests.",
+ " Please refer to Mockito FAQ on limitations of concurrency testing.",
+ "2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - ",
+ " - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.",
+ ""
+ ));
+ }
+
+ public static MockitoException defaultAnswerDoesNotAcceptNullParameter() {
+ return new MockitoException("defaultAnswer() does not accept null parameter");
+ }
+
+ public static MockitoException serializableWontWorkForObjectsThatDontImplementSerializable(Class<?> classToMock) {
+ return new MockitoException(join(
+ "You are using the setting 'withSettings().serializable()' however the type you are trying to mock '" + classToMock.getSimpleName() + "'",
+ "do not implement Serializable AND do not have a no-arg constructor.",
+ "This combination is requested, otherwise you will get an 'java.io.InvalidClassException' when the mock will be serialized",
+ "",
+ "Also note that as requested by the Java serialization specification, the whole hierarchy need to implements Serializable,",
+ "i.e. the top-most superclass has to implements Serializable.",
+ ""
+ ));
+ }
+
+ public static MockitoException delegatedMethodHasWrongReturnType(Method mockMethod, Method delegateMethod, Object mock, Object delegate) {
+ return new MockitoException(join(
+ "Methods called on delegated instance must have compatible return types with the mock.",
+ "When calling: " + mockMethod + " on mock: " + safelyGetMockName(mock),
+ "return type should be: " + mockMethod.getReturnType().getSimpleName() + ", but was: " + delegateMethod.getReturnType().getSimpleName(),
+ "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
+ "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"
+ ));
+ }
+
+ public static MockitoException delegatedMethodDoesNotExistOnDelegate(Method mockMethod, Object mock, Object delegate) {
+ return new MockitoException(join(
+ "Methods called on mock must exist in delegated instance.",
+ "When calling: " + mockMethod + " on mock: " + safelyGetMockName(mock),
+ "no such method was found.",
+ "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods",
+ "(delegate instance had type: " + delegate.getClass().getSimpleName() + ")"
+ ));
+ }
+
+ public static MockitoException usingConstructorWithFancySerializable(SerializableMode mode) {
+ return new MockitoException("Mocks instantiated with constructor cannot be combined with " + mode + " serialization mode.");
+ }
+
+ public static MockitoException cannotCreateTimerWithNegativeDurationTime(long durationMillis) {
+ return new FriendlyReminderException(join(
+ "",
+ "Don't panic! I'm just a friendly reminder!",
+ "It is impossible for time to go backward, therefore...",
+ "You cannot put negative value of duration: (" + durationMillis + ")",
+ "as argument of timer methods (after(), timeout())",
+ ""
+ ));
+ }
+
+ public static MockitoException notAnException() {
+ return new MockitoException(join(
+ "Exception type cannot be null.",
+ "This may happen with doThrow(Class)|thenThrow(Class) family of methods if passing null parameter."));
+ }
+
+ private static MockName safelyGetMockName(Object mock) {
+ return MockUtil.getMockName(mock);
+ }
+
+ public static UnnecessaryStubbingException formatUnncessaryStubbingException(Class<?> testClass, Collection<Invocation> unnecessaryStubbings) {
+ StringBuilder stubbings = new StringBuilder();
+ int count = 1;
+ for (Invocation u : unnecessaryStubbings) {
+ stubbings.append("\n ").append(count++).append(". ").append(u.getLocation());
+ }
+ return new UnnecessaryStubbingException(join(
+ "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."
+ ));
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/VerificationAwareInvocation.java b/mockito-updated/src/org/mockito/internal/exceptions/VerificationAwareInvocation.java
new file mode 100644
index 0000000..adfdbc9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/VerificationAwareInvocation.java
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.exceptions;
+
+import org.mockito.invocation.DescribedInvocation;
+
+public interface VerificationAwareInvocation extends DescribedInvocation {
+
+ boolean isVerified();
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilter.java b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilter.java
new file mode 100644
index 0000000..1996e40
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/ConditionalStackTraceFilter.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.exceptions.stacktrace;
+
+import org.mockito.configuration.IMockitoConfiguration;
+import org.mockito.internal.configuration.GlobalConfiguration;
+
+import java.io.Serializable;
+
+public class ConditionalStackTraceFilter implements Serializable {
+ private static final long serialVersionUID = -8085849703510292641L;
+
+ private final IMockitoConfiguration config = new GlobalConfiguration();
+ private final StackTraceFilter filter = new StackTraceFilter();
+
+ public void filter(Throwable throwable) {
+ if (!config.cleansStackTrace()) {
+ return;
+ }
+ StackTraceElement[] filtered = filter.filter(throwable.getStackTrace(), true);
+ throwable.setStackTrace(filtered);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java
new file mode 100644
index 0000000..c7ac166
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleaner.java
@@ -0,0 +1,36 @@
+package org.mockito.internal.exceptions.stacktrace;
+
+import org.mockito.exceptions.stacktrace.StackTraceCleaner;
+
+/**
+* This predicate is used to filter "good" {@link StackTraceElement}. Good
+*/
+public class DefaultStackTraceCleaner implements StackTraceCleaner {
+
+ @Override
+ public boolean isIn(StackTraceElement e) {
+ if (isFromMockitoRunner(e.getClassName()) || isFromMockitoRule(e.getClassName())) {
+ return true;
+ } else if (isMockDispatcher(e.getClassName()) || isFromMockito(e.getClassName())) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ private static boolean isMockDispatcher(String className) {
+ return (className.contains("$$EnhancerByMockitoWithCGLIB$$")|| className.contains("$MockitoMock$"));
+ }
+
+ private static boolean isFromMockito(String className) {
+ return className.startsWith("org.mockito.");
+ }
+
+ private static boolean isFromMockitoRule(String className) {
+ return className.startsWith("org.mockito.internal.junit.JUnitRule");
+ }
+
+ private static boolean isFromMockitoRunner(String className) {
+ return className.startsWith("org.mockito.internal.runners.") || className.startsWith("org.mockito.runners.");
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleanerProvider.java b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleanerProvider.java
new file mode 100644
index 0000000..b0d30e4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/DefaultStackTraceCleanerProvider.java
@@ -0,0 +1,14 @@
+package org.mockito.internal.exceptions.stacktrace;
+
+import org.mockito.exceptions.stacktrace.StackTraceCleaner;
+import org.mockito.plugins.StackTraceCleanerProvider;
+
+/**
+ * by Szczepan Faber, created at: 7/29/12
+ */
+public class DefaultStackTraceCleanerProvider implements StackTraceCleanerProvider {
+
+ public StackTraceCleaner getStackTraceCleaner(StackTraceCleaner defaultCleaner) {
+ return defaultCleaner;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
new file mode 100644
index 0000000..2b6fcfa
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.exceptions.stacktrace;
+
+import org.mockito.exceptions.stacktrace.StackTraceCleaner;
+import org.mockito.internal.configuration.plugins.Plugins;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class StackTraceFilter implements Serializable {
+
+ static final long serialVersionUID = -5499819791513105700L;
+
+ private static final StackTraceCleaner CLEANER =
+ Plugins.getStackTraceCleanerProvider().getStackTraceCleaner(new DefaultStackTraceCleaner());
+
+ /**
+ * Example how the filter works (+/- means good/bad):
+ * [a+, b+, c-, d+, e+, f-, g+] -> [a+, b+, d+, e+, g+]
+ * Basically removes all bad from the middle.
+ * <strike>If any good are in the middle of bad those are also removed.</strike>
+ */
+ public StackTraceElement[] filter(StackTraceElement[] target, boolean keepTop) {
+ //TODO: profile
+ //TODO: investigate "keepTop" commit history - no effect!
+ final List<StackTraceElement> filtered = new ArrayList<StackTraceElement>();
+ for (StackTraceElement element : target) {
+ if (CLEANER.isIn(element)) {
+ filtered.add(element);
+ }
+ }
+ StackTraceElement[] result = new StackTraceElement[filtered.size()];
+ return filtered.toArray(result);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/package.html b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/package.html
new file mode 100644
index 0000000..84b9ff9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/stacktrace/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Stack trace filtering / cleaning internal APIs.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/exceptions/util/ScenarioPrinter.java b/mockito-updated/src/org/mockito/internal/exceptions/util/ScenarioPrinter.java
new file mode 100644
index 0000000..5cb415f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/exceptions/util/ScenarioPrinter.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.exceptions.util;
+
+import java.util.List;
+
+import org.mockito.internal.exceptions.VerificationAwareInvocation;
+
+public class ScenarioPrinter {
+
+ public String print(List<VerificationAwareInvocation> invocations) {
+ if (invocations.size() == 1) {
+ return "Actually, above is the only interaction with this mock.";
+ }
+ StringBuilder sb = new StringBuilder(
+ "***\n" +
+ "For your reference, here is the list of all invocations ([?] - means unverified).\n");
+
+ int counter = 0;
+ for (VerificationAwareInvocation i : invocations) {
+ sb.append(++counter).append(". ");
+ if (!i.isVerified()) {
+ sb.append("[?]");
+ }
+ sb.append(i.getLocation()).append("\n");
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/framework/DefaultMockitoFramework.java b/mockito-updated/src/org/mockito/internal/framework/DefaultMockitoFramework.java
new file mode 100644
index 0000000..f507727
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/framework/DefaultMockitoFramework.java
@@ -0,0 +1,25 @@
+package org.mockito.internal.framework;
+
+import org.mockito.MockitoFramework;
+import org.mockito.listeners.MockitoListener;
+
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+
+public class DefaultMockitoFramework implements MockitoFramework {
+
+ public void addListener(MockitoListener listener) {
+ assertNotNull(listener);
+ mockingProgress().addListener(listener);
+ }
+
+ public void removeListener(MockitoListener listener) {
+ assertNotNull(listener);
+ mockingProgress().removeListener(listener);
+ }
+
+ private void assertNotNull(MockitoListener listener) {
+ if (listener == null) {
+ throw new IllegalArgumentException("listener cannot be null");
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java b/mockito-updated/src/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
new file mode 100644
index 0000000..74078d3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/hamcrest/HamcrestArgumentMatcher.java
@@ -0,0 +1,23 @@
+package org.mockito.internal.hamcrest;
+
+import org.hamcrest.Matcher;
+import org.hamcrest.StringDescription;
+import org.mockito.ArgumentMatcher;
+
+public class HamcrestArgumentMatcher<T> implements ArgumentMatcher<T> {
+
+ private final Matcher matcher;
+
+ public HamcrestArgumentMatcher(Matcher<T> matcher) {
+ this.matcher = matcher;
+ }
+
+ public boolean matches(Object argument) {
+ return this.matcher.matches(argument);
+ }
+
+ public String toString() {
+ //TODO SF add unit tests and integ test coverage for describeTo()
+ return StringDescription.toString(matcher);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java b/mockito-updated/src/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java
new file mode 100644
index 0000000..9100c20
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/hamcrest/MatcherGenericTypeExtractor.java
@@ -0,0 +1,21 @@
+package org.mockito.internal.hamcrest;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Matcher;
+
+import static org.mockito.internal.util.reflection.GenericTypeExtractor.genericTypeOf;
+
+/**
+ * Extracts generic type of matcher
+ */
+public class MatcherGenericTypeExtractor {
+
+ /**
+ * Gets the generic type of given matcher. For example,
+ * for matcher class that extends BaseMatcher[Integer] this method returns Integer
+ */
+ public static Class<?> genericTypeOfMatcher(Class<?> matcherClass) {
+ //TODO SF check if we can reuse it for Mockito ArgumentMatcher
+ return genericTypeOf(matcherClass, BaseMatcher.class, Matcher.class);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/handler/InvocationNotifierHandler.java b/mockito-updated/src/org/mockito/internal/handler/InvocationNotifierHandler.java
new file mode 100644
index 0000000..562089f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/handler/InvocationNotifierHandler.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.handler;
+
+import static org.mockito.internal.exceptions.Reporter.invocationListenerThrewException;
+
+import java.util.List;
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.MockHandler;
+import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Handler, that call all listeners wanted for this mock, before delegating it
+ * to the parameterized handler.
+ *
+ * Also imposterize MockHandlerImpl, delegate all call of InternalMockHandler to the real mockHandler
+ */
+class InvocationNotifierHandler<T> implements MockHandler, InternalMockHandler<T> {
+
+ private final List<InvocationListener> invocationListeners;
+ private final InternalMockHandler<T> mockHandler;
+
+ public InvocationNotifierHandler(InternalMockHandler<T> mockHandler, MockCreationSettings<T> settings) {
+ this.mockHandler = mockHandler;
+ this.invocationListeners = settings.getInvocationListeners();
+ }
+
+ public Object handle(Invocation invocation) throws Throwable {
+ try {
+ Object returnedValue = mockHandler.handle(invocation);
+ notifyMethodCall(invocation, returnedValue);
+ return returnedValue;
+ } catch (Throwable t){
+ notifyMethodCallException(invocation, t);
+ throw t;
+ }
+ }
+
+
+ private void notifyMethodCall(Invocation invocation, Object returnValue) {
+ for (InvocationListener listener : invocationListeners) {
+ try {
+ listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, returnValue));
+ } catch(Throwable listenerThrowable) {
+ throw invocationListenerThrewException(listener, listenerThrowable);
+ }
+ }
+ }
+
+ private void notifyMethodCallException(Invocation invocation, Throwable exception) {
+ for (InvocationListener listener : invocationListeners) {
+ try {
+ listener.reportInvocation(new NotifiedMethodInvocationReport(invocation, exception));
+ } catch(Throwable listenerThrowable) {
+ throw invocationListenerThrewException(listener, listenerThrowable);
+ }
+ }
+ }
+
+ public MockCreationSettings<T> getMockSettings() {
+ return mockHandler.getMockSettings();
+ }
+
+ public void setAnswersForStubbing(List<Answer<?>> answers) {
+ mockHandler.setAnswersForStubbing(answers);
+ }
+
+ public InvocationContainer getInvocationContainer() {
+ return mockHandler.getInvocationContainer();
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/handler/MockHandlerFactory.java b/mockito-updated/src/org/mockito/internal/handler/MockHandlerFactory.java
new file mode 100644
index 0000000..0d11243
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/handler/MockHandlerFactory.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.handler;
+
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.mock.MockCreationSettings;
+
+/**
+ * by Szczepan Faber, created at: 5/21/12
+ */
+public class MockHandlerFactory {
+
+ public static <T> InternalMockHandler<T> createMockHandler(MockCreationSettings<T> settings) {
+ InternalMockHandler<T> handler = new MockHandlerImpl<T>(settings);
+ InternalMockHandler<T> nullResultGuardian = new NullResultGuardian<T>(handler);
+ return new InvocationNotifierHandler<T>(nullResultGuardian, settings);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/handler/MockHandlerImpl.java b/mockito-updated/src/org/mockito/internal/handler/MockHandlerImpl.java
new file mode 100644
index 0000000..8a0a33e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/handler/MockHandlerImpl.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.handler;
+
+import static org.mockito.internal.exceptions.Reporter.stubPassedToVerify;
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+
+import java.util.List;
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.invocation.MatchersBinder;
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.internal.stubbing.InvocationContainerImpl;
+import org.mockito.internal.stubbing.OngoingStubbingImpl;
+import org.mockito.internal.stubbing.StubbedInvocationMatcher;
+import org.mockito.internal.stubbing.answers.AnswersValidator;
+import org.mockito.internal.verification.MockAwareVerificationMode;
+import org.mockito.internal.verification.VerificationDataImpl;
+import org.mockito.invocation.Invocation;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.Answer;
+import org.mockito.verification.VerificationMode;
+
+/**
+ * Invocation handler set on mock objects.
+ *
+ * @param <T> type of mock object to handle
+ */
+public class MockHandlerImpl<T> implements InternalMockHandler<T> {
+
+ private static final long serialVersionUID = -2917871070982574165L;
+
+ InvocationContainerImpl invocationContainerImpl;
+
+ MatchersBinder matchersBinder = new MatchersBinder();
+
+ private final MockCreationSettings<T> mockSettings;
+
+ public MockHandlerImpl(MockCreationSettings<T> mockSettings) {
+ this.mockSettings = mockSettings;
+
+ this.matchersBinder = new MatchersBinder();
+ this.invocationContainerImpl = new InvocationContainerImpl( mockSettings);
+ }
+
+ public Object handle(Invocation invocation) throws Throwable {
+ if (invocationContainerImpl.hasAnswersForStubbing()) {
+ // stubbing voids with doThrow() or doAnswer() style
+ InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
+ mockingProgress().getArgumentMatcherStorage(),
+ invocation
+ );
+ invocationContainerImpl.setMethodForStubbing(invocationMatcher);
+ return null;
+ }
+ VerificationMode verificationMode = mockingProgress().pullVerificationMode();
+
+ InvocationMatcher invocationMatcher = matchersBinder.bindMatchers(
+ mockingProgress().getArgumentMatcherStorage(),
+ invocation
+ );
+
+ mockingProgress().validateState();
+
+ // if verificationMode is not null then someone is doing verify()
+ if (verificationMode != null) {
+ // We need to check if verification was started on the correct mock
+ // - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
+ if (((MockAwareVerificationMode) verificationMode).getMock() == invocation.getMock()) {
+ VerificationDataImpl data = createVerificationData(invocationContainerImpl, invocationMatcher);
+ verificationMode.verify(data);
+ return null;
+ } else {
+ // this means there is an invocation on a different mock. Re-adding verification mode
+ // - see VerifyingWithAnExtraCallToADifferentMockTest (bug 138)
+ mockingProgress().verificationStarted(verificationMode);
+ }
+ }
+
+ // prepare invocation for stubbing
+ invocationContainerImpl.setInvocationForPotentialStubbing(invocationMatcher);
+ OngoingStubbingImpl<T> ongoingStubbing = new OngoingStubbingImpl<T>(invocationContainerImpl);
+ mockingProgress().reportOngoingStubbing(ongoingStubbing);
+
+ // look for existing answer for this invocation
+ StubbedInvocationMatcher stubbedInvocation = invocationContainerImpl.findAnswerFor(invocation);
+
+ if (stubbedInvocation != null) {
+ stubbedInvocation.captureArgumentsFrom(invocation);
+ return stubbedInvocation.answer(invocation);
+ } else {
+ Object ret = mockSettings.getDefaultAnswer().answer(invocation);
+ new AnswersValidator().validateDefaultAnswerReturnedValue(invocation, ret);
+
+ // redo setting invocation for potential stubbing in case of partial
+ // mocks / spies.
+ // Without it, the real method inside 'when' might have delegated
+ // to other self method and overwrite the intended stubbed method
+ // with a different one. The reset is required to avoid runtime exception that validates return type with stubbed method signature.
+ invocationContainerImpl.resetInvocationForPotentialStubbing(invocationMatcher);
+ return ret;
+ }
+ }
+
+ public MockCreationSettings<T> getMockSettings() {
+ return mockSettings;
+ }
+
+ public void setAnswersForStubbing(List<Answer<?>> answers) {
+ invocationContainerImpl.setAnswersForStubbing(answers);
+ }
+
+ public InvocationContainer getInvocationContainer() {
+ return invocationContainerImpl;
+ }
+
+ private VerificationDataImpl createVerificationData(InvocationContainerImpl invocationContainerImpl, InvocationMatcher invocationMatcher) {
+ if (mockSettings.isStubOnly()) {
+ throw stubPassedToVerify(); // this throws an exception
+ }
+
+ return new VerificationDataImpl(invocationContainerImpl, invocationMatcher);
+ }
+}
+
diff --git a/mockito-updated/src/org/mockito/internal/handler/NotifiedMethodInvocationReport.java b/mockito-updated/src/org/mockito/internal/handler/NotifiedMethodInvocationReport.java
new file mode 100644
index 0000000..1684f9b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/handler/NotifiedMethodInvocationReport.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.handler;
+
+import org.mockito.invocation.DescribedInvocation;
+import org.mockito.invocation.Invocation;
+import org.mockito.listeners.MethodInvocationReport;
+
+import static org.mockito.internal.matchers.Equality.areEqual;
+
+/**
+ * Report on a method call
+ */
+public class NotifiedMethodInvocationReport implements MethodInvocationReport {
+ private final Invocation invocation;
+ private final Object returnedValue;
+ private final Throwable throwable;
+
+
+ /**
+ * Build a new {@link org.mockito.listeners.MethodInvocationReport} with a return value.
+ *
+ *
+ * @param invocation Information on the method call
+ * @param returnedValue The value returned by the method invocation
+ */
+ public NotifiedMethodInvocationReport(Invocation invocation, Object returnedValue) {
+ this.invocation = invocation;
+ this.returnedValue = returnedValue;
+ this.throwable = null;
+ }
+
+ /**
+ * Build a new {@link org.mockito.listeners.MethodInvocationReport} with a return value.
+ *
+ *
+ * @param invocation Information on the method call
+ * @param throwable Tha throwable raised by the method invocation
+ */
+ public NotifiedMethodInvocationReport(Invocation invocation, Throwable throwable) {
+ this.invocation = invocation;
+ this.returnedValue = null;
+ this.throwable = throwable;
+ }
+
+ public DescribedInvocation getInvocation() {
+ return invocation;
+ }
+
+ public Object getReturnedValue() {
+ return returnedValue;
+ }
+
+ public Throwable getThrowable() {
+ return throwable;
+ }
+
+ public boolean threwException() {
+ return throwable != null;
+ }
+
+ public String getLocationOfStubbing() {
+ return (invocation.stubInfo() == null) ? null : invocation.stubInfo().stubbedAt().toString();
+ }
+
+
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ NotifiedMethodInvocationReport that = (NotifiedMethodInvocationReport) o;
+
+ return areEqual(invocation, that.invocation) &&
+ areEqual(returnedValue, that.returnedValue) &&
+ areEqual(throwable, that.throwable);
+ }
+
+ public int hashCode() {
+ int result = invocation != null ? invocation.hashCode() : 0;
+ result = 31 * result + (returnedValue != null ? returnedValue.hashCode() : 0);
+ result = 31 * result + (throwable != null ? throwable.hashCode() : 0);
+ return result;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/handler/NullResultGuardian.java b/mockito-updated/src/org/mockito/internal/handler/NullResultGuardian.java
new file mode 100644
index 0000000..9fb4d14
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/handler/NullResultGuardian.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.handler;
+
+import static org.mockito.internal.util.Primitives.defaultValue;
+
+import java.util.List;
+
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.invocation.Invocation;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Protects the results from delegate MockHandler. Makes sure the results are valid.
+ *
+ * by Szczepan Faber, created at: 5/22/12
+ */
+class NullResultGuardian<T> implements InternalMockHandler<T> {
+
+ private final InternalMockHandler<T> delegate;
+
+ public NullResultGuardian(InternalMockHandler<T> delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public Object handle(Invocation invocation) throws Throwable {
+ Object result = delegate.handle(invocation);
+ Class<?> returnType = invocation.getMethod().getReturnType();
+ if(result == null && returnType.isPrimitive()) {
+ //primitive values cannot be null
+ return defaultValue(returnType);
+ }
+ return result;
+ }
+
+ @Override
+ public MockCreationSettings<T> getMockSettings() {
+ return delegate.getMockSettings();
+ }
+
+ @Override
+ public void setAnswersForStubbing(List<Answer<?>> answers) {
+ delegate.setAnswersForStubbing(answers);
+ }
+
+ @Override
+ public InvocationContainer getInvocationContainer() {
+ return delegate.getInvocationContainer();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/AbstractAwareMethod.java b/mockito-updated/src/org/mockito/internal/invocation/AbstractAwareMethod.java
new file mode 100644
index 0000000..2b36073
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/AbstractAwareMethod.java
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation;
+
+public interface AbstractAwareMethod {
+ boolean isAbstract();
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/ArgumentMatcherAction.java b/mockito-updated/src/org/mockito/internal/invocation/ArgumentMatcherAction.java
new file mode 100644
index 0000000..29156d0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/ArgumentMatcherAction.java
@@ -0,0 +1,28 @@
+package org.mockito.internal.invocation;
+
+import org.mockito.ArgumentMatcher;
+
+public interface ArgumentMatcherAction {
+ /**
+ * Implementations must apply the given matcher to the argument and return
+ * <code>true</code> if the operation was successful or <code>false</code>
+ * if not. In this case no more matchers and arguments will be passed by
+ * {@link MatcherApplicationStrategy#forEachMatcherAndArgument(ArgumentMatcherAction)} to this method.
+ * .
+ *
+ * @param matcher
+ * to process the argument, never <code>null</code>
+ * @param argument
+ * to be processed by the matcher, can be <code>null</code>
+ * @return
+ * <ul>
+ * <li><code>true</code> if the <b>matcher</b> was successfully
+ * applied to the <b>argument</b> and the next pair of matcher and
+ * argument should be passed
+ * <li><code>false</code> otherwise
+ * </ul>
+ *
+ *
+ */
+ boolean apply(ArgumentMatcher<?> matcher, Object argument);
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/ArgumentsProcessor.java b/mockito-updated/src/org/mockito/internal/invocation/ArgumentsProcessor.java
new file mode 100644
index 0000000..a0b0550
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/ArgumentsProcessor.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.ArrayEquals;
+import org.mockito.internal.matchers.Equals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * by Szczepan Faber, created at: 3/31/12
+ */
+public class ArgumentsProcessor {
+ // expands array varArgs that are given by runtime (1, [a, b]) into true
+ // varArgs (1, a, b);
+ public static Object[] expandVarArgs(final boolean isVarArgs, final Object[] args) {
+ if (!isVarArgs || isNullOrEmpty(args) || args[args.length - 1] != null && !args[args.length - 1].getClass().isArray()) {
+ return args == null ? new Object[0] : args;
+ }
+
+ final int nonVarArgsCount = args.length - 1;
+ Object[] varArgs;
+ if (args[nonVarArgsCount] == null) {
+ // in case someone deliberately passed null varArg array
+ varArgs = new Object[] { null };
+ } else {
+ varArgs = ArrayEquals.createObjectArray(args[nonVarArgsCount]);
+ }
+ final int varArgsCount = varArgs.length;
+ Object[] newArgs = new Object[nonVarArgsCount + varArgsCount];
+ System.arraycopy(args, 0, newArgs, 0, nonVarArgsCount);
+ System.arraycopy(varArgs, 0, newArgs, nonVarArgsCount, varArgsCount);
+ return newArgs;
+ }
+
+ private static <T> boolean isNullOrEmpty(T[] array) {
+ return array == null || array.length == 0;
+ }
+
+ public static List<ArgumentMatcher> argumentsToMatchers(Object[] arguments) {
+ List<ArgumentMatcher> matchers = new ArrayList<ArgumentMatcher>(arguments.length);
+ for (Object arg : arguments) {
+ if (arg != null && arg.getClass().isArray()) {
+ matchers.add(new ArrayEquals(arg));
+ } else {
+ matchers.add(new Equals(arg));
+ }
+ }
+ return matchers;
+ }
+
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java b/mockito-updated/src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java
new file mode 100644
index 0000000..ef7bde4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/CapturesArgumentsFromInvocation.java
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+
+import org.mockito.invocation.Invocation;
+
+public interface CapturesArgumentsFromInvocation {
+
+ void captureArgumentsFrom(Invocation i);
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/InvocationComparator.java b/mockito-updated/src/org/mockito/internal/invocation/InvocationComparator.java
new file mode 100644
index 0000000..901fc48
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/InvocationComparator.java
@@ -0,0 +1,14 @@
+package org.mockito.internal.invocation;
+
+import org.mockito.invocation.Invocation;
+
+import java.util.Comparator;
+
+/**
+ * Compares invocations based on the sequence number
+ */
+public class InvocationComparator implements Comparator<Invocation> {
+ public int compare(Invocation o1, Invocation o2) {
+ return Integer.valueOf(o1.getSequenceNumber()).compareTo(o2.getSequenceNumber());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/InvocationImpl.java b/mockito-updated/src/org/mockito/internal/invocation/InvocationImpl.java
new file mode 100644
index 0000000..a728a0c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/InvocationImpl.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation;
+
+import org.mockito.internal.exceptions.VerificationAwareInvocation;
+import org.mockito.internal.invocation.realmethod.RealMethod;
+import org.mockito.internal.reporting.PrintSettings;
+import org.mockito.invocation.*;
+
+import static org.mockito.internal.exceptions.Reporter.cannotCallAbstractRealMethod;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+
+/**
+ * Method call on a mock object.
+ * <p>
+ * Contains sequence number which should be globally unique and is used for
+ * verification in order.
+ * <p>
+ * Contains stack trace of invocation
+ */
+@SuppressWarnings("unchecked")
+public class InvocationImpl implements Invocation, VerificationAwareInvocation {
+
+ private static final long serialVersionUID = 8240069639250980199L;
+ private final int sequenceNumber;
+ private final Object mock;
+ private final MockitoMethod method;
+ private final Object[] arguments;
+ private final Object[] rawArguments;
+
+ private final Location location;
+ private boolean verified;
+ private boolean isIgnoredForVerification;
+
+ final RealMethod realMethod;
+ private StubInfo stubInfo;
+
+ public InvocationImpl(Object mock, MockitoMethod mockitoMethod, Object[] args, int sequenceNumber,
+ RealMethod realMethod, Location location) {
+ this.method = mockitoMethod;
+ this.mock = mock;
+ this.realMethod = realMethod;
+ this.arguments = ArgumentsProcessor.expandVarArgs(mockitoMethod.isVarArgs(), args);
+ this.rawArguments = args;
+ this.sequenceNumber = sequenceNumber;
+ this.location = location;
+ }
+
+ public Object getMock() {
+ return mock;
+ }
+
+ public Method getMethod() {
+ return method.getJavaMethod();
+ }
+
+ public Object[] getArguments() {
+ return arguments;
+ }
+
+ public <T> T getArgument(int index) {
+ return (T)arguments[index];
+ }
+
+ public boolean isVerified() {
+ return verified || isIgnoredForVerification;
+ }
+
+ public int getSequenceNumber() {
+ return sequenceNumber;
+ }
+
+ public boolean equals(Object o) {
+ if (o == null || !o.getClass().equals(this.getClass())) {
+ return false;
+ }
+
+ InvocationImpl other = (InvocationImpl) o;
+
+ return this.mock.equals(other.mock) && this.method.equals(other.method) && this.equalArguments(other.arguments);
+ }
+
+ private boolean equalArguments(Object[] arguments) {
+ return Arrays.equals(arguments, this.arguments);
+ }
+
+ @Override
+ public int hashCode() {
+ return 1;
+ }
+
+ public String toString() {
+ return new PrintSettings().print(ArgumentsProcessor.argumentsToMatchers(getArguments()), this);
+ }
+
+ public Location getLocation() {
+ return location;
+ }
+
+ public Object[] getRawArguments() {
+ return this.rawArguments;
+ }
+
+ public Class<?> getRawReturnType() {
+ return method.getReturnType();
+ }
+
+ public Object callRealMethod() throws Throwable {
+ if (method.isAbstract()) {
+ throw cannotCallAbstractRealMethod();
+ }
+ return realMethod.invoke(mock, rawArguments);
+ }
+
+ public void markVerified() {
+ this.verified = true;
+ }
+
+ public StubInfo stubInfo() {
+ return stubInfo;
+ }
+
+ public void markStubbed(StubInfo stubInfo) {
+ this.stubInfo = stubInfo;
+ }
+
+ public boolean isIgnoredForVerification() {
+ return isIgnoredForVerification;
+ }
+
+ public void ignoreForVerification() {
+ isIgnoredForVerification = true;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/InvocationMarker.java b/mockito-updated/src/org/mockito/internal/invocation/InvocationMarker.java
new file mode 100644
index 0000000..f05a221
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/InvocationMarker.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.invocation.Invocation;
+
+import java.util.List;
+
+public class InvocationMarker {
+
+ private InvocationMarker(){}
+
+ public static void markVerified(List<Invocation> invocations, CapturesArgumentsFromInvocation wanted) {
+ for (Invocation invocation : invocations) {
+ markVerified(invocation, wanted);
+ }
+ }
+
+ public static void markVerified(Invocation invocation, CapturesArgumentsFromInvocation wanted) {
+ invocation.markVerified();
+ wanted.captureArgumentsFrom(invocation);
+ }
+
+ public static void markVerifiedInOrder(List<Invocation> chunk, CapturesArgumentsFromInvocation wanted, InOrderContext context) {
+ markVerified(chunk, wanted);
+
+ for (Invocation i : chunk) {
+ context.markVerified(i);
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/InvocationMatcher.java b/mockito-updated/src/org/mockito/internal/invocation/InvocationMatcher.java
new file mode 100644
index 0000000..d955b70
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/InvocationMatcher.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+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;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.CapturesArguments;
+import org.mockito.internal.reporting.PrintSettings;
+import org.mockito.invocation.DescribedInvocation;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
+
+/**
+ * In addition to all content of the invocation, the invocation matcher contains the argument matchers. Invocation matcher is used during verification and stubbing. In those cases, the user can provide argument matchers instead of 'raw' arguments. Raw arguments are converted to 'equals' matchers anyway.
+ */
+@SuppressWarnings("serial")
+public class InvocationMatcher implements DescribedInvocation, CapturesArgumentsFromInvocation, Serializable {
+
+ private final Invocation invocation;
+ private final List<ArgumentMatcher<?>> matchers;
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public InvocationMatcher(Invocation invocation, List<ArgumentMatcher> matchers) {
+ this.invocation = invocation;
+ if (matchers.isEmpty()) {
+ this.matchers = (List) argumentsToMatchers(invocation.getArguments());
+ } else {
+ this.matchers = (List) matchers;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ public InvocationMatcher(Invocation invocation) {
+ this(invocation, Collections.<ArgumentMatcher> emptyList());
+ }
+
+ public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
+ LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();
+ for (Invocation i : invocations) {
+ out.add(new InvocationMatcher(i));
+ }
+ return out;
+ }
+
+ public Method getMethod() {
+ return invocation.getMethod();
+ }
+
+ public Invocation getInvocation() {
+ return invocation;
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public List<ArgumentMatcher> getMatchers() {
+ return (List) matchers;
+ }
+
+ @Override
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public String toString() {
+ return new PrintSettings().print((List) matchers, invocation);
+ }
+
+ public boolean matches(Invocation actual) {
+ return invocation.getMock().equals(actual.getMock()) && hasSameMethod(actual) && argumentsMatch(actual);
+ }
+
+ /**
+ * similar means the same method name, same mock, unverified and: if arguments are the same cannot be overloaded
+ */
+ public boolean hasSimilarMethod(Invocation candidate) {
+ String wantedMethodName = getMethod().getName();
+ String candidateMethodName = candidate.getMethod().getName();
+
+ if (!wantedMethodName.equals(candidateMethodName)) {
+ return false;
+ }
+ if (candidate.isVerified()) {
+ return false;
+ }
+ if (getInvocation().getMock() != candidate.getMock()) {
+ return false;
+ }
+ if (hasSameMethod(candidate)) {
+ return true;
+ }
+
+ return !argumentsMatch(candidate);
+ }
+
+ public boolean hasSameMethod(Invocation candidate) {
+ // not using method.equals() for 1 good reason:
+ // sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
+ Method m1 = invocation.getMethod();
+ Method m2 = candidate.getMethod();
+
+ if (m1.getName() != null && m1.getName().equals(m2.getName())) {
+ /* Avoid unnecessary cloning */
+ Class<?>[] params1 = m1.getParameterTypes();
+ Class<?>[] params2 = m2.getParameterTypes();
+ if (params1.length == params2.length) {
+ for (int i = 0; i < params1.length; i++) {
+ if (params1[i] != params2[i])
+ return false;
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public Location getLocation() {
+ return invocation.getLocation();
+ }
+
+ @Override
+ public void captureArgumentsFrom(Invocation invocation) {
+ MatcherApplicationStrategy strategy = getMatcherApplicationStrategyFor(invocation, matchers);
+ strategy.forEachMatcherAndArgument(captureArgument());
+ }
+
+ private ArgumentMatcherAction captureArgument() {
+ return new ArgumentMatcherAction() {
+
+ @Override
+ public boolean apply(ArgumentMatcher<?> matcher, Object argument) {
+ if (matcher instanceof CapturesArguments) {
+ ((CapturesArguments) matcher).captureFrom(argument);
+ }
+
+ return true;
+ }
+ };
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private boolean argumentsMatch(Invocation actual) {
+ List matchers = getMatchers();
+ return getMatcherApplicationStrategyFor(actual, matchers).forEachMatcherAndArgument( matchesTypeSafe());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/InvocationsFinder.java b/mockito-updated/src/org/mockito/internal/invocation/InvocationsFinder.java
new file mode 100644
index 0000000..dec0876
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/InvocationsFinder.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.mockito.internal.util.collections.ListUtil;
+import org.mockito.internal.util.collections.ListUtil.Filter;
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
+
+public class InvocationsFinder {
+
+ private InvocationsFinder() {
+ }
+
+ public static List<Invocation> findInvocations(List<Invocation> invocations, InvocationMatcher wanted) {
+ return ListUtil.filter(invocations, new RemoveNotMatching(wanted));
+ }
+
+ public static List<Invocation> findAllMatchingUnverifiedChunks(List<Invocation> invocations, InvocationMatcher wanted, InOrderContext orderingContext) {
+ List<Invocation> unverified = removeVerifiedInOrder(invocations, orderingContext);
+ return ListUtil.filter(unverified, new RemoveNotMatching(wanted));
+ }
+
+ /**
+ * some examples how it works:
+ *
+ * Given invocations sequence:
+ * 1,1,2,1
+ *
+ * if wanted is 1 and mode is times(2) then returns
+ * 1,1
+ *
+ * if wanted is 1 and mode is atLeast() then returns
+ * 1,1,1
+ *
+ * if wanted is 1 and mode is times(x), where x != 2 then returns
+ * 1,1,1
+ */
+ public static List<Invocation> findMatchingChunk(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount, InOrderContext context) {
+ List<Invocation> unverified = removeVerifiedInOrder(invocations, context);
+ List<Invocation> firstChunk = getFirstMatchingChunk(wanted, unverified);
+
+ if (wantedCount != firstChunk.size()) {
+ return findAllMatchingUnverifiedChunks(invocations, wanted, context);
+ } else {
+ return firstChunk;
+ }
+ }
+
+ private static List<Invocation> getFirstMatchingChunk(InvocationMatcher wanted, List<Invocation> unverified) {
+ List<Invocation> firstChunk = new LinkedList<Invocation>();
+ for (Invocation invocation : unverified) {
+ if (wanted.matches(invocation)) {
+ firstChunk.add(invocation);
+ } else if (!firstChunk.isEmpty()) {
+ break;
+ }
+ }
+ return firstChunk;
+ }
+
+ public static Invocation findFirstMatchingUnverifiedInvocation( List<Invocation> invocations, InvocationMatcher wanted, InOrderContext context ){
+ for( Invocation invocation : removeVerifiedInOrder( invocations, context )){
+ if( wanted.matches( invocation )){
+ return invocation;
+ }
+ }
+ return null;
+ }
+
+ public static Invocation findSimilarInvocation(List<Invocation> invocations, InvocationMatcher wanted) {
+ Invocation firstSimilar = null;
+ for (Invocation invocation : invocations) {
+ if (!wanted.hasSimilarMethod(invocation)) {
+ continue;
+ }
+ if (firstSimilar == null) {
+ firstSimilar = invocation;
+ }
+ if (wanted.hasSameMethod(invocation)) {
+ return invocation;
+ }
+ }
+
+ return firstSimilar;
+ }
+
+ public static Invocation findFirstUnverified(List<Invocation> invocations) {
+ return findFirstUnverified(invocations, null);
+ }
+
+ static Invocation findFirstUnverified(List<Invocation> invocations, Object mock) {
+ for (Invocation i : invocations) {
+ boolean mockIsValid = mock == null || mock == i.getMock();
+ if (!i.isVerified() && mockIsValid) {
+ return i;
+ }
+ }
+ return null;
+ }
+
+ public static Location getLastLocation(List<Invocation> invocations) {
+ if (invocations.isEmpty()) {
+ return null;
+ } else {
+ Invocation last = invocations.get(invocations.size() - 1);
+ return last.getLocation();
+ }
+ }
+
+ public static Invocation findPreviousVerifiedInOrder(List<Invocation> invocations, InOrderContext context) {
+ LinkedList<Invocation> verifiedOnly = ListUtil.filter(invocations, new RemoveUnverifiedInOrder(context));
+
+ if (verifiedOnly.isEmpty()) {
+ return null;
+ } else {
+ return verifiedOnly.getLast();
+ }
+ }
+
+ private static List<Invocation> removeVerifiedInOrder(List<Invocation> invocations, InOrderContext orderingContext) {
+ List<Invocation> unverified = new LinkedList<Invocation>();
+ for (Invocation i : invocations) {
+ if (orderingContext.isVerified(i)) {
+ unverified.clear();
+ } else {
+ unverified.add(i);
+ }
+ }
+ return unverified;
+ }
+
+ private static class RemoveNotMatching implements Filter<Invocation> {
+ private final InvocationMatcher wanted;
+
+ private RemoveNotMatching(InvocationMatcher wanted) {
+ this.wanted = wanted;
+ }
+
+ public boolean isOut(Invocation invocation) {
+ return !wanted.matches(invocation);
+ }
+ }
+
+ private static class RemoveUnverifiedInOrder implements Filter<Invocation> {
+ private final InOrderContext orderingContext;
+
+ public RemoveUnverifiedInOrder(InOrderContext orderingContext) {
+ this.orderingContext = orderingContext;
+ }
+
+ public boolean isOut(Invocation invocation) {
+ return !orderingContext.isVerified(invocation);
+ }
+ }
+
+ /**
+ * i3 is unverified here:
+ *
+ * i1, i2, i3
+ * v
+ *
+ * all good here:
+ *
+ * i1, i2, i3
+ * v v
+ *
+ * @param context
+ * @param orderedInvocations
+ */
+ public static Invocation findFirstUnverifiedInOrder(InOrderContext context, List<Invocation> orderedInvocations) {
+ Invocation candidate = null;
+ for(Invocation i : orderedInvocations) {
+ if (!context.isVerified(i)) {
+ candidate = candidate != null ? candidate : i;
+ } else {
+ candidate = null;
+ }
+ }
+ return candidate;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/MatcherApplicationStrategy.java b/mockito-updated/src/org/mockito/internal/invocation/MatcherApplicationStrategy.java
new file mode 100644
index 0000000..1948177
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/MatcherApplicationStrategy.java
@@ -0,0 +1,129 @@
+package org.mockito.internal.invocation;
+
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.MATCH_EACH_VARARGS_WITH_LAST_MATCHER;
+import static org.mockito.internal.invocation.MatcherApplicationStrategy.MatcherApplicationType.ONE_MATCHER_PER_ARGUMENT;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.CapturingMatcher;
+import org.mockito.internal.matchers.VarargMatcher;
+import org.mockito.invocation.Invocation;
+
+public class MatcherApplicationStrategy {
+
+ private final Invocation invocation;
+ private final List<ArgumentMatcher<?>> matchers;
+ private final MatcherApplicationType matchingType;
+
+
+
+ private MatcherApplicationStrategy(Invocation invocation, List<ArgumentMatcher<?>> matchers, MatcherApplicationType matchingType) {
+ this.invocation = invocation;
+ if (matchingType == MATCH_EACH_VARARGS_WITH_LAST_MATCHER) {
+ int times = varargLength(invocation);
+ this.matchers = appendLastMatcherNTimes(matchers, times);
+ } else {
+ this.matchers = matchers;
+ }
+
+ this.matchingType = matchingType;
+ }
+
+ /**
+ * Returns the {@link MatcherApplicationStrategy} that must be used to capture the
+ * arguments of the given <b>invocation</b> using the given <b>matchers</b>.
+ *
+ * @param invocation
+ * that contain the arguments to capture
+ * @param matchers
+ * that will be used to capture the arguments of the invocation,
+ * the passed {@link List} is not required to contain a
+ * {@link CapturingMatcher}
+ * @return never <code>null</code>
+ */
+ public static MatcherApplicationStrategy getMatcherApplicationStrategyFor(Invocation invocation, List<ArgumentMatcher<?>> matchers) {
+
+ MatcherApplicationType type = getMatcherApplicationType(invocation, matchers);
+ return new MatcherApplicationStrategy(invocation, matchers, type);
+ }
+
+ /**
+ * Applies the given {@link ArgumentMatcherAction} to all arguments and
+ * corresponding matchers
+ *
+ * @param action
+ * must not be <code>null</code>
+ * @return
+ * <ul>
+ * <li><code>true</code> if the given <b>action</b> returned
+ * <code>true</code> for all arguments and matchers passed to it.
+ * <li><code>false</code> if the given <b>action</b> returned
+ * <code>false</code> for one of the passed arguments and matchers
+ * <li><code>false</code> if the given matchers don't fit to the given invocation
+ * because too many or to few matchers are available.
+ * </ul>
+ */
+ public boolean forEachMatcherAndArgument(ArgumentMatcherAction action) {
+ if (matchingType == ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS)
+ return false;
+
+ Object[] arguments = invocation.getArguments();
+ for (int i = 0; i < arguments.length; i++) {
+ ArgumentMatcher<?> matcher = matchers.get(i);
+ Object argument = arguments[i];
+
+ if (!action.apply(matcher, argument)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static MatcherApplicationType getMatcherApplicationType(Invocation invocation, List<ArgumentMatcher<?>> matchers) {
+ final int rawArguments = invocation.getRawArguments() != null
+ ? invocation.getRawArguments().length : 0;
+ final int expandedArguments = invocation.getArguments().length;
+ final int matcherCount = matchers.size();
+
+ if (expandedArguments == matcherCount) {
+ return ONE_MATCHER_PER_ARGUMENT;
+ }
+
+ if (rawArguments == matcherCount && isLastMatcherVargargMatcher(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 List<ArgumentMatcher<?>> appendLastMatcherNTimes(List<ArgumentMatcher<?>> matchers, int timesToAppendLastMatcher) {
+ ArgumentMatcher<?> lastMatcher = lastMatcher(matchers);
+
+ List<ArgumentMatcher<?>> expandedMatchers = new ArrayList<ArgumentMatcher<?>>(matchers);
+ for (int i = 0; i < timesToAppendLastMatcher; i++) {
+ expandedMatchers.add(lastMatcher);
+ }
+ return expandedMatchers;
+ }
+
+ private static int varargLength(Invocation invocation) {
+ int rawArgumentCount = invocation.getRawArguments().length;
+ int expandedArgumentCount = invocation.getArguments().length;
+ return expandedArgumentCount - rawArgumentCount;
+ }
+
+ private static ArgumentMatcher<?> lastMatcher(List<ArgumentMatcher<?>> matchers) {
+ return matchers.get(matchers.size() - 1);
+ }
+
+ enum MatcherApplicationType {
+ ONE_MATCHER_PER_ARGUMENT, MATCH_EACH_VARARGS_WITH_LAST_MATCHER, ERROR_UNSUPPORTED_NUMBER_OF_MATCHERS;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/MatchersBinder.java b/mockito-updated/src/org/mockito/internal/invocation/MatchersBinder.java
new file mode 100644
index 0000000..8a01d2c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/MatchersBinder.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation;
+
+
+import static org.mockito.internal.exceptions.Reporter.invalidUseOfMatchers;
+
+import java.io.Serializable;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.LocalizedMatcher;
+import org.mockito.internal.progress.ArgumentMatcherStorage;
+import org.mockito.invocation.Invocation;
+
+@SuppressWarnings("unchecked")
+public class MatchersBinder implements Serializable {
+
+ public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
+ List<LocalizedMatcher> lastMatchers = argumentMatcherStorage.pullLocalizedMatchers();
+ validateMatchers(invocation, lastMatchers);
+
+ List<ArgumentMatcher> matchers = new LinkedList<ArgumentMatcher>();
+ for (LocalizedMatcher m : lastMatchers) {
+ matchers.add(m.getMatcher());
+ }
+ return new InvocationMatcher(invocation, matchers);
+ }
+
+ private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) {
+ if (!lastMatchers.isEmpty()) {
+ int recordedMatchersSize = lastMatchers.size();
+ int expectedMatchersSize = invocation.getArguments().length;
+ if (expectedMatchersSize != recordedMatchersSize) {
+ throw invalidUseOfMatchers(expectedMatchersSize, lastMatchers);
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/MockitoMethod.java b/mockito-updated/src/org/mockito/internal/invocation/MockitoMethod.java
new file mode 100644
index 0000000..69637c9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/MockitoMethod.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import java.lang.reflect.Method;
+
+public interface MockitoMethod extends AbstractAwareMethod {
+
+ String getName();
+
+ Class<?> getReturnType();
+
+ Class<?>[] getParameterTypes();
+
+ Class<?>[] getExceptionTypes();
+
+ boolean isVarArgs();
+
+ Method getJavaMethod();
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/SerializableMethod.java b/mockito-updated/src/org/mockito/internal/invocation/SerializableMethod.java
new file mode 100644
index 0000000..5dc8e70
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/SerializableMethod.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import org.mockito.exceptions.base.MockitoException;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+
+public class SerializableMethod implements Serializable, MockitoMethod {
+
+ private static final long serialVersionUID = 6005610965006048445L;
+
+ private final Class<?> declaringClass;
+ private final String methodName;
+ private final Class<?>[] parameterTypes;
+ private final Class<?> returnType;
+ private final Class<?>[] exceptionTypes;
+ private final boolean isVarArgs;
+ private final boolean isAbstract;
+
+ private volatile transient Method method;
+
+ public SerializableMethod(Method method) {
+ this.method = method;
+ declaringClass = method.getDeclaringClass();
+ methodName = method.getName();
+ parameterTypes = method.getParameterTypes();
+ returnType = method.getReturnType();
+ exceptionTypes = method.getExceptionTypes();
+ isVarArgs = method.isVarArgs();
+ isAbstract = (method.getModifiers() & Modifier.ABSTRACT) != 0;
+ }
+
+ public String getName() {
+ return methodName;
+ }
+
+ public Class<?> getReturnType() {
+ return returnType;
+ }
+
+ public Class<?>[] getParameterTypes() {
+ return parameterTypes;
+ }
+
+ public Class<?>[] getExceptionTypes() {
+ return exceptionTypes;
+ }
+
+ public boolean isVarArgs() {
+ return isVarArgs;
+ }
+
+ public boolean isAbstract() {
+ return isAbstract;
+ }
+
+ public Method getJavaMethod() {
+ if (method != null) {
+ return method;
+ }
+ try {
+ method = declaringClass.getDeclaredMethod(methodName, parameterTypes);
+ return method;
+ } catch (SecurityException e) {
+ String message = String.format(
+ "The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" +
+ "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName);
+ throw new MockitoException(message, e);
+ } catch (NoSuchMethodException e) {
+ String message = String.format(
+ "The method %1$s.%2$s does not exists and you should not get to this point.\n" +
+ "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName);
+ throw new MockitoException(message, e);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return 1;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ SerializableMethod other = (SerializableMethod) obj;
+ if (declaringClass == null) {
+ if (other.declaringClass != null)
+ return false;
+ } else if (!declaringClass.equals(other.declaringClass))
+ return false;
+ if (methodName == null) {
+ if (other.methodName != null)
+ return false;
+ } else if (!methodName.equals(other.methodName))
+ return false;
+ if (!Arrays.equals(parameterTypes, other.parameterTypes))
+ return false;
+ if (returnType == null) {
+ if (other.returnType != null)
+ return false;
+ } else if (!returnType.equals(other.returnType))
+ return false;
+ return true;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/StubInfoImpl.java b/mockito-updated/src/org/mockito/internal/invocation/StubInfoImpl.java
new file mode 100644
index 0000000..6245211
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/StubInfoImpl.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import org.mockito.invocation.DescribedInvocation;
+import org.mockito.invocation.Location;
+import org.mockito.invocation.StubInfo;
+
+import java.io.Serializable;
+
+public class StubInfoImpl implements StubInfo, Serializable {
+ private static final long serialVersionUID = 2125827349332068867L;
+ private final DescribedInvocation stubbedAt;
+
+ public StubInfoImpl(DescribedInvocation stubbedAt) {
+ this.stubbedAt = stubbedAt;
+ }
+
+ public Location stubbedAt() {
+ return stubbedAt.getLocation();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/TypeSafeMatching.java b/mockito-updated/src/org/mockito/internal/invocation/TypeSafeMatching.java
new file mode 100644
index 0000000..181e47f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/TypeSafeMatching.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation;
+
+import java.lang.reflect.Method;
+
+import org.mockito.ArgumentMatcher;
+
+@SuppressWarnings({"unchecked","rawtypes"})
+public class TypeSafeMatching implements ArgumentMatcherAction {
+
+ private final static ArgumentMatcherAction TYPE_SAFE_MATCHING_ACTION = new TypeSafeMatching();
+
+ private TypeSafeMatching() {}
+
+
+ public static ArgumentMatcherAction matchesTypeSafe(){
+ return TYPE_SAFE_MATCHING_ACTION;
+ }
+ @Override
+ public boolean apply(ArgumentMatcher matcher, Object argument) {
+ return isCompatible(matcher, argument) && matcher.matches(argument);
+ }
+
+
+ /**
+ * Returns <code>true</code> if the given <b>argument</b> can be passed to
+ * the given <code>argumentMatcher</code> without causing a
+ * {@link ClassCastException}.
+ */
+ private static boolean isCompatible(ArgumentMatcher<?> argumentMatcher, Object argument) {
+ if (argument == null)
+ return true;
+
+ Class<?> expectedArgumentType = getArgumentType(argumentMatcher);
+
+ return expectedArgumentType.isInstance(argument);
+ }
+
+ /**
+ * Returns the type of {@link ArgumentMatcher#matches(Object)} of the given
+ * {@link ArgumentMatcher} implementation.
+ */
+ private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) {
+ Method[] methods = argumentMatcher.getClass().getMethods();
+
+ for (Method method : methods) {
+ if (isMatchesMethod(method)) {
+ return method.getParameterTypes()[0];
+ }
+ }
+ throw new NoSuchMethodError("Method 'matches(T)' not found in ArgumentMatcher: " + argumentMatcher + " !\r\n Please file a bug with this stack trace at: https://github.com/mockito/mockito/issues/new ");
+ }
+
+ /**
+ * Returns <code>true</code> if the given method is
+ * {@link ArgumentMatcher#matches(Object)}
+ */
+ private static boolean isMatchesMethod(Method method) {
+ if (method.getParameterTypes().length != 1) {
+ return false;
+ }
+ if (method.isBridge()) {
+ return false;
+ }
+ return method.getName().equals("matches");
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/UnusedStubsFinder.java b/mockito-updated/src/org/mockito/internal/invocation/UnusedStubsFinder.java
new file mode 100644
index 0000000..21d3b27
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/UnusedStubsFinder.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation;
+
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.stubbing.StubbedInvocationMatcher;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.invocation.Invocation;
+
+import java.util.*;
+
+@Deprecated
+public class UnusedStubsFinder {
+
+ /**
+ * Finds all unused stubs for given mocks
+ *
+ * @param mocks full list of mocks
+ */
+ public List<Invocation> find(List<?> mocks) {
+ List<Invocation> unused = new LinkedList<Invocation>();
+ for (Object mock : mocks) {
+ InternalMockHandler<Object> handler = MockUtil.getMockHandler(mock);
+ List<StubbedInvocationMatcher> fromSingleMock = handler.getInvocationContainer().getStubbedInvocations();
+ for(StubbedInvocationMatcher s : fromSingleMock) {
+ if (!s.wasUsed()) {
+ unused.add(s.getInvocation());
+ }
+ }
+ }
+ return unused;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/finder/AllInvocationsFinder.java b/mockito-updated/src/org/mockito/internal/invocation/finder/AllInvocationsFinder.java
new file mode 100644
index 0000000..4dbe868
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/finder/AllInvocationsFinder.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation.finder;
+
+import org.mockito.internal.invocation.InvocationComparator;
+import org.mockito.stubbing.Stubbing;
+import org.mockito.internal.stubbing.StubbingComparator;
+import org.mockito.internal.util.DefaultMockingDetails;
+import org.mockito.invocation.Invocation;
+
+import java.util.*;
+
+public class AllInvocationsFinder {
+
+ private AllInvocationsFinder() {}
+
+ /**
+ * gets all invocations from mocks. Invocations are ordered earlier first.
+ *
+ * @param mocks mocks
+ * @return invocations
+ */
+ public static List<Invocation> find(Iterable<?> mocks) {
+ Set<Invocation> invocationsInOrder = new TreeSet<Invocation>(new InvocationComparator());
+ for (Object mock : mocks) {
+ Collection<Invocation> fromSingleMock = new DefaultMockingDetails(mock).getInvocations();
+ invocationsInOrder.addAll(fromSingleMock);
+ }
+
+ return new LinkedList<Invocation>(invocationsInOrder);
+ }
+
+ /**
+ * Gets all stubbings from mocks. Invocations are ordered earlier first.
+ *
+ * @param mocks mocks
+ * @return stubbings
+ */
+ public static Set<Stubbing> findStubbings(Iterable<?> mocks) {
+ Set<Stubbing> stubbings = new TreeSet<Stubbing>(new StubbingComparator());
+ for (Object mock : mocks) {
+ Collection<? extends Stubbing> fromSingleMock = new DefaultMockingDetails(mock).getStubbings();
+ stubbings.addAll(fromSingleMock);
+ }
+
+ return stubbings;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java b/mockito-updated/src/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java
new file mode 100644
index 0000000..819c7e0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/finder/VerifiableInvocationsFinder.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.invocation.finder;
+
+import org.mockito.internal.util.collections.ListUtil;
+import org.mockito.internal.util.collections.ListUtil.Filter;
+import org.mockito.invocation.Invocation;
+
+import java.util.List;
+
+/**
+ * Author: Szczepan Faber, created at: 4/3/11
+ */
+public class VerifiableInvocationsFinder {
+
+ private VerifiableInvocationsFinder() {}
+
+ public static List<Invocation> find(List<?> mocks) {
+ List<Invocation> invocations = AllInvocationsFinder.find(mocks);
+ return ListUtil.filter(invocations, new RemoveIgnoredForVerification());
+ }
+
+ private static class RemoveIgnoredForVerification implements Filter<Invocation>{
+ public boolean isOut(Invocation invocation) {
+ return invocation.isIgnoredForVerification();
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/package.html b/mockito-updated/src/org/mockito/internal/invocation/package.html
new file mode 100644
index 0000000..4ed1db4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Invocation and related classes.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/realmethod/CleanTraceRealMethod.java b/mockito-updated/src/org/mockito/internal/invocation/realmethod/CleanTraceRealMethod.java
new file mode 100644
index 0000000..b7964e8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/realmethod/CleanTraceRealMethod.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation.realmethod;
+
+import org.mockito.internal.creation.util.MockitoMethodProxy;
+import org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter;
+
+import java.io.Serializable;
+
+/**
+ * Provides stack trace filtering on exception.
+ */
+public class CleanTraceRealMethod implements RealMethod, Serializable {
+
+ private static final long serialVersionUID = 3596550785818938496L;
+ private final RealMethod realMethod;
+
+ public CleanTraceRealMethod(MockitoMethodProxy methodProxy) {
+ this(new DefaultRealMethod(methodProxy));
+ }
+
+ public CleanTraceRealMethod(RealMethod realMethod) {
+ this.realMethod = realMethod;
+ }
+
+ public Object invoke(Object target, Object[] arguments) throws Throwable {
+ try {
+ return realMethod.invoke(target, arguments);
+ } catch (Throwable t) {
+ new ConditionalStackTraceFilter().filter(t);
+ throw t;
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/invocation/realmethod/DefaultRealMethod.java b/mockito-updated/src/org/mockito/internal/invocation/realmethod/DefaultRealMethod.java
new file mode 100644
index 0000000..49ad30a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/realmethod/DefaultRealMethod.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation.realmethod;
+
+import org.mockito.internal.creation.util.MockitoMethodProxy;
+
+import java.io.Serializable;
+
+public class DefaultRealMethod implements RealMethod, Serializable {
+
+ private static final long serialVersionUID = -4596470901191501582L;
+ private final MockitoMethodProxy methodProxy;
+
+ public DefaultRealMethod(MockitoMethodProxy methodProxy) {
+ this.methodProxy = methodProxy;
+ }
+
+ public Object invoke(Object target, Object[] arguments) throws Throwable {
+ return methodProxy.invokeSuper(target, arguments);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/realmethod/RealMethod.java b/mockito-updated/src/org/mockito/internal/invocation/realmethod/RealMethod.java
new file mode 100644
index 0000000..60ebc87
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/realmethod/RealMethod.java
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.invocation.realmethod;
+
+public interface RealMethod {
+
+ Object invoke(Object target, Object[] arguments) throws Throwable;
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/invocation/realmethod/package.html b/mockito-updated/src/org/mockito/internal/invocation/realmethod/package.html
new file mode 100644
index 0000000..d89c54f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/invocation/realmethod/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+implementations of real method calls
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/junit/ArgMismatchFinder.java b/mockito-updated/src/org/mockito/internal/junit/ArgMismatchFinder.java
new file mode 100644
index 0000000..44ac59d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/ArgMismatchFinder.java
@@ -0,0 +1,28 @@
+package org.mockito.internal.junit;
+
+import org.mockito.internal.invocation.finder.AllInvocationsFinder;
+import org.mockito.invocation.Invocation;
+import org.mockito.stubbing.Stubbing;
+
+/**
+ * For given mocks, finds stubbing arg mismatches
+ */
+class ArgMismatchFinder {
+
+ StubbingArgMismatches getStubbingArgMismatches(Iterable<Object> mocks) {
+ StubbingArgMismatches mismatches = new StubbingArgMismatches();
+ for (Invocation i : AllInvocationsFinder.find(mocks)) {
+ if (i.stubInfo() != null) {
+ continue;
+ }
+ for (Stubbing stubbing : AllInvocationsFinder.findStubbings(mocks)) {
+ //method name & mock matches
+ if (!stubbing.wasUsed() && stubbing.getInvocation().getMock() == i.getMock()
+ && stubbing.getInvocation().getMethod().getName().equals(i.getMethod().getName())) {
+ mismatches.add(i, stubbing.getInvocation());
+ }
+ }
+ }
+ return mismatches;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/FriendlyExceptionMaker.java b/mockito-updated/src/org/mockito/internal/junit/FriendlyExceptionMaker.java
new file mode 100644
index 0000000..2900f72
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/FriendlyExceptionMaker.java
@@ -0,0 +1,31 @@
+package org.mockito.internal.junit;
+
+import org.mockito.exceptions.verification.ArgumentsAreDifferent;
+
+/**
+ * If JUnit is used, we can use an exception that extends from ComparisonFailure
+ * and hence provide a better IDE support as the comparison result is comparable
+ */
+class FriendlyExceptionMaker {
+
+ private final JUnitDetecter detecter;
+
+ FriendlyExceptionMaker(JUnitDetecter detecter) {
+ this.detecter = detecter;
+ }
+
+ //TODO SF this can be now unit tested
+ public AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
+ if (!detecter.hasJUnit()) {
+ return new ArgumentsAreDifferent(message);
+ }
+
+ try {
+ Class<?> clazz = Class.forName("org.mockito.exceptions.verification.junit.ArgumentsAreDifferent");
+ return (AssertionError) clazz.getConstructors()[0].newInstance(message, wanted, actual);
+ } catch (Throwable t) {
+// throw the default exception in case of problems
+ return new ArgumentsAreDifferent(message);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/JUnitDetecter.java b/mockito-updated/src/org/mockito/internal/junit/JUnitDetecter.java
new file mode 100644
index 0000000..3ccc7f0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/JUnitDetecter.java
@@ -0,0 +1,19 @@
+package org.mockito.internal.junit;
+
+class JUnitDetecter {
+
+ private boolean hasJUnit;
+
+ JUnitDetecter() {
+ try {
+ Class.forName("junit.framework.ComparisonFailure");
+ hasJUnit = true;
+ } catch (Throwable t) {
+ hasJUnit = false;
+ }
+ }
+
+ public boolean hasJUnit() {
+ return hasJUnit;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/JUnitRule.java b/mockito-updated/src/org/mockito/internal/junit/JUnitRule.java
new file mode 100644
index 0000000..4c37e52
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/JUnitRule.java
@@ -0,0 +1,90 @@
+package org.mockito.internal.junit;
+
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.util.MockitoLogger;
+import org.mockito.junit.MockitoRule;
+
+/**
+ * Internal implementation.
+ */
+public class JUnitRule implements MockitoRule {
+
+ private final MockitoLogger logger;
+ private final boolean silent;
+
+ /**
+ * @param logger target for the stubbing warnings
+ * @param silent whether the rule
+ */
+ public JUnitRule(MockitoLogger logger, boolean silent) {
+ this.logger = logger;
+ this.silent = silent;
+ }
+
+ @Override
+ public Statement apply(final Statement base, FrameworkMethod method, final Object target) {
+ if (silent) {
+ return new SilentStatement(target, base);
+ } else {
+ String testName = target.getClass().getSimpleName() + "." + method.getName();
+ return new DefaultStatement(target, testName, base);
+ }
+ }
+
+ public JUnitRule silent() {
+ return new JUnitRule(logger, true);
+ }
+
+ private class SilentStatement extends Statement {
+ private final Object target;
+ private final Statement base;
+
+ public SilentStatement(Object target, Statement base) {
+ this.target = target;
+ this.base = base;
+ }
+
+ public void evaluate() throws Throwable {
+ MockitoAnnotations.initMocks(target);
+ base.evaluate();
+ Mockito.validateMockitoUsage();
+ }
+ }
+
+ private class DefaultStatement extends Statement {
+ private final Object target;
+ private final String testName;
+ private final Statement base;
+
+ DefaultStatement(Object target, String testName, Statement base) {
+ this.target = target;
+ this.testName = testName;
+ this.base = base;
+ }
+
+ public void evaluate() throws Throwable {
+ RuleStubbingHintsReporter reporter = new RuleStubbingHintsReporter();
+ Mockito.framework().addListener(reporter);
+ try {
+ performEvaluation(reporter);
+ } finally {
+ Mockito.framework().removeListener(reporter);
+ }
+ }
+
+ private void performEvaluation(RuleStubbingHintsReporter reporter) throws Throwable {
+ MockitoAnnotations.initMocks(target);
+ try {
+ base.evaluate();
+ } catch(Throwable t) {
+ reporter.getStubbingArgMismatches().format(testName, logger);
+ throw t;
+ }
+ reporter.getUnusedStubbings().format(testName, logger);
+ Mockito.validateMockitoUsage();
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/junit/JUnitTool.java b/mockito-updated/src/org/mockito/internal/junit/JUnitTool.java
new file mode 100644
index 0000000..ec98faa
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/JUnitTool.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.junit;
+
+public class JUnitTool {
+
+ private static final JUnitDetecter detecter = new JUnitDetecter();
+
+ public static boolean hasJUnit() {
+ return detecter.hasJUnit();
+ }
+
+ public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
+ return new FriendlyExceptionMaker(detecter).createArgumentsAreDifferentException(message, wanted, actual);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/junit/RuleStubbingHintsReporter.java b/mockito-updated/src/org/mockito/internal/junit/RuleStubbingHintsReporter.java
new file mode 100644
index 0000000..345f390
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/RuleStubbingHintsReporter.java
@@ -0,0 +1,27 @@
+package org.mockito.internal.junit;
+
+import org.mockito.listeners.MockCreationListener;
+import org.mockito.mock.MockCreationSettings;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Stubbing listener that is used in JUnit rules and detects stubbing problems.
+ */
+class RuleStubbingHintsReporter implements MockCreationListener {
+
+ private final List<Object> mocks = new LinkedList<Object>();
+
+ StubbingArgMismatches getStubbingArgMismatches() {
+ return new ArgMismatchFinder().getStubbingArgMismatches(mocks);
+ }
+
+ UnusedStubbings getUnusedStubbings() {
+ return new UnusedStubbingsFinder().getUnusedStubbings(mocks);
+ }
+
+ public void onMockCreated(Object mock, MockCreationSettings settings) {
+ mocks.add(mock);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/StubbingArgMismatches.java b/mockito-updated/src/org/mockito/internal/junit/StubbingArgMismatches.java
new file mode 100644
index 0000000..53f48b2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/StubbingArgMismatches.java
@@ -0,0 +1,48 @@
+package org.mockito.internal.junit;
+
+import org.mockito.internal.util.MockitoLogger;
+import org.mockito.invocation.Invocation;
+
+import java.util.*;
+
+/**
+ * Contains stubbing arg mismatches, knows how to format them
+ */
+class StubbingArgMismatches {
+
+ final Map<Invocation, Set<Invocation>> mismatches = new LinkedHashMap<Invocation, Set<Invocation>>();
+
+ public void add(Invocation invocation, Invocation stubbing) {
+ Set<Invocation> matchingInvocations = mismatches.get(stubbing);
+ if (matchingInvocations == null) {
+ matchingInvocations = new LinkedHashSet<Invocation>();
+ mismatches.put(stubbing, matchingInvocations);
+ }
+ matchingInvocations.add(invocation);
+ }
+
+ public void format(String testName, MockitoLogger logger) {
+ if (mismatches.isEmpty()) {
+ return;
+ }
+
+ StubbingHint hint = new StubbingHint(testName);
+ int x = 1;
+ for (Map.Entry<Invocation, Set<Invocation>> m : mismatches.entrySet()) {
+ hint.appendLine(x++, ". Unused... ", m.getKey().getLocation());
+ for (Invocation invocation : m.getValue()) {
+ hint.appendLine(" ...args ok? ", invocation.getLocation());
+ }
+ }
+
+ logger.log(hint.toString());
+ }
+
+ public int size() {
+ return mismatches.size();
+ }
+
+ public String toString() {
+ return "" + mismatches;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/StubbingHint.java b/mockito-updated/src/org/mockito/internal/junit/StubbingHint.java
new file mode 100644
index 0000000..07ab5a5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/StubbingHint.java
@@ -0,0 +1,25 @@
+package org.mockito.internal.junit;
+
+/**
+ * Stubbing hint emitted to the user
+ */
+class StubbingHint {
+
+ private final StringBuilder hint;
+
+ StubbingHint(String testName) {
+ hint = new StringBuilder("[MockitoHint] ")
+ .append(testName).append(" (see javadoc for MockitoHint):");
+ }
+
+ void appendLine(Object ... elements) {
+ hint.append("\n[MockitoHint] ");
+ for (Object e : elements) {
+ hint.append(e);
+ }
+ }
+
+ public String toString() {
+ return hint.toString() + "\n";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java b/mockito-updated/src/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java
new file mode 100644
index 0000000..a43e35f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/UnnecessaryStubbingsReporter.java
@@ -0,0 +1,38 @@
+package org.mockito.internal.junit;
+
+import org.junit.runner.Description;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunNotifier;
+import org.mockito.internal.exceptions.Reporter;
+import org.mockito.invocation.Invocation;
+import org.mockito.listeners.MockCreationListener;
+import org.mockito.mock.MockCreationSettings;
+
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Reports unnecessary stubbings
+ */
+public class UnnecessaryStubbingsReporter implements MockCreationListener {
+
+ private List<Object> mocks = new LinkedList<Object>();
+
+ public void validateUnusedStubs(Class<?> testClass, RunNotifier notifier) {
+ Collection<Invocation> unused = new UnusedStubbingsFinder().getUnusedStubbingsByLocation(mocks);
+ if (unused.size() == 0) {
+ return; //whoa!!! All stubbings were used!
+ }
+
+ //Oups, there are unused stubbings
+ Description unnecessaryStubbings = Description.createTestDescription(testClass, "unnecessary Mockito stubbings");
+ notifier.fireTestFailure(new Failure(unnecessaryStubbings,
+ Reporter.formatUnncessaryStubbingException(testClass, unused)));
+ }
+
+ @Override
+ public void onMockCreated(Object mock, MockCreationSettings settings) {
+ mocks.add(mock);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/UnusedStubbings.java b/mockito-updated/src/org/mockito/internal/junit/UnusedStubbings.java
new file mode 100644
index 0000000..0fa5b8c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/UnusedStubbings.java
@@ -0,0 +1,41 @@
+package org.mockito.internal.junit;
+
+import org.mockito.internal.util.MockitoLogger;
+import org.mockito.stubbing.Stubbing;
+
+import java.util.Collection;
+
+/**
+ * Contains unused stubbings, knows how to format them
+ */
+public class UnusedStubbings {
+
+ private final Collection<? extends Stubbing> unused;
+
+ UnusedStubbings(Collection<? extends Stubbing> unused) {
+ this.unused = unused;
+ }
+
+ void format(String testName, MockitoLogger logger) {
+ if (unused.isEmpty()) {
+ return;
+ }
+
+ StubbingHint hint = new StubbingHint(testName);
+ int x = 1;
+ for (Stubbing candidate : unused) {
+ if (!candidate.wasUsed()) {
+ hint.appendLine(x++, ". Unused ", candidate.getInvocation().getLocation());
+ }
+ }
+ logger.log(hint.toString());
+ }
+
+ public int size() {
+ return unused.size();
+ }
+
+ public String toString() {
+ return unused.toString();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/UnusedStubbingsFinder.java b/mockito-updated/src/org/mockito/internal/junit/UnusedStubbingsFinder.java
new file mode 100644
index 0000000..ae743b7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/UnusedStubbingsFinder.java
@@ -0,0 +1,69 @@
+package org.mockito.internal.junit;
+
+import org.mockito.stubbing.Stubbing;
+import org.mockito.internal.invocation.finder.AllInvocationsFinder;
+import org.mockito.internal.util.collections.ListUtil.Filter;
+import org.mockito.invocation.Invocation;
+
+import java.util.*;
+
+import static org.mockito.internal.util.collections.ListUtil.filter;
+
+/**
+ * Finds unused stubbings
+ */
+public class UnusedStubbingsFinder {
+
+ /**
+ * Gets all unused stubbings for given set of mock objects, in order
+ */
+ public UnusedStubbings getUnusedStubbings(Iterable<Object> mocks) {
+ Set<Stubbing> stubbings = AllInvocationsFinder.findStubbings(mocks);
+
+ List<Stubbing> unused = filter(stubbings, new Filter<Stubbing>() {
+ public boolean isOut(Stubbing s) {
+ return s.wasUsed();
+ }
+ });
+
+ return new UnusedStubbings(unused);
+ }
+
+ /**
+ * Gets unused stubbings per location. This method is less accurate than {@link #getUnusedStubbings(Iterable)}.
+ * It considers that stubbings with the same location (e.g. ClassFile + line number) are the same.
+ * This is not completely accurate because a stubbing declared in a setup or constructor
+ * is created per each test method. Because those are different test methods,
+ * different mocks are created, different 'Invocation' instance is backing the 'Stubbing' instance.
+ * In certain scenarios (detecting unused stubbings by JUnit runner), we need this exact level of accuracy.
+ * Stubbing declared in constructor but realized in % of test methods is considered as 'used' stubbing.
+ * There are high level unit tests that demonstrate this scenario.
+ */
+ public Collection<Invocation> getUnusedStubbingsByLocation(Iterable<Object> mocks) {
+ Set<Stubbing> stubbings = AllInvocationsFinder.findStubbings(mocks);
+
+ //1st pass, collect all the locations of the stubbings that were used
+ //note that those are _not_ locations where the stubbings was used
+ Set<String> locationsOfUsedStubbings = new HashSet<String>();
+ for (Stubbing s : stubbings) {
+ if (s.wasUsed()) {
+ String location = s.getInvocation().getLocation().toString();
+ locationsOfUsedStubbings.add(location);
+ }
+ }
+
+ //2nd pass, collect unused stubbings by location
+ //If the location matches we assume the stubbing was used in at least one test method
+ //Also, using map to deduplicate reported unused stubbings
+ // if unused stubbing appear in the setup method / constructor we don't want to report it per each test case
+ Map<String, Invocation> out = new LinkedHashMap<String, Invocation>();
+ for (Stubbing s : stubbings) {
+ String location = s.getInvocation().getLocation().toString();
+ if (!locationsOfUsedStubbings.contains(location)) {
+ out.put(location, s.getInvocation());
+ }
+ }
+
+ return out.values();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/junit/VerificationCollectorImpl.java b/mockito-updated/src/org/mockito/internal/junit/VerificationCollectorImpl.java
new file mode 100644
index 0000000..da9c451
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/junit/VerificationCollectorImpl.java
@@ -0,0 +1,98 @@
+package org.mockito.internal.junit;
+
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.progress.MockingProgressImpl;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.junit.VerificationCollector;
+import org.mockito.verification.VerificationMode;
+import org.mockito.verification.VerificationStrategy;
+
+/**
+ * Mockito implementation of VerificationCollector.
+ */
+public class VerificationCollectorImpl implements VerificationCollector {
+
+ private StringBuilder builder;
+ private int numberOfFailures;
+
+ public VerificationCollectorImpl() {
+ this.resetBuilder();
+ }
+
+ public Statement apply(final Statement base, final Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ try {
+ VerificationCollectorImpl.this.assertLazily();
+ base.evaluate();
+ VerificationCollectorImpl.this.collectAndReport();
+ } finally {
+ // If base.evaluate() throws an error, we must explicitly reset the VerificationStrategy
+ // to prevent subsequent tests to be assert lazily
+ mockingProgress().setVerificationStrategy(MockingProgressImpl.getDefaultVerificationStrategy());
+ }
+ }
+ };
+ }
+
+ public void collectAndReport() throws MockitoAssertionError {
+ mockingProgress().setVerificationStrategy(MockingProgressImpl.getDefaultVerificationStrategy());
+
+ if (this.numberOfFailures > 0) {
+ String error = this.builder.toString();
+
+ this.resetBuilder();
+
+ throw new MockitoAssertionError(error);
+ }
+ }
+
+ public VerificationCollector assertLazily() {
+ mockingProgress().setVerificationStrategy(new VerificationStrategy() {
+ public VerificationMode maybeVerifyLazily(VerificationMode mode) {
+ return new VerificationWrapper(mode);
+ }
+ });
+ return this;
+ }
+
+ private void resetBuilder() {
+ this.builder = new StringBuilder()
+ .append("There were multiple verification failures:");
+ this.numberOfFailures = 0;
+ }
+
+ private void append(String message) {
+ this.numberOfFailures++;
+ this.builder.append('\n')
+ .append(this.numberOfFailures).append(". ")
+ .append(message.substring(1, message.length()));
+ }
+
+ private class VerificationWrapper implements VerificationMode {
+
+ private final VerificationMode delegate;
+
+ private VerificationWrapper(VerificationMode delegate) {
+ this.delegate = delegate;
+ }
+
+ public void verify(VerificationData data) {
+ try {
+ this.delegate.verify(data);
+ } catch (MockitoAssertionError error) {
+ VerificationCollectorImpl.this.append(error.getMessage());
+ }
+ }
+
+ public VerificationMode description(String description) {
+ throw new IllegalStateException("Should not fail in this mode");
+ }
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/And.java b/mockito-updated/src/org/mockito/internal/matchers/And.java
new file mode 100644
index 0000000..1b969fa
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/And.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+import java.util.Iterator;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public class And implements ArgumentMatcher, Serializable {
+
+ private final List<ArgumentMatcher> matchers;
+
+ public And(List<ArgumentMatcher> matchers) {
+ this.matchers = matchers;
+ }
+
+ public boolean matches(Object actual) {
+ for (ArgumentMatcher matcher : matchers) {
+ if (!matcher.matches(actual)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public String toString() {
+ StringBuilder out = new StringBuilder();
+ out.append("and(");
+ for (Iterator<ArgumentMatcher> it = matchers.iterator(); it.hasNext();) {
+ out.append(it.next().toString());
+ if (it.hasNext()) {
+ out.append(", ");
+ }
+ }
+ out.append(")");
+ return out.toString();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Any.java b/mockito-updated/src/org/mockito/internal/matchers/Any.java
new file mode 100644
index 0000000..f9f0069
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Any.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+import org.mockito.ArgumentMatcher;
+
+public class Any implements ArgumentMatcher<Object>, VarargMatcher ,Serializable {
+
+ public static final Any ANY = new Any();
+
+ private Any() {
+ }
+
+ public boolean matches(Object actual) {
+ return true;
+ }
+
+ public String toString() {
+ return "<any>";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/ArrayEquals.java b/mockito-updated/src/org/mockito/internal/matchers/ArrayEquals.java
new file mode 100644
index 0000000..d647d1e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/ArrayEquals.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.lang.reflect.Array;
+import java.util.Arrays;
+
+public class ArrayEquals extends Equals {
+
+ public ArrayEquals(Object wanted) {
+ super(wanted);
+ }
+
+ public boolean matches(Object actual) {
+ Object wanted = getWanted();
+ if (wanted == null || actual == null) {
+ return super.matches(actual);
+ } else if (wanted instanceof boolean[] && actual instanceof boolean[]) {
+ return Arrays.equals((boolean[]) wanted, (boolean[]) actual);
+ } else if (wanted instanceof byte[] && actual instanceof byte[]) {
+ return Arrays.equals((byte[]) wanted, (byte[]) actual);
+ } else if (wanted instanceof char[] && actual instanceof char[]) {
+ return Arrays.equals((char[]) wanted, (char[]) actual);
+ } else if (wanted instanceof double[] && actual instanceof double[]) {
+ return Arrays.equals((double[]) wanted, (double[]) actual);
+ } else if (wanted instanceof float[] && actual instanceof float[]) {
+ return Arrays.equals((float[]) wanted, (float[]) actual);
+ } else if (wanted instanceof int[] && actual instanceof int[]) {
+ return Arrays.equals((int[]) wanted, (int[]) actual);
+ } else if (wanted instanceof long[] && actual instanceof long[]) {
+ return Arrays.equals((long[]) wanted, (long[]) actual);
+ } else if (wanted instanceof short[] && actual instanceof short[]) {
+ return Arrays.equals((short[]) wanted, (short[]) actual);
+ } else if (wanted instanceof Object[] && actual instanceof Object[]) {
+ return Arrays.equals((Object[]) wanted, (Object[]) actual);
+ }
+ return false;
+ }
+
+ public String toString() {
+ if (getWanted() != null && getWanted().getClass().isArray()) {
+ return appendArray(createObjectArray(getWanted()));
+ } else {
+ return super.toString();
+ }
+ }
+
+ private String appendArray(Object[] array) {
+ //TODO SF overlap with ValuePrinter
+ StringBuilder out = new StringBuilder("[");
+ for (int i = 0; i < array.length; i++) {
+ out.append(new Equals(array[i]).toString());
+ if (i != array.length - 1) {
+ out.append(", ");
+ }
+ }
+ out.append("]");
+ return out.toString();
+ }
+
+ public static Object[] createObjectArray(Object array) {
+ if (array instanceof Object[]) {
+ return (Object[]) array;
+ }
+ Object[] result = new Object[Array.getLength(array)];
+ for (int i = 0; i < Array.getLength(array); i++) {
+ result[i] = Array.get(array, i);
+ }
+ return result;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/CapturesArguments.java b/mockito-updated/src/org/mockito/internal/matchers/CapturesArguments.java
new file mode 100644
index 0000000..0c13853
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/CapturesArguments.java
@@ -0,0 +1,12 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers;
+
+
+public interface CapturesArguments {
+
+ void captureFrom(Object argument);
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/CapturingMatcher.java b/mockito-updated/src/org/mockito/internal/matchers/CapturingMatcher.java
new file mode 100644
index 0000000..830ef50
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/CapturingMatcher.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import static org.mockito.internal.exceptions.Reporter.noArgumentValueWasCaptured;
+
+import java.io.Serializable;
+import java.util.LinkedList;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public class CapturingMatcher<T> implements ArgumentMatcher<T>, CapturesArguments, VarargMatcher, Serializable {
+
+ private final LinkedList<Object> arguments = new LinkedList<Object>();
+
+ public boolean matches(Object argument) {
+ return true;
+ }
+
+ public String toString() {
+ return "<Capturing argument>";
+ }
+
+ public T getLastValue() {
+ if (arguments.isEmpty()) {
+ throw noArgumentValueWasCaptured();
+ }
+
+ return (T) arguments.getLast();
+
+ }
+
+ public List<T> getAllValues() {
+ return (List) arguments;
+ }
+
+ public void captureFrom(Object argument) {
+ this.arguments.add(argument);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/CompareEqual.java b/mockito-updated/src/org/mockito/internal/matchers/CompareEqual.java
new file mode 100644
index 0000000..eb21c46
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/CompareEqual.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+public class CompareEqual<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
+
+ public CompareEqual(T value) {
+ super(value);
+ }
+
+ @Override
+ protected String getName() {
+ return "cmpEq";
+ }
+
+ @Override
+ protected boolean matchResult(int result) {
+ return result == 0;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/CompareTo.java b/mockito-updated/src/org/mockito/internal/matchers/CompareTo.java
new file mode 100644
index 0000000..9be4b58
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/CompareTo.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public abstract class CompareTo<T extends Comparable<T>> implements ArgumentMatcher<T>, Serializable {
+ private final T wanted;
+
+ public CompareTo(T value) {
+ this.wanted = value;
+ }
+
+ @Override
+ public final boolean matches(T actual) {
+ if (actual == null) {
+ return false;
+ }
+ if (!actual.getClass().isInstance(wanted)){
+ return false;
+ }
+
+ int result = actual.compareTo(wanted);
+ return matchResult(result);
+ }
+
+ @Override
+ public final String toString() {
+ return getName() + "(" + wanted + ")";
+ }
+
+ protected abstract String getName();
+
+ protected abstract boolean matchResult(int result);
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Contains.java b/mockito-updated/src/org/mockito/internal/matchers/Contains.java
new file mode 100644
index 0000000..daa7608
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Contains.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+
+public class Contains implements ArgumentMatcher<String>, Serializable {
+
+ private final String substring;
+
+ public Contains(String substring) {
+ this.substring = substring;
+ }
+
+ public boolean matches(String actual) {
+ return actual != null && actual.contains(substring);
+ }
+
+ public String toString() {
+ return "contains(\"" + substring + "\")";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/ContainsExtraTypeInfo.java b/mockito-updated/src/org/mockito/internal/matchers/ContainsExtraTypeInfo.java
new file mode 100644
index 0000000..06da354
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/ContainsExtraTypeInfo.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers;
+
+/**
+ * Intended to use in certain ArgumentMatchers.
+ * When ArgumentMatcher fails, chance is that the actual object has the same output of toString() than
+ * the wanted object. This looks weird when failures are reported.
+ * Therefore when matcher fails but toString() yields the same outputs,
+ * we will try to use the {@link #toStringWithType()} method.
+ */
+public interface ContainsExtraTypeInfo {
+
+ /**
+ * Returns more verbose description of the object which include type information
+ */
+ String toStringWithType();
+
+ /**
+ * Checks if target target has matching type.
+ * If the type matches, there is no point in rendering result from {@link #toStringWithType()}
+ */
+ boolean typeMatches(Object target);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/EndsWith.java b/mockito-updated/src/org/mockito/internal/matchers/EndsWith.java
new file mode 100644
index 0000000..7bb194b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/EndsWith.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.matchers;
+
+import java.io.Serializable;
+
+import org.mockito.ArgumentMatcher;
+
+public class EndsWith implements ArgumentMatcher<String>, Serializable {
+
+ private final String suffix;
+
+ public EndsWith(String suffix) {
+ this.suffix = suffix;
+ }
+
+ public boolean matches(String actual) {
+ return actual != null && actual.endsWith(suffix);
+ }
+
+ public String toString() {
+ return "endsWith(\"" + suffix + "\")";
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Equality.java b/mockito-updated/src/org/mockito/internal/matchers/Equality.java
new file mode 100644
index 0000000..0fc6abf
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Equality.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers;
+
+import java.lang.reflect.Array;
+
+//stolen from hamcrest because I didn't want to have more dependency than Matcher class
+public class Equality {
+
+ public static boolean areEqual(Object o1, Object o2) {
+ if (o1 == o2 ) {
+ return true;
+ } else if (o1 == null || o2 == null) {
+ return false;
+ } else if (isArray(o1)) {
+ return isArray(o2) && areArraysEqual(o1, o2);
+ } else {
+ return o1.equals(o2);
+ }
+ }
+
+ static boolean areArraysEqual(Object o1, Object o2) {
+ return areArrayLengthsEqual(o1, o2)
+ && areArrayElementsEqual(o1, o2);
+ }
+
+ static boolean areArrayLengthsEqual(Object o1, Object o2) {
+ return Array.getLength(o1) == Array.getLength(o2);
+ }
+
+ static boolean areArrayElementsEqual(Object o1, Object o2) {
+ for (int i = 0; i < Array.getLength(o1); i++) {
+ if (!areEqual(Array.get(o1, i), Array.get(o2, i))) return false;
+ }
+ return true;
+ }
+
+ static boolean isArray(Object o) {
+ return o.getClass().isArray();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Equals.java b/mockito-updated/src/org/mockito/internal/matchers/Equals.java
new file mode 100644
index 0000000..f1c5f49
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Equals.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.text.ValuePrinter;
+
+import java.io.Serializable;
+
+public class Equals implements ArgumentMatcher<Object>, ContainsExtraTypeInfo, Serializable {
+
+ private final Object wanted;
+
+ public Equals(Object wanted) {
+ this.wanted = wanted;
+ }
+
+ public boolean matches(Object actual) {
+ return Equality.areEqual(this.wanted, actual);
+ }
+
+ public String toString() {
+ return describe(wanted);
+ }
+
+ private String describe(Object object) {
+ return ValuePrinter.print(object);
+ }
+
+ protected final Object getWanted() {
+ return wanted;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null || !this.getClass().equals(o.getClass())) {
+ return false;
+ }
+ Equals other = (Equals) o;
+ return this.wanted == null && other.wanted == null || this.wanted != null && this.wanted.equals(other.wanted);
+ }
+
+ @Override
+ public int hashCode() {
+ return 1;
+ }
+
+ public String toStringWithType() {
+ return "("+ wanted.getClass().getSimpleName() +") " + describe(wanted);
+ }
+
+ public boolean typeMatches(Object target) {
+ return wanted != null && target != null && target.getClass() == wanted.getClass();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/EqualsWithDelta.java b/mockito-updated/src/org/mockito/internal/matchers/EqualsWithDelta.java
new file mode 100644
index 0000000..d5d8e19
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/EqualsWithDelta.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public class EqualsWithDelta implements ArgumentMatcher<Number>, Serializable {
+
+ private final Number wanted;
+ private final Number delta;
+
+ public EqualsWithDelta(Number value, Number delta) {
+ this.wanted = value;
+ this.delta = delta;
+ }
+
+ public boolean matches(Number actual) {
+ if (wanted == null ^ actual == null) {
+ return false;
+ }
+
+ if (wanted == actual) {
+ return true;
+ }
+
+ return wanted.doubleValue() - delta.doubleValue() <= actual.doubleValue()
+ && actual.doubleValue() <= wanted.doubleValue()
+ + delta.doubleValue();
+ }
+
+ public String toString() {
+ return "eq(" + wanted + ", " + delta + ")";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Find.java b/mockito-updated/src/org/mockito/internal/matchers/Find.java
new file mode 100644
index 0000000..d37771a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Find.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+import java.util.regex.Pattern;
+
+import org.mockito.ArgumentMatcher;
+
+public class Find implements ArgumentMatcher<String>, Serializable {
+
+ private final String regex;
+
+ public Find(String regex) {
+ this.regex = regex;
+ }
+
+ public boolean matches(String actual) {
+ return actual != null && Pattern.compile(regex).matcher(actual).find();
+ }
+
+ public String toString() {
+ return "find(\"" + regex.replaceAll("\\\\", "\\\\\\\\") + "\")";
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/GreaterOrEqual.java b/mockito-updated/src/org/mockito/internal/matchers/GreaterOrEqual.java
new file mode 100644
index 0000000..f1c8ff2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/GreaterOrEqual.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+public class GreaterOrEqual<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
+
+ public GreaterOrEqual(T value) {
+ super(value);
+ }
+
+ @Override
+ protected String getName() {
+ return "geq";
+ }
+
+ @Override
+ protected boolean matchResult(int result) {
+ return result >= 0;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/GreaterThan.java b/mockito-updated/src/org/mockito/internal/matchers/GreaterThan.java
new file mode 100644
index 0000000..4ca82cf
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/GreaterThan.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+public class GreaterThan<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
+
+ public GreaterThan(T value) {
+ super(value);
+ }
+
+ @Override
+ protected String getName() {
+ return "gt";
+ }
+
+ @Override
+ protected boolean matchResult(int result) {
+ return result > 0;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/InstanceOf.java b/mockito-updated/src/org/mockito/internal/matchers/InstanceOf.java
new file mode 100644
index 0000000..2876aa2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/InstanceOf.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.util.Primitives;
+
+import java.io.Serializable;
+
+
+public class InstanceOf implements ArgumentMatcher<Object>, Serializable {
+
+ private final Class<?> clazz;
+ private String description;
+
+ public InstanceOf(Class<?> clazz) {
+ this(clazz, "isA(" + clazz.getCanonicalName() + ")");
+ }
+
+ public InstanceOf(Class<?> clazz, String describedAs) {
+ this.clazz = clazz;
+ this.description = describedAs;
+ }
+
+ public boolean matches(Object actual) {
+ return (actual != null) &&
+ (Primitives.isAssignableFromWrapper(actual.getClass(), clazz)
+ || clazz.isAssignableFrom(actual.getClass()));
+ }
+
+ public String toString() {
+ return description;
+ }
+
+ public static class VarArgAware extends InstanceOf implements VarargMatcher {
+
+ public VarArgAware(Class<?> clazz) {
+ super(clazz);
+ }
+
+ public VarArgAware(Class<?> clazz, String describedAs) {
+ super(clazz, describedAs);
+ }
+ }
+
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/LessOrEqual.java b/mockito-updated/src/org/mockito/internal/matchers/LessOrEqual.java
new file mode 100644
index 0000000..1b3d737
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/LessOrEqual.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+public class LessOrEqual<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
+
+ public LessOrEqual(T value) {
+ super(value);
+ }
+
+ @Override
+ protected String getName() {
+ return "leq";
+ }
+
+ @Override
+ protected boolean matchResult(int result) {
+ return result <= 0;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/LessThan.java b/mockito-updated/src/org/mockito/internal/matchers/LessThan.java
new file mode 100644
index 0000000..c0c931e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/LessThan.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+public class LessThan<T extends Comparable<T>> extends CompareTo<T> implements Serializable {
+
+ public LessThan(T value) {
+ super(value);
+ }
+
+ @Override
+ protected String getName() {
+ return "lt";
+ }
+
+ @Override
+ protected boolean matchResult(int result) {
+ return result < 0;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/LocalizedMatcher.java b/mockito-updated/src/org/mockito/internal/matchers/LocalizedMatcher.java
new file mode 100644
index 0000000..310a316
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/LocalizedMatcher.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.debugging.LocationImpl;
+import org.mockito.invocation.Location;
+
+@SuppressWarnings("unchecked")
+public class LocalizedMatcher {
+
+ private final ArgumentMatcher<?> matcher;
+ private final Location location;
+
+ public LocalizedMatcher(ArgumentMatcher<?> matcher) {
+ this.matcher = matcher;
+ this.location = new LocationImpl();
+ }
+
+ public Location getLocation() {
+ return location;
+ }
+
+ public ArgumentMatcher<?> getMatcher() {
+ return matcher;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Matches.java b/mockito-updated/src/org/mockito/internal/matchers/Matches.java
new file mode 100644
index 0000000..6ebb4a8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Matches.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.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public class Matches implements ArgumentMatcher<Object>, Serializable {
+
+ private final String regex;
+
+ public Matches(String regex) {
+ this.regex = regex;
+ }
+
+ public boolean matches(Object actual) {
+ return (actual instanceof String) && ((String) actual).matches(regex);
+ }
+
+ public String toString() {
+ return "matches(\"" + regex.replaceAll("\\\\", "\\\\\\\\") + "\")";
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Not.java b/mockito-updated/src/org/mockito/internal/matchers/Not.java
new file mode 100644
index 0000000..a090270
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Not.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+@SuppressWarnings("unchecked")
+public class Not implements ArgumentMatcher, Serializable {
+
+ private final ArgumentMatcher first;
+
+ public Not(ArgumentMatcher first) {
+ this.first = first;
+ }
+
+ public boolean matches(Object actual) {
+ return !first.matches(actual);
+ }
+
+ public String toString() {
+ return "not(" + first.toString() + ")";
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/NotNull.java b/mockito-updated/src/org/mockito/internal/matchers/NotNull.java
new file mode 100644
index 0000000..1b4b36d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/NotNull.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public class NotNull implements ArgumentMatcher<Object>, Serializable {
+
+ public static final NotNull NOT_NULL = new NotNull();
+
+ private NotNull() {
+ }
+
+ public boolean matches(Object actual) {
+ return actual != null;
+ }
+
+ public String toString() {
+ return "notNull()";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Null.java b/mockito-updated/src/org/mockito/internal/matchers/Null.java
new file mode 100644
index 0000000..650a606
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Null.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public class Null implements ArgumentMatcher<Object>, Serializable {
+
+ public static final Null NULL = new Null();
+
+ private Null() {
+ }
+
+ public boolean matches(Object actual) {
+ return actual == null;
+ }
+
+ public String toString() {
+ return "isNull()";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Or.java b/mockito-updated/src/org/mockito/internal/matchers/Or.java
new file mode 100644
index 0000000..c6a2e27
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Or.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+import java.util.Iterator;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public class Or implements ArgumentMatcher, Serializable {
+
+ private final List<ArgumentMatcher> matchers;
+
+ public Or(List<ArgumentMatcher> matchers) {
+ this.matchers = matchers;
+ }
+
+ public boolean matches(Object actual) {
+ for (ArgumentMatcher matcher : matchers) {
+ if (matcher.matches(actual)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String toString() {
+ //TODO SF here and in other places we should reuse ValuePrinter
+ StringBuilder sb = new StringBuilder("or(");
+ for (Iterator<ArgumentMatcher> it = matchers.iterator(); it.hasNext();) {
+ sb.append(it.next().toString());
+ if (it.hasNext()) {
+ sb.append(", ");
+ }
+ }
+ return sb.append(")").toString();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/Same.java b/mockito-updated/src/org/mockito/internal/matchers/Same.java
new file mode 100644
index 0000000..b834376
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/Same.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.text.ValuePrinter;
+
+import java.io.Serializable;
+
+public class Same implements ArgumentMatcher<Object>, Serializable {
+
+ private final Object wanted;
+
+ public Same(Object wanted) {
+ this.wanted = wanted;
+ }
+
+ public boolean matches(Object actual) {
+ return wanted == actual;
+ }
+
+ public String toString() {
+ return "same(" + ValuePrinter.print(wanted) + ")";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/StartsWith.java b/mockito-updated/src/org/mockito/internal/matchers/StartsWith.java
new file mode 100644
index 0000000..f89c2c0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/StartsWith.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.matchers;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public class StartsWith implements ArgumentMatcher<String>, Serializable {
+
+ private final String prefix;
+
+ public StartsWith(String prefix) {
+ this.prefix = prefix;
+ }
+
+ public boolean matches(String actual) {
+ return actual != null && actual.startsWith(prefix);
+ }
+
+ public String toString() {
+ return "startsWith(\"" + prefix + "\")";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/VarargMatcher.java b/mockito-updated/src/org/mockito/internal/matchers/VarargMatcher.java
new file mode 100644
index 0000000..fc843f6
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/VarargMatcher.java
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers;
+
+import java.io.Serializable;
+
+/**
+ * Internal interface that informs Mockito that the matcher is intended to capture varargs.
+ * This information is needed when mockito collects the arguments.
+ */
+public interface VarargMatcher extends Serializable {
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java
new file mode 100644
index 0000000..55f2ccd
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/EqualsBuilder.java
@@ -0,0 +1,794 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+//NON-STANDARD LICENCE HEADER HERE - THAT'S OK
+//Class comes from Apache Commons Lang, added some tiny changes
+package org.mockito.internal.matchers.apachecommons;
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * <p>Assists in implementing {@link Object#equals(Object)} methods.</p>
+ *
+ * <p> This class provides methods to build a good equals method for any
+ * class. It follows rules laid out in
+ * <a href="http://java.sun.com/docs/books/effective/index.html">Effective Java</a>
+ * , by Joshua Bloch. In particular the rule for comparing <code>doubles</code>,
+ * <code>floats</code>, and arrays can be tricky. Also, making sure that
+ * <code>equals()</code> and <code>hashCode()</code> are consistent can be
+ * difficult.</p>
+ *
+ * <p>Two Objects that compare as equals must generate the same hash code,
+ * but two Objects with the same hash code do not have to be equal.</p>
+ *
+ * <p>All relevant fields should be included in the calculation of equals.
+ * Derived fields may be ignored. In particular, any field used in
+ * generating a hash code must be used in the equals method, and vice
+ * versa.</p>
+ *
+ * <p>Typical use for the code is as follows:</p>
+ * <pre class="code"><code class="java">
+ * public boolean equals(Object obj) {
+ * if (obj == null) { return false; }
+ * if (obj == this) { return true; }
+ * if (obj.getClass() != getClass()) {
+ * return false;
+ * }
+ * MyClass rhs = (MyClass) obj;
+ * return new EqualsBuilder()
+ * .appendSuper(super.equals(obj))
+ * .append(field1, rhs.field1)
+ * .append(field2, rhs.field2)
+ * .append(field3, rhs.field3)
+ * .isEquals();
+ * }
+ * </code></pre>
+ *
+ * <p> Alternatively, there is a method that uses reflection to determine
+ * the fields to test. Because these fields are usually private, the method,
+ * <code>reflectionEquals</code>, uses <code>AccessibleObject.setAccessible</code> to
+ * change the visibility of the fields. This will fail under a security
+ * manager, unless the appropriate permissions are set up correctly. It is
+ * also slower than testing explicitly.</p>
+ *
+ * <p> A typical invocation for this method would look like:</p>
+ * <pre class="code"><code class="java">
+ * public boolean equals(Object obj) {
+ * return EqualsBuilder.reflectionEquals(this, obj);
+ * }
+ * </code></pre>
+ *
+ * @author <a href="mailto:steve.downey@netfolio.com">Steve Downey</a>
+ * @author Stephen Colebourne
+ * @author Gary Gregory
+ * @author Pete Gieser
+ * @author Arun Mammen Thomas
+ * @since 1.0
+ * @version $Id: EqualsBuilder.java 611543 2008-01-13 07:00:22Z bayard $
+ */
+@SuppressWarnings("unchecked")
+class EqualsBuilder {
+
+ /**
+ * If the fields tested are equals.
+ * The default value is <code>true</code>.
+ */
+ private boolean isEquals = true;
+
+ /**
+ * <p>Constructor for EqualsBuilder.</p>
+ *
+ * <p>Starts off assuming that equals is <code>true</code>.</p>
+ * @see Object#equals(Object)
+ */
+ public EqualsBuilder() {
+ // do nothing for now.
+ }
+
+ //-------------------------------------------------------------------------
+
+ /**
+ * <p>This method uses reflection to determine if the two <code>Object</code>s
+ * are equal.</p>
+ *
+ * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
+ * fields. This means that it will throw a security exception if run under
+ * a security manager, if the permissions are not set up correctly. It is also
+ * not as efficient as testing explicitly.</p>
+ *
+ * <p>Transient members will be not be tested, as they are likely derived
+ * fields, and not part of the value of the Object.</p>
+ *
+ * <p>Static fields will not be tested. Superclass fields will be included.</p>
+ *
+ * @param lhs <code>this</code> object
+ * @param rhs the other object
+ * @return <code>true</code> if the two Objects have tested equals.
+ */
+ public static boolean reflectionEquals(Object lhs, Object rhs) {
+ return reflectionEquals(lhs, rhs, false, null, null);
+ }
+
+ /**
+ * <p>This method uses reflection to determine if the two <code>Object</code>s
+ * are equal.</p>
+ *
+ * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
+ * fields. This means that it will throw a security exception if run under
+ * a security manager, if the permissions are not set up correctly. It is also
+ * not as efficient as testing explicitly.</p>
+ *
+ * <p>Transient members will be not be tested, as they are likely derived
+ * fields, and not part of the value of the Object.</p>
+ *
+ * <p>Static fields will not be tested. Superclass fields will be included.</p>
+ *
+ * @param lhs <code>this</code> object
+ * @param rhs the other object
+ * @param excludeFields array of field names to exclude from testing
+ * @return <code>true</code> if the two Objects have tested equals.
+ */
+ public static boolean reflectionEquals(Object lhs, Object rhs, String[] excludeFields) {
+ return reflectionEquals(lhs, rhs, false, null, excludeFields);
+ }
+
+ /**
+ * <p>This method uses reflection to determine if the two <code>Object</code>s
+ * are equal.</p>
+ *
+ * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
+ * fields. This means that it will throw a security exception if run under
+ * a security manager, if the permissions are not set up correctly. It is also
+ * not as efficient as testing explicitly.</p>
+ *
+ * <p>If the TestTransients parameter is set to <code>true</code>, transient
+ * members will be tested, otherwise they are ignored, as they are likely
+ * derived fields, and not part of the value of the <code>Object</code>.</p>
+ *
+ * <p>Static fields will not be tested. Superclass fields will be included.</p>
+ *
+ * @param lhs <code>this</code> object
+ * @param rhs the other object
+ * @param testTransients whether to include transient fields
+ * @return <code>true</code> if the two Objects have tested equals.
+ */
+ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) {
+ return reflectionEquals(lhs, rhs, testTransients, null, null);
+ }
+
+ /**
+ * <p>This method uses reflection to determine if the two <code>Object</code>s
+ * are equal.</p>
+ *
+ * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
+ * fields. This means that it will throw a security exception if run under
+ * a security manager, if the permissions are not set up correctly. It is also
+ * not as efficient as testing explicitly.</p>
+ *
+ * <p>If the testTransients parameter is set to <code>true</code>, transient
+ * members will be tested, otherwise they are ignored, as they are likely
+ * derived fields, and not part of the value of the <code>Object</code>.</p>
+ *
+ * <p>Static fields will not be included. Superclass fields will be appended
+ * up to and including the specified superclass. A null superclass is treated
+ * as java.lang.Object.</p>
+ *
+ * @param lhs <code>this</code> object
+ * @param rhs the other object
+ * @param testTransients whether to include transient fields
+ * @param reflectUpToClass the superclass to reflect up to (inclusive),
+ * may be <code>null</code>
+ * @return <code>true</code> if the two Objects have tested equals.
+ * @since 2.1.0
+ */
+ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class<?> reflectUpToClass) {
+ return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, null);
+ }
+
+ /**
+ * <p>This method uses reflection to determine if the two <code>Object</code>s
+ * are equal.</p>
+ *
+ * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
+ * fields. This means that it will throw a security exception if run under
+ * a security manager, if the permissions are not set up correctly. It is also
+ * not as efficient as testing explicitly.</p>
+ *
+ * <p>If the testTransients parameter is set to <code>true</code>, transient
+ * members will be tested, otherwise they are ignored, as they are likely
+ * derived fields, and not part of the value of the <code>Object</code>.</p>
+ *
+ * <p>Static fields will not be included. Superclass fields will be appended
+ * up to and including the specified superclass. A null superclass is treated
+ * as java.lang.Object.</p>
+ *
+ * @param lhs <code>this</code> object
+ * @param rhs the other object
+ * @param testTransients whether to include transient fields
+ * @param reflectUpToClass the superclass to reflect up to (inclusive),
+ * may be <code>null</code>
+ * @param excludeFields array of field names to exclude from testing
+ * @return <code>true</code> if the two Objects have tested equals.
+ * @since 2.1.0
+ */
+ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class<?> reflectUpToClass,
+ String[] excludeFields) {
+ if (lhs == rhs) {
+ return true;
+ }
+ if (lhs == null || rhs == null) {
+ return false;
+ }
+ // Find the leaf class since there may be transients in the leaf
+ // class or in classes between the leaf and root.
+ // If we are not testing transients or a subclass has no ivars,
+ // then a subclass can test equals to a superclass.
+ Class<?> lhsClass = lhs.getClass();
+ Class<?> rhsClass = rhs.getClass();
+ Class<?> testClass;
+ if (lhsClass.isInstance(rhs)) {
+ testClass = lhsClass;
+ if (!rhsClass.isInstance(lhs)) {
+ // rhsClass is a subclass of lhsClass
+ testClass = rhsClass;
+ }
+ } else if (rhsClass.isInstance(lhs)) {
+ testClass = rhsClass;
+ if (!lhsClass.isInstance(rhs)) {
+ // lhsClass is a subclass of rhsClass
+ testClass = lhsClass;
+ }
+ } else {
+ // The two classes are not related.
+ return false;
+ }
+ EqualsBuilder equalsBuilder = new EqualsBuilder();
+ try {
+ reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
+ while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
+ testClass = testClass.getSuperclass();
+ reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
+ }
+ } catch (IllegalArgumentException e) {
+ // In this case, we tried to test a subclass vs. a superclass and
+ // the subclass has ivars or the ivars are transient and
+ // we are testing transients.
+ // If a subclass has ivars that we are trying to test them, we get an
+ // exception and we know that the objects are not equal.
+ return false;
+ }
+ return equalsBuilder.isEquals();
+ }
+
+ /**
+ * <p>Appends the fields and values defined by the given object of the
+ * given Class.</p>
+ *
+ * @param lhs the left hand object
+ * @param rhs the right hand object
+ * @param clazz the class to append details of
+ * @param builder the builder to append to
+ * @param useTransients whether to test transient fields
+ * @param excludeFields array of field names to exclude from testing
+ */
+ private static void reflectionAppend(
+ Object lhs,
+ Object rhs,
+ Class<?> clazz,
+ EqualsBuilder builder,
+ boolean useTransients,
+ String[] excludeFields) {
+ Field[] fields = clazz.getDeclaredFields();
+ List<String> excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.<String>emptyList();
+ AccessibleObject.setAccessible(fields, true);
+ for (int i = 0; i < fields.length && builder.isEquals; i++) {
+ Field f = fields[i];
+ if (!excludedFieldList.contains(f.getName())
+ && (f.getName().indexOf('$') == -1)
+ && (useTransients || !Modifier.isTransient(f.getModifiers()))
+ && (!Modifier.isStatic(f.getModifiers()))) {
+ try {
+ builder.append(f.get(lhs), f.get(rhs));
+ } catch (IllegalAccessException e) {
+ //this can't happen. Would get a Security exception instead
+ //throw a runtime exception in case the impossible happens.
+ throw new InternalError("Unexpected IllegalAccessException");
+ }
+ }
+ }
+ }
+
+ //-------------------------------------------------------------------------
+
+ /**
+ * <p>Adds the result of <code>super.equals()</code> to this builder.</p>
+ *
+ * @param superEquals the result of calling <code>super.equals()</code>
+ * @return EqualsBuilder - used to chain calls.
+ * @since 2.1.0
+ */
+ public EqualsBuilder appendSuper(boolean superEquals) {
+ isEquals &= superEquals;
+ return this;
+ }
+
+ //-------------------------------------------------------------------------
+
+ /**
+ * <p>Test if two <code>Object</code>s are equal using their
+ * <code>equals</code> method.</p>
+ *
+ * @param lhs the left hand object
+ * @param rhs the right hand object
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(Object lhs, Object rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ Class<?> lhsClass = lhs.getClass();
+ if (!lhsClass.isArray()) {
+ if (lhs instanceof java.math.BigDecimal && rhs instanceof java.math.BigDecimal) {
+ isEquals = (((java.math.BigDecimal) lhs).compareTo((java.math.BigDecimal) rhs) == 0);
+ } else {
+ // The simple case, not an array, just test the element
+ isEquals = lhs.equals(rhs);
+ }
+ } else if (lhs.getClass() != rhs.getClass()) {
+ // Here when we compare different dimensions, for example: a boolean[][] to a boolean[]
+ this.setEquals(false);
+
+ // 'Switch' on type of array, to dispatch to the correct handler
+ // This handles multi dimensional arrays of the same depth
+ } else if (lhs instanceof long[]) {
+ append((long[]) lhs, (long[]) rhs);
+ } else if (lhs instanceof int[]) {
+ append((int[]) lhs, (int[]) rhs);
+ } else if (lhs instanceof short[]) {
+ append((short[]) lhs, (short[]) rhs);
+ } else if (lhs instanceof char[]) {
+ append((char[]) lhs, (char[]) rhs);
+ } else if (lhs instanceof byte[]) {
+ append((byte[]) lhs, (byte[]) rhs);
+ } else if (lhs instanceof double[]) {
+ append((double[]) lhs, (double[]) rhs);
+ } else if (lhs instanceof float[]) {
+ append((float[]) lhs, (float[]) rhs);
+ } else if (lhs instanceof boolean[]) {
+ append((boolean[]) lhs, (boolean[]) rhs);
+ } else {
+ // Not an array of primitives
+ append((Object[]) lhs, (Object[]) rhs);
+ }
+ return this;
+ }
+
+ /**
+ * <p>
+ * Test if two <code>long</code> s are equal.
+ * </p>
+ *
+ * @param lhs
+ * the left hand <code>long</code>
+ * @param rhs
+ * the right hand <code>long</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(long lhs, long rhs) {
+ isEquals &= (lhs == rhs);
+ return this;
+ }
+
+ /**
+ * <p>Test if two <code>int</code>s are equal.</p>
+ *
+ * @param lhs the left hand <code>int</code>
+ * @param rhs the right hand <code>int</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(int lhs, int rhs) {
+ isEquals &= (lhs == rhs);
+ return this;
+ }
+
+ /**
+ * <p>Test if two <code>short</code>s are equal.</p>
+ *
+ * @param lhs the left hand <code>short</code>
+ * @param rhs the right hand <code>short</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(short lhs, short rhs) {
+ isEquals &= (lhs == rhs);
+ return this;
+ }
+
+ /**
+ * <p>Test if two <code>char</code>s are equal.</p>
+ *
+ * @param lhs the left hand <code>char</code>
+ * @param rhs the right hand <code>char</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(char lhs, char rhs) {
+ isEquals &= (lhs == rhs);
+ return this;
+ }
+
+ /**
+ * <p>Test if two <code>byte</code>s are equal.</p>
+ *
+ * @param lhs the left hand <code>byte</code>
+ * @param rhs the right hand <code>byte</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(byte lhs, byte rhs) {
+ isEquals &= (lhs == rhs);
+ return this;
+ }
+
+ /**
+ * <p>Test if two <code>double</code>s are equal by testing that the
+ * pattern of bits returned by <code>doubleToLong</code> are equal.</p>
+ *
+ * <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
+ *
+ * <p>It is compatible with the hash code generated by
+ * <code>HashCodeBuilder</code>.</p>
+ *
+ * @param lhs the left hand <code>double</code>
+ * @param rhs the right hand <code>double</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(double lhs, double rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs));
+ }
+
+ /**
+ * <p>Test if two <code>float</code>s are equal byt testing that the
+ * pattern of bits returned by doubleToLong are equal.</p>
+ *
+ * <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
+ *
+ * <p>It is compatible with the hash code generated by
+ * <code>HashCodeBuilder</code>.</p>
+ *
+ * @param lhs the left hand <code>float</code>
+ * @param rhs the right hand <code>float</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(float lhs, float rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs));
+ }
+
+ /**
+ * <p>Test if two <code>booleans</code>s are equal.</p>
+ *
+ * @param lhs the left hand <code>boolean</code>
+ * @param rhs the right hand <code>boolean</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(boolean lhs, boolean rhs) {
+ isEquals &= (lhs == rhs);
+ return this;
+ }
+
+ /**
+ * <p>Performs a deep comparison of two <code>Object</code> arrays.</p>
+ *
+ * <p>This also will be called for the top level of
+ * multi-dimensional, ragged, and multi-typed arrays.</p>
+ *
+ * @param lhs the left hand <code>Object[]</code>
+ * @param rhs the right hand <code>Object[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(Object[] lhs, Object[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>long</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(long, long)} is used.</p>
+ *
+ * @param lhs the left hand <code>long[]</code>
+ * @param rhs the right hand <code>long[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(long[] lhs, long[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>int</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(int, int)} is used.</p>
+ *
+ * @param lhs the left hand <code>int[]</code>
+ * @param rhs the right hand <code>int[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(int[] lhs, int[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>short</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(short, short)} is used.</p>
+ *
+ * @param lhs the left hand <code>short[]</code>
+ * @param rhs the right hand <code>short[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(short[] lhs, short[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>char</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(char, char)} is used.</p>
+ *
+ * @param lhs the left hand <code>char[]</code>
+ * @param rhs the right hand <code>char[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(char[] lhs, char[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>byte</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(byte, byte)} is used.</p>
+ *
+ * @param lhs the left hand <code>byte[]</code>
+ * @param rhs the right hand <code>byte[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(byte[] lhs, byte[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>double</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(double, double)} is used.</p>
+ *
+ * @param lhs the left hand <code>double[]</code>
+ * @param rhs the right hand <code>double[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(double[] lhs, double[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>float</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(float, float)} is used.</p>
+ *
+ * @param lhs the left hand <code>float[]</code>
+ * @param rhs the right hand <code>float[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(float[] lhs, float[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Deep comparison of array of <code>boolean</code>. Length and all
+ * values are compared.</p>
+ *
+ * <p>The method {@link #append(boolean, boolean)} is used.</p>
+ *
+ * @param lhs the left hand <code>boolean[]</code>
+ * @param rhs the right hand <code>boolean[]</code>
+ * @return EqualsBuilder - used to chain calls.
+ */
+ public EqualsBuilder append(boolean[] lhs, boolean[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
+ /**
+ * <p>Returns <code>true</code> if the fields that have been checked
+ * are all equal.</p>
+ *
+ * @return boolean
+ */
+ public boolean isEquals() {
+ return this.isEquals;
+ }
+
+ /**
+ * Sets the <code>isEquals</code> value.
+ *
+ * @param isEquals The value to set.
+ * @since 2.1
+ */
+ protected void setEquals(boolean isEquals) {
+ this.isEquals = isEquals;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/apachecommons/ReflectionEquals.java b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/ReflectionEquals.java
new file mode 100644
index 0000000..320f625
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/ReflectionEquals.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.matchers.apachecommons;
+
+import org.mockito.ArgumentMatcher;
+
+import java.io.Serializable;
+
+public class ReflectionEquals implements ArgumentMatcher<Object>, Serializable {
+
+ private final Object wanted;
+ private final String[] excludeFields;
+
+ public ReflectionEquals(Object wanted, String... excludeFields) {
+ this.wanted = wanted;
+ this.excludeFields = excludeFields;
+ }
+
+ public boolean matches(Object actual) {
+ return EqualsBuilder.reflectionEquals(wanted, actual, excludeFields);
+ }
+
+ public String toString() {
+ return "refEq(" + wanted + ")";
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/apachecommons/commons-lang-license.txt b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/commons-lang-license.txt
new file mode 100644
index 0000000..f49a4e1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/commons-lang-license.txt
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/apachecommons/package.html b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/package.html
new file mode 100644
index 0000000..bbb72c8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/apachecommons/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Argument matchers that use Apache Commons Lang reflection-equality.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/package.html b/mockito-updated/src/org/mockito/internal/matchers/package.html
new file mode 100644
index 0000000..26b6f88
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Argument matchers for verification and stubbing.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/matchers/text/ArrayIterator.java b/mockito-updated/src/org/mockito/internal/matchers/text/ArrayIterator.java
new file mode 100644
index 0000000..c72fa5f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/text/ArrayIterator.java
@@ -0,0 +1,38 @@
+package org.mockito.internal.matchers.text;
+
+import java.lang.reflect.Array;
+import java.util.Iterator;
+
+/**
+ * Inspired on hamcrest, internal package class,
+ * TODO add specific unit tests instead of relying on higher level unit tests
+ */
+class ArrayIterator implements Iterator<Object> {
+
+ private final Object array;
+ private int currentIndex = 0;
+
+ public ArrayIterator(Object array) {
+ if (array == null) {
+ //TODO extract a small utility for null-checking
+ throw new IllegalArgumentException("Expected array instance but got null");
+ }
+ if (!array.getClass().isArray()) {
+ throw new IllegalArgumentException("Expected array but got object of type: "
+ + array.getClass() + ", the object: " + array.toString());
+ }
+ this.array = array;
+ }
+
+ public boolean hasNext() {
+ return currentIndex < Array.getLength(array);
+ }
+
+ public Object next() {
+ return Array.get(array, currentIndex++);
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException("cannot remove items from an array");
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/text/FormattedText.java b/mockito-updated/src/org/mockito/internal/matchers/text/FormattedText.java
new file mode 100644
index 0000000..37bca3d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/text/FormattedText.java
@@ -0,0 +1,18 @@
+package org.mockito.internal.matchers.text;
+
+/**
+ * Contains text that has already been formatted
+ * and hence it does not need any formatting (like quotes around string, etc.)
+ */
+class FormattedText {
+
+ private final String text;
+
+ public FormattedText(String text) {
+ this.text = text;
+ }
+
+ public String getText() {
+ return text;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/text/MatcherToString.java b/mockito-updated/src/org/mockito/internal/matchers/text/MatcherToString.java
new file mode 100644
index 0000000..f994ac9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/text/MatcherToString.java
@@ -0,0 +1,39 @@
+package org.mockito.internal.matchers.text;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.util.Decamelizer;
+import org.mockito.internal.util.ObjectMethodsGuru;
+
+import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
+
+import java.lang.reflect.Method;
+
+/**
+ * Provides better toString() text for matcher that don't have toString() method declared.
+ */
+class MatcherToString {
+
+ /**
+ * Attempts to provide more descriptive toString() for given matcher.
+ * Searches matcher class hierarchy for toString() method. If it is found it will be used.
+ * If no toString() is defined for the matcher hierarchy,
+ * uses decamelized class name instead of default Object.toString().
+ * This way we can promote meaningful names for custom matchers.
+ *
+ * @param matcher
+ * @return
+ */
+ static String toString(ArgumentMatcher<?> matcher) {
+ Class<?> cls = matcher.getClass();
+ while(cls != Object.class) {
+ Method[] methods = cls.getDeclaredMethods();
+ for (Method m : methods) {
+ if(isToStringMethod(m)) {
+ return matcher.toString();
+ }
+ }
+ cls = cls.getSuperclass();
+ }
+ return Decamelizer.decamelizeMatcher(matcher.getClass().getSimpleName());
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/text/MatchersPrinter.java b/mockito-updated/src/org/mockito/internal/matchers/text/MatchersPrinter.java
new file mode 100644
index 0000000..98194fc
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/text/MatchersPrinter.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.matchers.text;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.ContainsExtraTypeInfo;
+import org.mockito.internal.reporting.PrintSettings;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public class MatchersPrinter {
+
+ public String getArgumentsLine(List<ArgumentMatcher> matchers, PrintSettings printSettings) {
+ Iterator args = applyPrintSettings(matchers, printSettings);
+ return ValuePrinter.printValues("(", ", ", ");", args);
+ }
+
+ public String getArgumentsBlock(List<ArgumentMatcher> matchers, PrintSettings printSettings) {
+ Iterator args = applyPrintSettings(matchers, printSettings);
+ return ValuePrinter.printValues("(\n ", ",\n ", "\n);", args);
+ }
+
+ private Iterator<FormattedText> applyPrintSettings(List<ArgumentMatcher> matchers, PrintSettings printSettings) {
+ List<FormattedText> out = new LinkedList<FormattedText>();
+ int i = 0;
+ for (final ArgumentMatcher matcher : matchers) {
+ if (matcher instanceof ContainsExtraTypeInfo && printSettings.extraTypeInfoFor(i)) {
+ out.add(new FormattedText(((ContainsExtraTypeInfo) matcher).toStringWithType()));
+ } else {
+ out.add(new FormattedText(MatcherToString.toString(matcher)));
+ }
+ i++;
+ }
+ return out.iterator();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/matchers/text/ValuePrinter.java b/mockito-updated/src/org/mockito/internal/matchers/text/ValuePrinter.java
new file mode 100644
index 0000000..41ce403
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/matchers/text/ValuePrinter.java
@@ -0,0 +1,124 @@
+package org.mockito.internal.matchers.text;
+
+import java.util.Iterator;
+import java.util.Map;
+
+import static java.lang.String.valueOf;
+
+/**
+ * Prints a Java object value in a way humans can read it neatly.
+ * Inspired on hamcrest. Used for printing arguments in verification errors.
+ */
+public class ValuePrinter {
+
+ /**
+ * Prints given value so that it is neatly readable by humans.
+ * Handles explosive toString() implementations.
+ */
+ public static String print(Object value) {
+ if (value == null) {
+ return "null";
+ } else if (value instanceof String) {
+ return "\"" + value + "\"";
+ } else if (value instanceof Character) {
+ return printChar((Character) value);
+ } else if (value instanceof Long) {
+ return value + "L";
+ } else if (value instanceof Double) {
+ return value + "d";
+ } else if (value instanceof Float) {
+ return value + "f";
+ } else if (value instanceof Short) {
+ return "(short) " + value;
+ } else if (value instanceof Byte) {
+ return String.format("(byte) 0x%02X", (Byte) value);
+ } else if (value instanceof Map) {
+ return printMap((Map) value);
+ } else if (value.getClass().isArray()) {
+ return printValues("[", ", ", "]", new org.mockito.internal.matchers.text.ArrayIterator(value));
+ } else if (value instanceof FormattedText) {
+ return (((FormattedText) value).getText());
+ }
+
+ return descriptionOf(value);
+ }
+
+ private static String printMap(Map<?,?> map) {
+ StringBuilder result = new StringBuilder();
+ Iterator<? extends Map.Entry<?, ?>> iterator = map.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Map.Entry<?, ?> entry = iterator.next();
+ result.append(print(entry.getKey())).append(" = ").append(print(entry.getValue()));
+ if (iterator.hasNext()) {
+ result.append(", ");
+ }
+ }
+ return "{" + result.toString() + "}";
+ }
+
+ /**
+ * Print values in a nice format, e.g. (1, 2, 3)
+ *
+ * @param start the beginning of the values, e.g. "("
+ * @param separator the separator of values, e.g. ", "
+ * @param end the end of the values, e.g. ")"
+ * @param values the values to print
+ *
+ * @return neatly formatted value list
+ */
+ public static String printValues(String start, String separator, String end, Iterator values) {
+ if(start == null){
+ start = "(";
+ }
+ if (separator == null){
+ separator = ",";
+ }
+ if (end == null){
+ end = ")";
+ }
+ if (values == null){
+ values = new ArrayIterator(new String[]{""});
+ }
+
+ StringBuilder sb = new StringBuilder(start);
+ while(values.hasNext()) {
+ sb.append(print(values.next()));
+ if (values.hasNext()) {
+ sb.append(separator);
+ }
+ }
+ return sb.append(end).toString();
+ }
+
+ private static String printChar(char value) {
+ StringBuilder sb = new StringBuilder();
+ sb.append('\'');
+ switch (value) {
+ case '"':
+ sb.append("\\\"");
+ break;
+ case '\n':
+ sb.append("\\n");
+ break;
+ case '\r':
+ sb.append("\\r");
+ break;
+ case '\t':
+ sb.append("\\t");
+ break;
+ default:
+ sb.append(value);
+ }
+ sb.append('\'');
+ return sb.toString();
+ }
+
+ private static String descriptionOf(Object value) {
+ try {
+ return valueOf(value);
+ }
+ catch (Exception e) {
+ return value.getClass().getName() + "@" + Integer.toHexString(value.hashCode());
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/package.html b/mockito-updated/src/org/mockito/internal/package.html
new file mode 100644
index 0000000..bd8f199
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Internal classes, not to be used by clients.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/progress/ArgumentMatcherStorage.java b/mockito-updated/src/org/mockito/internal/progress/ArgumentMatcherStorage.java
new file mode 100644
index 0000000..4e47f58
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/ArgumentMatcherStorage.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.progress;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.LocalizedMatcher;
+
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public interface ArgumentMatcherStorage {
+
+ void reportMatcher(ArgumentMatcher<?> matcher);
+
+ List<LocalizedMatcher> pullLocalizedMatchers();
+
+ void reportAnd();
+
+ void reportNot();
+
+ void reportOr();
+
+ void validateState();
+
+ void reset();
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java b/mockito-updated/src/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java
new file mode 100644
index 0000000..e513856
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/ArgumentMatcherStorageImpl.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.progress;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.And;
+import org.mockito.internal.matchers.LocalizedMatcher;
+import org.mockito.internal.matchers.Not;
+import org.mockito.internal.matchers.Or;
+
+import static org.mockito.internal.exceptions.Reporter.incorrectUseOfAdditionalMatchers;
+import static org.mockito.internal.exceptions.Reporter.misplacedArgumentMatcher;
+import static org.mockito.internal.exceptions.Reporter.reportNoSubMatchersFound;
+
+import java.util.*;
+
+public class ArgumentMatcherStorageImpl implements ArgumentMatcherStorage {
+
+ public static final int TWO_SUB_MATCHERS = 2;
+ public static final int ONE_SUB_MATCHER = 1;
+ private final Stack<LocalizedMatcher> matcherStack = new Stack<LocalizedMatcher>();
+
+ public void reportMatcher(ArgumentMatcher matcher) {
+ matcherStack.push(new LocalizedMatcher(matcher));
+ }
+
+ public List<LocalizedMatcher> pullLocalizedMatchers() {
+ if (matcherStack.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ List<LocalizedMatcher> matchers = new ArrayList<LocalizedMatcher>(matcherStack);
+ matcherStack.clear();
+ return matchers;
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.progress.ArgumentMatcherStorage#reportAnd()
+ */
+ public void reportAnd() {
+ assertStateFor("And(?)", TWO_SUB_MATCHERS);
+ And and = new And(popLastArgumentMatchers(TWO_SUB_MATCHERS));
+ matcherStack.push(new LocalizedMatcher(and));
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.progress.ArgumentMatcherStorage#reportOr()
+ */
+ public void reportOr() {
+ assertStateFor("Or(?)", TWO_SUB_MATCHERS);
+ Or or = new Or(popLastArgumentMatchers(TWO_SUB_MATCHERS));
+ matcherStack.push(new LocalizedMatcher(or));
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.progress.ArgumentMatcherStorage#reportNot()
+ */
+ public void reportNot() {
+ assertStateFor("Not(?)", ONE_SUB_MATCHER);
+ Not not = new Not(popLastArgumentMatchers(ONE_SUB_MATCHER).get(0));
+ matcherStack.push(new LocalizedMatcher(not));
+ }
+
+ private void assertStateFor(String additionalMatcherName, int subMatchersCount) {
+ assertMatchersFoundFor(additionalMatcherName);
+ assertIncorrectUseOfAdditionalMatchers(additionalMatcherName, subMatchersCount);
+ }
+
+ private List<ArgumentMatcher> popLastArgumentMatchers(int count) {
+ LinkedList<ArgumentMatcher> result = new LinkedList<ArgumentMatcher>();
+ for (int i = 0; i < count; i++) {
+ result.addFirst(matcherStack.pop().getMatcher());
+ }
+ return result;
+ }
+
+ private void assertMatchersFoundFor(String additionalMatcherName) {
+ if (matcherStack.isEmpty()) {
+ matcherStack.clear();
+ throw reportNoSubMatchersFound(additionalMatcherName);
+ }
+ }
+
+ private void assertIncorrectUseOfAdditionalMatchers(String additionalMatcherName, int count) {
+ if(matcherStack.size() < count) {
+ ArrayList<LocalizedMatcher> lastMatchers = new ArrayList<LocalizedMatcher>(matcherStack);
+ matcherStack.clear();
+ throw incorrectUseOfAdditionalMatchers(additionalMatcherName, count, lastMatchers);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.progress.ArgumentMatcherStorage#validateState()
+ */
+ public void validateState() {
+ if (!matcherStack.isEmpty()) {
+ ArrayList<LocalizedMatcher> lastMatchers = new ArrayList<LocalizedMatcher>(matcherStack);
+ matcherStack.clear();
+ throw misplacedArgumentMatcher(lastMatchers);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.progress.ArgumentMatcherStorage#reset()
+ */
+ public void reset() {
+ matcherStack.clear();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/progress/MockingProgress.java b/mockito-updated/src/org/mockito/internal/progress/MockingProgress.java
new file mode 100644
index 0000000..07e0342
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/MockingProgress.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.progress;
+
+import org.mockito.invocation.Invocation;
+import org.mockito.listeners.MockitoListener;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.OngoingStubbing;
+import org.mockito.verification.VerificationMode;
+import org.mockito.verification.VerificationStrategy;
+
+public interface MockingProgress {
+
+ void reportOngoingStubbing(OngoingStubbing<?> ongoingStubbing);
+
+ OngoingStubbing<?> pullOngoingStubbing();
+
+ void verificationStarted(VerificationMode verificationMode);
+
+ VerificationMode pullVerificationMode();
+
+ void stubbingStarted();
+
+ void stubbingCompleted(Invocation invocation);
+
+ void validateState();
+
+ void reset();
+
+ /**
+ * Removes ongoing stubbing so that in case the framework is misused
+ * state validation errors are more accurate
+ */
+ void resetOngoingStubbing();
+
+ ArgumentMatcherStorage getArgumentMatcherStorage();
+
+ void mockingStarted(Object mock, MockCreationSettings settings);
+
+ void addListener(MockitoListener listener);
+
+ void removeListener(MockitoListener listener);
+
+ void setVerificationStrategy(VerificationStrategy strategy);
+
+ VerificationMode maybeVerifyLazily(VerificationMode mode);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/progress/MockingProgressImpl.java b/mockito-updated/src/org/mockito/internal/progress/MockingProgressImpl.java
new file mode 100644
index 0000000..9345c71
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/MockingProgressImpl.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.progress;
+
+import org.mockito.internal.configuration.GlobalConfiguration;
+import org.mockito.internal.debugging.Localized;
+import org.mockito.internal.debugging.LocationImpl;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
+import org.mockito.listeners.MockCreationListener;
+import org.mockito.listeners.MockitoListener;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.OngoingStubbing;
+import org.mockito.verification.VerificationMode;
+import org.mockito.verification.VerificationStrategy;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import static org.mockito.internal.exceptions.Reporter.unfinishedStubbing;
+import static org.mockito.internal.exceptions.Reporter.unfinishedVerificationException;
+
+@SuppressWarnings("unchecked")
+public class MockingProgressImpl implements MockingProgress {
+
+ private final ArgumentMatcherStorage argumentMatcherStorage = new ArgumentMatcherStorageImpl();
+
+ private OngoingStubbing<?> ongoingStubbing;
+ private Localized<VerificationMode> verificationMode;
+ private Location stubbingInProgress = null;
+ private VerificationStrategy verificationStrategy;
+ private final Set<MockitoListener> listeners = new LinkedHashSet<MockitoListener>();
+
+ public MockingProgressImpl() {
+ this.verificationStrategy = getDefaultVerificationStrategy();
+ }
+
+ public static VerificationStrategy getDefaultVerificationStrategy() {
+ return new VerificationStrategy() {
+ public VerificationMode maybeVerifyLazily(VerificationMode mode) {
+ return mode;
+ }
+ };
+ }
+ public void reportOngoingStubbing(OngoingStubbing iOngoingStubbing) {
+ this.ongoingStubbing = iOngoingStubbing;
+ }
+
+ public OngoingStubbing<?> pullOngoingStubbing() {
+ OngoingStubbing<?> temp = ongoingStubbing;
+ ongoingStubbing = null;
+ return temp;
+ }
+
+ public void verificationStarted(VerificationMode verify) {
+ validateState();
+ resetOngoingStubbing();
+ verificationMode = new Localized(verify);
+ }
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.progress.MockingProgress#resetOngoingStubbing()
+ */
+ public void resetOngoingStubbing() {
+ ongoingStubbing = null;
+ }
+
+ public VerificationMode pullVerificationMode() {
+ if (verificationMode == null) {
+ return null;
+ }
+
+ VerificationMode temp = verificationMode.getObject();
+ verificationMode = null;
+ return temp;
+ }
+
+ public void stubbingStarted() {
+ validateState();
+ stubbingInProgress = new LocationImpl();
+ }
+
+ public void validateState() {
+ validateMostStuff();
+
+ //validate stubbing:
+ if (stubbingInProgress != null) {
+ Location temp = stubbingInProgress;
+ stubbingInProgress = null;
+ throw unfinishedStubbing(temp);
+ }
+ }
+
+ private void validateMostStuff() {
+ //State is cool when GlobalConfiguration is already loaded
+ //this cannot really be tested functionally because I cannot dynamically mess up org.mockito.configuration.MockitoConfiguration class
+ GlobalConfiguration.validate();
+
+ if (verificationMode != null) {
+ Location location = verificationMode.getLocation();
+ verificationMode = null;
+ throw unfinishedVerificationException(location);
+ }
+
+ getArgumentMatcherStorage().validateState();
+ }
+
+ public void stubbingCompleted(Invocation invocation) {
+ stubbingInProgress = null;
+ }
+
+ public String toString() {
+ return "iOngoingStubbing: " + ongoingStubbing +
+ ", verificationMode: " + verificationMode +
+ ", stubbingInProgress: " + stubbingInProgress;
+ }
+
+ public void reset() {
+ stubbingInProgress = null;
+ verificationMode = null;
+ getArgumentMatcherStorage().reset();
+ }
+
+ public ArgumentMatcherStorage getArgumentMatcherStorage() {
+ return argumentMatcherStorage;
+ }
+
+ public void mockingStarted(Object mock, MockCreationSettings settings) {
+ for (MockitoListener listener : listeners) {
+ if (listener instanceof MockCreationListener) {
+ ((MockCreationListener) listener).onMockCreated(mock, settings);
+ }
+ }
+ validateMostStuff();
+ }
+
+ public void addListener(MockitoListener listener) {
+ this.listeners.add(listener);
+ }
+
+ public void removeListener(MockitoListener listener) {
+ this.listeners.remove(listener);
+ }
+
+ public void setVerificationStrategy(VerificationStrategy strategy) {
+ this.verificationStrategy = strategy;
+ }
+
+ public VerificationMode maybeVerifyLazily(VerificationMode mode) {
+ return this.verificationStrategy.maybeVerifyLazily(mode);
+ }
+
+ /*
+
+ //TODO 545 thread safety of all mockito
+
+ use cases:
+ - single threaded execution throughout
+ - single threaded mock creation, stubbing & verification, multi-threaded interaction with mock
+ - thread per test case
+
+ */
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/progress/SequenceNumber.java b/mockito-updated/src/org/mockito/internal/progress/SequenceNumber.java
new file mode 100644
index 0000000..f364dc0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/SequenceNumber.java
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.progress;
+
+public class SequenceNumber {
+
+ private static int sequenceNumber = 1;
+
+ public static synchronized int next() {
+ return sequenceNumber++;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/progress/ThreadSafeMockingProgress.java b/mockito-updated/src/org/mockito/internal/progress/ThreadSafeMockingProgress.java
new file mode 100644
index 0000000..ddbc813
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/ThreadSafeMockingProgress.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.progress;
+
+/**
+ * Provides access to the {@link MockingProgress} of a corresponding {@link Thread}. Every {@link Thread} in Mockito has it s own {@link MockingProgress} to avoid data races while stubbing.
+ */
+public class ThreadSafeMockingProgress {
+
+ private static final ThreadLocal<MockingProgress> MOCKING_PROGRESS_PROVIDER = new ThreadLocal<MockingProgress>() {
+ @Override
+ protected MockingProgress initialValue() {
+ return new MockingProgressImpl();
+ }
+ };
+
+ private ThreadSafeMockingProgress() {
+ }
+
+ /**
+ * Returns the {@link MockingProgress} for the current Thread.
+ * <p>
+ * <b>IMPORTANT</b>: Never assign and access the returned {@link MockingProgress} to an instance or static field. Thread safety can not be guaranteed in this case, cause the Thread that wrote the field might not be the same that read it. In other words multiple threads will access the same {@link MockingProgress}.
+ *
+ * @return never <code>null</code>
+ */
+ public final static MockingProgress mockingProgress() {
+ return MOCKING_PROGRESS_PROVIDER.get();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/progress/package.html b/mockito-updated/src/org/mockito/internal/progress/package.html
new file mode 100644
index 0000000..0db3625
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/progress/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Mocking progress stateful classes.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/reporting/Discrepancy.java b/mockito-updated/src/org/mockito/internal/reporting/Discrepancy.java
new file mode 100644
index 0000000..49f57fd
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/reporting/Discrepancy.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.reporting;
+
+public class Discrepancy {
+
+ private final int wantedCount;
+ private final int actualCount;
+
+ public Discrepancy(int wantedCount, int actualCount) {
+ this.wantedCount = wantedCount;
+ this.actualCount = actualCount;
+ }
+
+ public int getWantedCount() {
+ return wantedCount;
+ }
+
+ public String getPluralizedWantedCount() {
+ return Pluralizer.pluralize(wantedCount);
+ }
+
+ public int getActualCount() {
+ return actualCount;
+ }
+
+ public String getPluralizedActualCount() {
+ return Pluralizer.pluralize(actualCount);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/reporting/Pluralizer.java b/mockito-updated/src/org/mockito/internal/reporting/Pluralizer.java
new file mode 100644
index 0000000..1e8d0e3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/reporting/Pluralizer.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.reporting;
+
+public class Pluralizer {
+
+ public static String pluralize(int number) {
+ return number == 1 ? "1 time" : number + " times";
+ }
+
+ public static String were_exactly_x_interactions(int x) {
+ if (x == 1) {
+ return "was exactly 1 interaction";
+ } else {
+ return "were exactly " + x + " interactions";
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/reporting/PrintSettings.java b/mockito-updated/src/org/mockito/internal/reporting/PrintSettings.java
new file mode 100644
index 0000000..c90e8c7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/reporting/PrintSettings.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.reporting;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.invocation.ArgumentsProcessor;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.matchers.text.MatchersPrinter;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.invocation.Invocation;
+
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+
+public class PrintSettings {
+
+ public static final int MAX_LINE_LENGTH = 45;
+ private boolean multiline;
+ private List<Integer> withTypeInfo = new LinkedList<Integer>();
+
+ public void setMultiline(boolean multiline) {
+ this.multiline = multiline;
+ }
+
+ public boolean isMultiline() {
+ return multiline;
+ }
+
+ public static PrintSettings verboseMatchers(Integer ... indexesOfMatchers) {
+ PrintSettings settings = new PrintSettings();
+ settings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchers);
+ return settings;
+ }
+
+ public boolean extraTypeInfoFor(int argumentIndex) {
+ return withTypeInfo.contains(argumentIndex);
+ }
+
+ public void setMatchersToBeDescribedWithExtraTypeInfo(Integer[] indexesOfMatchers) {
+ this.withTypeInfo = Arrays.asList(indexesOfMatchers);
+ }
+
+ public String print(List<ArgumentMatcher> matchers, Invocation invocation) {
+ MatchersPrinter matchersPrinter = new MatchersPrinter();
+ String qualifiedName = MockUtil.getMockName(invocation.getMock()) + "." + invocation.getMethod().getName();
+ String invocationString = qualifiedName + matchersPrinter.getArgumentsLine(matchers, this);
+ if (isMultiline() || (!matchers.isEmpty() && invocationString.length() > MAX_LINE_LENGTH)) {
+ return qualifiedName + matchersPrinter.getArgumentsBlock(matchers, this);
+ } else {
+ return invocationString;
+ }
+ }
+
+ public String print(Invocation invocation) {
+ return print(ArgumentsProcessor.argumentsToMatchers(invocation.getArguments()), invocation);
+ }
+
+ public String print(InvocationMatcher invocationMatcher) {
+ return print(invocationMatcher.getMatchers(), invocationMatcher.getInvocation());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/reporting/SmartPrinter.java b/mockito-updated/src/org/mockito/internal/reporting/SmartPrinter.java
new file mode 100644
index 0000000..5e01fb8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/reporting/SmartPrinter.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.reporting;
+
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+/**
+ * Makes sure both wanted and actual are printed consistently (single line or multiline)
+ * <p>
+ * Makes arguments printed with types if necessary
+ */
+public class SmartPrinter {
+
+ private final String wanted;
+ private final String actual;
+
+ public SmartPrinter(InvocationMatcher wanted, Invocation actual, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) {
+ PrintSettings printSettings = new PrintSettings();
+ printSettings.setMultiline(wanted.toString().contains("\n") || actual.toString().contains("\n"));
+ printSettings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchersToBeDescribedWithExtraTypeInfo);
+
+ this.wanted = printSettings.print(wanted);
+ this.actual = printSettings.print(actual);
+ }
+
+ public String getWanted() {
+ return wanted;
+ }
+
+ public String getActual() {
+ return actual;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/reporting/package.html b/mockito-updated/src/org/mockito/internal/reporting/package.html
new file mode 100644
index 0000000..92b9096
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/reporting/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Deals with nicely printing verification errors
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/RunnerFactory.java b/mockito-updated/src/org/mockito/internal/runners/RunnerFactory.java
new file mode 100644
index 0000000..c51afc9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/RunnerFactory.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.runners.util.RunnerProvider;
+
+import java.lang.reflect.InvocationTargetException;
+
+import static org.mockito.internal.runners.util.TestMethodsFinder.hasTestMethods;
+
+/**
+ * Creates instances of Mockito JUnit Runner in a safe way, e.g. detecting inadequate version of JUnit, etc.
+ */
+public class RunnerFactory {
+
+ public RunnerImpl create(Class<?> klass) throws InvocationTargetException {
+ try {
+ return new RunnerProvider().newInstance("org.mockito.internal.runners.SilentJUnitRunner", klass);
+ } catch (InvocationTargetException e) {
+ if (!hasTestMethods(klass)) {
+ throw new MockitoException(
+ "\n" +
+ "\n" +
+ "No tests found in " + klass.getSimpleName() + "\n" +
+ "Haven't you forgot @Test annotation?\n"
+ , e);
+ }
+ throw e;
+ } catch (Throwable t) {
+ throw new MockitoException(
+ "\n" +
+ "\n" +
+ "MockitoRunner can only be used with JUnit 4.5 or higher.\n" +
+ "You can upgrade your JUnit version or write your own Runner (please consider contributing your runner to the Mockito community).\n" +
+ "Bear in mind that you can still enjoy all features of the framework without using runners (they are completely optional).\n" +
+ "If you get this error despite using JUnit 4.5 or higher then please report this error to the mockito mailing list.\n"
+ , t);
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/RunnerImpl.java b/mockito-updated/src/org/mockito/internal/runners/RunnerImpl.java
new file mode 100644
index 0000000..9443650
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/RunnerImpl.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners;
+
+import org.junit.runner.Description;
+import org.junit.runner.manipulation.Filterable;
+import org.junit.runner.notification.RunNotifier;
+
+/**
+ * I'm using this surrogate interface to hide internal Runner implementations.
+ * Surrogate cannot be used with @RunWith therefore it is less likely clients will use interal runners.
+ */
+public interface RunnerImpl extends Filterable{
+
+ void run(RunNotifier notifier);
+
+ Description getDescription();
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/SilentJUnitRunner.java b/mockito-updated/src/org/mockito/internal/runners/SilentJUnitRunner.java
new file mode 100644
index 0000000..658800f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/SilentJUnitRunner.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners;
+
+import org.junit.runner.Description;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.BlockJUnit4ClassRunner;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.InitializationError;
+import org.junit.runners.model.Statement;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.runners.util.FrameworkUsageValidator;
+
+public class SilentJUnitRunner implements RunnerImpl {
+
+ private final BlockJUnit4ClassRunner runner;
+ private final Class<?> testClass;
+
+ public SilentJUnitRunner(Class<?> testClass) throws InitializationError {
+ this.testClass = testClass;
+ runner = new BlockJUnit4ClassRunner(testClass) {
+ protected Statement withBefores(FrameworkMethod method, Object target,
+ Statement statement) {
+ // init annotated mocks before tests
+ MockitoAnnotations.initMocks(target);
+ return super.withBefores(method, target, statement);
+ }
+ };
+ }
+
+ public void run(final RunNotifier notifier) {
+ FrameworkUsageValidator listener = new FrameworkUsageValidator(notifier);
+ // add listener that validates framework usage at the end of each test
+ notifier.addListener(listener);
+ runner.run(notifier);
+ }
+
+ public Description getDescription() {
+ return runner.getDescription();
+ }
+
+ public void filter(Filter filter) throws NoTestsRemainException {
+ runner.filter(filter);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/StrictRunner.java b/mockito-updated/src/org/mockito/internal/runners/StrictRunner.java
new file mode 100644
index 0000000..0c4a347
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/StrictRunner.java
@@ -0,0 +1,57 @@
+package org.mockito.internal.runners;
+
+import org.junit.runner.Description;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runner.notification.RunNotifier;
+import org.mockito.Mockito;
+import org.mockito.internal.junit.UnnecessaryStubbingsReporter;
+import org.mockito.internal.runners.util.FailureDetector;
+
+public class StrictRunner implements RunnerImpl {
+
+ private final Class<?> testClass;
+ private final RunnerImpl runner;
+ private boolean filterRequested;
+
+ /**
+ * @param runner - the runner to wrap around
+ * @param testClass - for reporting purposes
+ */
+ public StrictRunner(RunnerImpl runner, Class<?> testClass) {
+ this.runner = runner;
+ this.testClass = 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();
+ FailureDetector listener = new FailureDetector();
+
+ Mockito.framework().addListener(reporter);
+ try {
+ // add listener that detects test failures
+ notifier.addListener(listener);
+ runner.run(notifier);
+ } finally {
+ Mockito.framework().removeListener(reporter);
+ }
+
+ if (!filterRequested && listener.isSuccessful()) {
+ //only report when:
+ //1. if all tests from given test have ran (filter requested is false)
+ // Otherwise we would report unnecessary stubs even if the user runs just single test from the class
+ //2. tests are successful (we don't want to add an extra failure on top of any existing failure, to avoid confusion)
+ reporter.validateUnusedStubs(testClass, notifier);
+ }
+ }
+
+ public Description getDescription() {
+ return runner.getDescription();
+ }
+
+ public void filter(Filter filter) throws NoTestsRemainException {
+ filterRequested = true;
+ runner.filter(filter);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/runners/package.html b/mockito-updated/src/org/mockito/internal/runners/package.html
new file mode 100644
index 0000000..6a1b89e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Internal classes for runners implementations
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/util/FailureDetector.java b/mockito-updated/src/org/mockito/internal/runners/util/FailureDetector.java
new file mode 100644
index 0000000..14d4eba
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/util/FailureDetector.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners.util;
+
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+
+/**
+ * Implementation of JUnit run listener that knows when any of the tests failed
+ */
+public class FailureDetector extends RunListener {
+
+ private boolean failed;
+
+ @Override
+ public void testFailure(Failure failure) throws Exception {
+ super.testFailure(failure);
+ failed = true;
+ }
+
+ public boolean isSuccessful() {
+ return !failed;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/runners/util/FrameworkUsageValidator.java b/mockito-updated/src/org/mockito/internal/runners/util/FrameworkUsageValidator.java
new file mode 100644
index 0000000..b156162
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/util/FrameworkUsageValidator.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners.util;
+
+import org.junit.runner.Description;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+import org.junit.runner.notification.RunNotifier;
+import org.mockito.Mockito;
+
+/**
+ * Implementation of JUnit run listener that validates Mockito usage after each test
+ */
+public class FrameworkUsageValidator extends RunListener {
+
+ private final RunNotifier notifier;
+ private boolean failed;
+
+ public FrameworkUsageValidator(RunNotifier notifier) {
+ this.notifier = notifier;
+ }
+
+ @Override
+ public void testFailure(Failure failure) throws Exception {
+ super.testFailure(failure);
+ failed = true;
+ }
+
+ @Override
+ public void testFinished(Description description) throws Exception {
+ super.testFinished(description);
+ try {
+ Mockito.validateMockitoUsage();
+ } catch(Throwable t) {
+ notifier.fireTestFailure(new Failure(description, t));
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/util/RunnerProvider.java b/mockito-updated/src/org/mockito/internal/runners/util/RunnerProvider.java
new file mode 100644
index 0000000..00a34b7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/util/RunnerProvider.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners.util;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+import org.mockito.internal.runners.RunnerImpl;
+
+public class RunnerProvider {
+
+ public RunnerImpl newInstance(String runnerClassName, Class<?> constructorParam) throws Exception {
+ Constructor<?> constructor;
+ try {
+ Class<?> runnerClass = Class.forName(runnerClassName);
+ constructor = runnerClass.getConstructor(Class.class.getClass());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ return (RunnerImpl) constructor.newInstance(constructorParam);
+ } catch (InvocationTargetException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/runners/util/TestMethodsFinder.java b/mockito-updated/src/org/mockito/internal/runners/util/TestMethodsFinder.java
new file mode 100644
index 0000000..f435df3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/util/TestMethodsFinder.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.runners.util;
+
+import org.junit.Test;
+
+import java.lang.reflect.Method;
+
+public class TestMethodsFinder {
+
+ private TestMethodsFinder() {}
+
+ public static boolean hasTestMethods(Class<?> klass) {
+ Method[] methods = klass.getMethods();
+ for(Method m:methods) {
+ if (m.isAnnotationPresent(Test.class)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/runners/util/package.html b/mockito-updated/src/org/mockito/internal/runners/util/package.html
new file mode 100644
index 0000000..b6c4110
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/runners/util/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Internal utils for runner implementations
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/BaseStubbing.java b/mockito-updated/src/org/mockito/internal/stubbing/BaseStubbing.java
new file mode 100644
index 0000000..6e58596
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/BaseStubbing.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import org.mockito.internal.stubbing.answers.CallsRealMethods;
+import org.mockito.internal.stubbing.answers.Returns;
+import org.mockito.internal.stubbing.answers.ThrowsException;
+import org.mockito.internal.stubbing.answers.ThrowsExceptionClass;
+import org.mockito.stubbing.OngoingStubbing;
+
+public abstract class BaseStubbing<T> implements OngoingStubbing<T> {
+
+ public OngoingStubbing<T> thenReturn(T value) {
+ return thenAnswer(new Returns(value));
+ }
+
+ @SuppressWarnings({"unchecked","vararg"})
+ public OngoingStubbing<T> thenReturn(T value, T... values) {
+ OngoingStubbing<T> stubbing = thenReturn(value);
+ if (values == null) {
+ //TODO below does not seem right
+ return stubbing.thenReturn(null);
+ }
+ for (T v: values) {
+ stubbing = stubbing.thenReturn(v);
+ }
+ return stubbing;
+ }
+
+ private OngoingStubbing<T> thenThrow(Throwable throwable) {
+ return thenAnswer(new ThrowsException(throwable));
+ }
+
+ public OngoingStubbing<T> thenThrow(Throwable... throwables) {
+ if (throwables == null) {
+ return thenThrow((Throwable) null);
+ }
+ OngoingStubbing<T> stubbing = null;
+ for (Throwable t: throwables) {
+ if (stubbing == null) {
+ stubbing = thenThrow(t);
+ } else {
+ stubbing = stubbing.thenThrow(t);
+ }
+ }
+ return stubbing;
+ }
+
+ public OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType) {
+ return thenAnswer(new ThrowsExceptionClass(throwableType));
+ }
+
+ @SuppressWarnings ({"unchecked", "varargs"})
+ public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
+ if (nextToBeThrown == null) {
+ thenThrow((Throwable) null);
+ }
+ OngoingStubbing<T> stubbing = thenThrow(toBeThrown);
+ for (Class<? extends Throwable> t: nextToBeThrown) {
+ stubbing = stubbing.thenThrow(t);
+ }
+ return stubbing;
+ }
+
+ public OngoingStubbing<T> thenCallRealMethod() {
+ return thenAnswer(new CallsRealMethods());
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/ConsecutiveStubbing.java b/mockito-updated/src/org/mockito/internal/stubbing/ConsecutiveStubbing.java
new file mode 100644
index 0000000..aac220d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/ConsecutiveStubbing.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.OngoingStubbing;
+
+public class ConsecutiveStubbing<T> extends BaseStubbing<T> {
+ private final InvocationContainerImpl invocationContainerImpl;
+
+ public ConsecutiveStubbing(InvocationContainerImpl invocationContainerImpl) {
+ this.invocationContainerImpl = invocationContainerImpl;
+ }
+
+ public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
+ invocationContainerImpl.addConsecutiveAnswer(answer);
+ return this;
+ }
+
+ public OngoingStubbing<T> then(Answer<?> answer) {
+ return thenAnswer(answer);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <M> M getMock() {
+ return (M) invocationContainerImpl.invokedMock();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/InvocationContainer.java b/mockito-updated/src/org/mockito/internal/stubbing/InvocationContainer.java
new file mode 100644
index 0000000..b926183
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/InvocationContainer.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import org.mockito.invocation.Invocation;
+
+import java.util.List;
+
+//TODO move to different package
+public interface InvocationContainer {
+ List<Invocation> getInvocations();
+
+ void clearInvocations();
+
+ List<StubbedInvocationMatcher> getStubbedInvocations();
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/InvocationContainerImpl.java b/mockito-updated/src/org/mockito/internal/stubbing/InvocationContainerImpl.java
new file mode 100644
index 0000000..c9363ae
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/InvocationContainerImpl.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.invocation.StubInfoImpl;
+import org.mockito.internal.stubbing.answers.AnswersValidator;
+import org.mockito.internal.verification.DefaultRegisteredInvocations;
+import org.mockito.internal.verification.RegisteredInvocations;
+import org.mockito.internal.verification.SingleRegisteredInvocation;
+import org.mockito.invocation.Invocation;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
+
+@SuppressWarnings("unchecked")
+public class InvocationContainerImpl implements InvocationContainer, Serializable {
+
+ private static final long serialVersionUID = -5334301962749537177L;
+ private final LinkedList<StubbedInvocationMatcher> stubbed = new LinkedList<StubbedInvocationMatcher>();
+ private final List<Answer<?>> answersForStubbing = new ArrayList<Answer<?>>();
+ private final RegisteredInvocations registeredInvocations;
+
+ private InvocationMatcher invocationForStubbing;
+
+ public InvocationContainerImpl(MockCreationSettings mockSettings) {
+ this.registeredInvocations = createRegisteredInvocations(mockSettings);
+ }
+
+ public void setInvocationForPotentialStubbing(InvocationMatcher invocation) {
+ registeredInvocations.add(invocation.getInvocation());
+ this.invocationForStubbing = invocation;
+ }
+
+ public void resetInvocationForPotentialStubbing(InvocationMatcher invocationMatcher) {
+ this.invocationForStubbing = invocationMatcher;
+ }
+
+ public void addAnswer(Answer answer) {
+ registeredInvocations.removeLast();
+ addAnswer(answer, false);
+ }
+
+ public void addConsecutiveAnswer(Answer answer) {
+ addAnswer(answer, true);
+ }
+
+ public void addAnswer(Answer answer, boolean isConsecutive) {
+ Invocation invocation = invocationForStubbing.getInvocation();
+ mockingProgress().stubbingCompleted(invocation);
+ AnswersValidator answersValidator = new AnswersValidator();
+ answersValidator.validate(answer, invocation);
+
+ synchronized (stubbed) {
+ if (isConsecutive) {
+ stubbed.getFirst().addAnswer(answer);
+ } else {
+ stubbed.addFirst(new StubbedInvocationMatcher(invocationForStubbing, answer));
+ }
+ }
+ }
+
+ Object answerTo(Invocation invocation) throws Throwable {
+ return findAnswerFor(invocation).answer(invocation);
+ }
+
+ public StubbedInvocationMatcher findAnswerFor(Invocation invocation) {
+ synchronized (stubbed) {
+ for (StubbedInvocationMatcher s : stubbed) {
+ if (s.matches(invocation)) {
+ s.markStubUsed(invocation);
+ invocation.markStubbed(new StubInfoImpl(s));
+ return s;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public void addAnswerForVoidMethod(Answer answer) {
+ answersForStubbing.add(answer);
+ }
+
+ public void setAnswersForStubbing(List<Answer<?>> answers) {
+ answersForStubbing.addAll(answers);
+ }
+
+ public boolean hasAnswersForStubbing() {
+ return !answersForStubbing.isEmpty();
+ }
+
+ public boolean hasInvocationForPotentialStubbing() {
+ return !registeredInvocations.isEmpty();
+ }
+
+ public void setMethodForStubbing(InvocationMatcher invocation) {
+ invocationForStubbing = invocation;
+ assert hasAnswersForStubbing();
+ for (int i = 0; i < answersForStubbing.size(); i++) {
+ addAnswer(answersForStubbing.get(i), i != 0);
+ }
+ answersForStubbing.clear();
+ }
+
+ @Override
+ public String toString() {
+ return "invocationForStubbing: " + invocationForStubbing;
+ }
+
+ public List<Invocation> getInvocations() {
+ return registeredInvocations.getAll();
+ }
+
+ public void clearInvocations() {
+ registeredInvocations.clear();
+ }
+
+ public List<StubbedInvocationMatcher> getStubbedInvocations() {
+ return stubbed;
+ }
+
+ public Object invokedMock() {
+ return invocationForStubbing.getInvocation().getMock();
+ }
+
+ public InvocationMatcher getInvocationForStubbing() {
+ return invocationForStubbing;
+ }
+
+ private RegisteredInvocations createRegisteredInvocations(MockCreationSettings mockSettings) {
+ return mockSettings.isStubOnly()
+ ? new SingleRegisteredInvocation()
+ : new DefaultRegisteredInvocations();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/OngoingStubbingImpl.java b/mockito-updated/src/org/mockito/internal/stubbing/OngoingStubbingImpl.java
new file mode 100644
index 0000000..037e98a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/OngoingStubbingImpl.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import org.mockito.invocation.Invocation;
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.OngoingStubbing;
+
+import static org.mockito.internal.exceptions.Reporter.incorrectUseOfApi;
+
+import java.util.List;
+
+public class OngoingStubbingImpl<T> extends BaseStubbing<T> {
+
+ private final InvocationContainerImpl invocationContainerImpl;
+
+ public OngoingStubbingImpl(InvocationContainerImpl invocationContainerImpl) {
+ this.invocationContainerImpl = invocationContainerImpl;
+ }
+
+ public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
+ if(!invocationContainerImpl.hasInvocationForPotentialStubbing()) {
+ throw incorrectUseOfApi();
+ }
+
+ invocationContainerImpl.addAnswer(answer);
+ return new ConsecutiveStubbing<T>(invocationContainerImpl);
+ }
+
+ public OngoingStubbing<T> then(Answer<?> answer) {
+ return thenAnswer(answer);
+ }
+
+ public List<Invocation> getRegisteredInvocations() {
+ //TODO interface for tests
+ return invocationContainerImpl.getInvocations();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <M> M getMock() {
+ return (M) invocationContainerImpl.invokedMock();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/StubbedInvocationMatcher.java b/mockito-updated/src/org/mockito/internal/stubbing/StubbedInvocationMatcher.java
new file mode 100644
index 0000000..d10cdc0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/StubbedInvocationMatcher.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.stubbing.Stubbing;
+import org.mockito.invocation.DescribedInvocation;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+@SuppressWarnings("unchecked")
+public class StubbedInvocationMatcher extends InvocationMatcher implements Answer, Serializable, Stubbing {
+
+ private static final long serialVersionUID = 4919105134123672727L;
+ private final Queue<Answer> answers = new ConcurrentLinkedQueue<Answer>();
+ private DescribedInvocation usedAt;
+
+ public StubbedInvocationMatcher(InvocationMatcher invocation, Answer answer) {
+ super(invocation.getInvocation(), invocation.getMatchers());
+ this.answers.add(answer);
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ //see ThreadsShareGenerouslyStubbedMockTest
+ Answer a;
+ synchronized(answers) {
+ a = answers.size() == 1 ? answers.peek() : answers.poll();
+ }
+ return a.answer(invocation);
+ }
+
+ public void addAnswer(Answer answer) {
+ answers.add(answer);
+ }
+
+ public void markStubUsed(DescribedInvocation usedAt) {
+ this.usedAt = usedAt;
+ }
+
+ public boolean wasUsed() {
+ return usedAt != null;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + " stubbed with: " + answers;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/StubberImpl.java b/mockito-updated/src/org/mockito/internal/stubbing/StubberImpl.java
new file mode 100644
index 0000000..c6f02e1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/StubberImpl.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing;
+
+import static org.mockito.internal.exceptions.Reporter.notAMockPassedToWhenMethod;
+import static org.mockito.internal.exceptions.Reporter.nullPassedToWhenMethod;
+
+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;
+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<?>>();
+
+ public <T> T when(T mock) {
+ if (mock == null) {
+ throw nullPassedToWhenMethod();
+ }
+
+ if (!MockUtil.isMock(mock)) {
+ throw notAMockPassedToWhenMethod();
+ }
+
+ MockUtil.getMockHandler(mock).setAnswersForStubbing(answers);
+ return mock;
+ }
+
+ public Stubber doReturn(Object toBeReturned) {
+ return doReturnValues(toBeReturned);
+ }
+
+ public Stubber doReturn(Object toBeReturned, Object... nextToBeReturned) {
+ return doReturnValues(toBeReturned).doReturnValues(nextToBeReturned);
+ }
+
+ private StubberImpl doReturnValues(Object... toBeReturned) {
+ if(toBeReturned == null) {
+ answers.add(new Returns(null));
+ return this;
+ }
+ for (Object r : toBeReturned) {
+ answers.add(new Returns(r));
+ }
+ return this;
+ }
+
+ public Stubber doThrow(Throwable... toBeThrown) {
+ if(toBeThrown == null) {
+ answers.add(new ThrowsException(null));
+ return this;
+ }
+ for (Throwable throwable : toBeThrown) {
+ answers.add(new ThrowsException(throwable));
+ }
+ return this;
+ }
+
+ public Stubber doThrow(Class<? extends Throwable> toBeThrown) {
+ return doThrowClasses(toBeThrown);
+ }
+
+ public Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
+ return doThrowClasses(toBeThrown).doThrowClasses(nextToBeThrown);
+ }
+
+ private StubberImpl doThrowClasses(Class<? extends Throwable>... toBeThrown) {
+ for (Class<? extends Throwable> throwable: toBeThrown) {
+ answers.add(new ThrowsExceptionClass(throwable));
+ }
+ return this;
+ }
+
+ public Stubber doNothing() {
+ answers.add(new DoesNothing());
+ return this;
+ }
+
+ public Stubber doAnswer(Answer answer) {
+ answers.add(answer);
+ return this;
+ }
+
+ public Stubber doCallRealMethod() {
+ answers.add(new CallsRealMethods());
+ return this;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/StubbingComparator.java b/mockito-updated/src/org/mockito/internal/stubbing/StubbingComparator.java
new file mode 100644
index 0000000..6410d48
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/StubbingComparator.java
@@ -0,0 +1,18 @@
+package org.mockito.internal.stubbing;
+
+import org.mockito.internal.invocation.InvocationComparator;
+import org.mockito.stubbing.Stubbing;
+
+import java.util.Comparator;
+
+/**
+ * Compares stubbings based on {@link InvocationComparator}
+ */
+public class StubbingComparator implements Comparator<Stubbing> {
+
+ private final InvocationComparator invocationComparator = new InvocationComparator();
+
+ public int compare(Stubbing o1, Stubbing o2) {
+ return invocationComparator.compare(o1.getInvocation(), o2.getInvocation());
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java
new file mode 100644
index 0000000..9ae93fc
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/AnswerFunctionalInterfaces.java
@@ -0,0 +1,235 @@
+package org.mockito.internal.stubbing.answers;
+
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.mockito.stubbing.Answer1;
+import org.mockito.stubbing.Answer2;
+import org.mockito.stubbing.Answer3;
+import org.mockito.stubbing.Answer4;
+import org.mockito.stubbing.Answer5;
+import org.mockito.stubbing.VoidAnswer1;
+import org.mockito.stubbing.VoidAnswer2;
+import org.mockito.stubbing.VoidAnswer3;
+import org.mockito.stubbing.VoidAnswer4;
+import org.mockito.stubbing.VoidAnswer5;
+
+/**
+ * Functional interfaces to make it easy to implement answers in Java 8
+ *
+ * @since 2.1.0
+ */
+public class AnswerFunctionalInterfaces {
+ /**
+ * Hide constructor to avoid instantiation of class with only static methods
+ */
+ private AnswerFunctionalInterfaces() {
+ }
+
+ /**
+ * Construct an answer from a two parameter answer interface
+ * @param answer answer interface
+ * @param <T> return type
+ * @param <A> input parameter 1 type
+ * @return a new answer object
+ */
+ public static <T, A> Answer<T> toAnswer(final Answer1<T, A> answer) {
+ return new Answer<T>() {
+ @SuppressWarnings("unchecked")
+ public T answer(InvocationOnMock invocation) throws Throwable {
+ return answer.answer((A)invocation.getArgument(0));
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a two parameter answer interface
+ * @param answer answer interface
+ * @param <A> input parameter 1 type
+ * @return a new answer object
+ */
+ public static <A> Answer<Void> toAnswer(final VoidAnswer1<A> answer) {
+ return new Answer<Void>() {
+ @SuppressWarnings("unchecked")
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ answer.answer((A)invocation.getArgument(0));
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a two parameter answer interface
+ * @param answer answer interface
+ * @param <T> return type
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @return a new answer object
+ */
+ public static <T, A, B> Answer<T> toAnswer(final Answer2<T, A, B> answer) {
+ return new Answer<T>() {
+ @SuppressWarnings("unchecked")
+ public T answer(InvocationOnMock invocation) throws Throwable {
+ return answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1));
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a two parameter answer interface
+ * @param answer answer interface
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @return a new answer object
+ */
+ public static <A, B> Answer<Void> toAnswer(final VoidAnswer2<A, B> answer) {
+ return new Answer<Void>() {
+ @SuppressWarnings("unchecked")
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1));
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a three parameter answer interface
+ * @param answer answer interface
+ * @param <T> return type
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @param <C> input parameter 3 type
+ * @return a new answer object
+ */
+ public static <T, A, B, C> Answer<T> toAnswer(final Answer3<T, A, B, C> answer) {
+ return new Answer<T>() {
+ @SuppressWarnings("unchecked")
+ public T answer(InvocationOnMock invocation) throws Throwable {
+ return answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1),
+ (C)invocation.getArgument(2));
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a three parameter answer interface
+ * @param answer answer interface
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @param <C> input parameter 3 type
+ * @return a new answer object
+ */
+ public static <A, B, C> Answer<Void> toAnswer(final VoidAnswer3<A, B, C> answer) {
+ return new Answer<Void>() {
+ @SuppressWarnings("unchecked")
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1),
+ (C)invocation.getArgument(2));
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a four parameter answer interface
+ * @param answer answer interface
+ * @param <T> return type
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @param <C> input parameter 3 type
+ * @param <D> input parameter 4 type
+ * @return a new answer object
+ */
+ public static <T, A, B, C, D> Answer<T> toAnswer(final Answer4<T, A, B, C, D> answer) {
+ return new Answer<T>() {
+ @SuppressWarnings("unchecked")
+ public T answer(InvocationOnMock invocation) throws Throwable {
+ return answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1),
+ (C)invocation.getArgument(2),
+ (D)invocation.getArgument(3));
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a four parameter answer interface
+ * @param answer answer interface
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @param <C> input parameter 3 type
+ * @param <D> input parameter 4 type
+ * @return a new answer object
+ */
+ public static <A, B, C, D> Answer<Void> toAnswer(final VoidAnswer4<A, B, C, D> answer) {
+ return new Answer<Void>() {
+ @SuppressWarnings("unchecked")
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1),
+ (C)invocation.getArgument(2),
+ (D)invocation.getArgument(3));
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a five parameter answer interface
+ * @param answer answer interface
+ * @param <T> return type
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @param <C> input parameter 3 type
+ * @param <D> input parameter 4 type
+ * @param <E> input parameter 5 type
+ * @return a new answer object
+ */
+ public static <T, A, B, C, D, E> Answer<T> toAnswer(final Answer5<T, A, B, C, D, E> answer) {
+ return new Answer<T>() {
+ @SuppressWarnings("unchecked")
+ public T answer(InvocationOnMock invocation) throws Throwable {
+ return answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1),
+ (C)invocation.getArgument(2),
+ (D)invocation.getArgument(3),
+ (E)invocation.getArgument(4));
+ }
+ };
+ }
+
+ /**
+ * Construct an answer from a five parameter answer interface
+ * @param answer answer interface
+ * @param <A> input parameter 1 type
+ * @param <B> input parameter 2 type
+ * @param <C> input parameter 3 type
+ * @param <D> input parameter 4 type
+ * @param <E> input parameter 5 type
+ * @return a new answer object
+ */
+ public static <A, B, C, D, E> Answer<Void> toAnswer(final VoidAnswer5<A, B, C, D, E> answer) {
+ return new Answer<Void>() {
+ @SuppressWarnings("unchecked")
+ public Void answer(InvocationOnMock invocation) throws Throwable {
+ answer.answer(
+ (A)invocation.getArgument(0),
+ (B)invocation.getArgument(1),
+ (C)invocation.getArgument(2),
+ (D)invocation.getArgument(3),
+ (E)invocation.getArgument(4));
+ return null;
+ }
+ };
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/AnswersValidator.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/AnswersValidator.java
new file mode 100644
index 0000000..144d778
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/AnswersValidator.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import static org.mockito.internal.exceptions.Reporter.cannotCallAbstractRealMethod;
+import static org.mockito.internal.exceptions.Reporter.cannotStubVoidMethodWithAReturnValue;
+import static org.mockito.internal.exceptions.Reporter.cannotStubWithNullThrowable;
+import static org.mockito.internal.exceptions.Reporter.checkedExceptionInvalid;
+import static org.mockito.internal.exceptions.Reporter.onlyVoidMethodsCanBeSetToDoNothing;
+import static org.mockito.internal.exceptions.Reporter.wrongTypeOfArgumentToReturn;
+import static org.mockito.internal.exceptions.Reporter.wrongTypeOfReturnValue;
+import static org.mockito.internal.exceptions.Reporter.wrongTypeReturnedByDefaultAnswer;
+
+import org.mockito.invocation.Invocation;
+import org.mockito.stubbing.Answer;
+
+public class AnswersValidator {
+
+
+ public void validate(Answer<?> answer, Invocation invocation) {
+ MethodInfo methodInfo = new MethodInfo(invocation);
+ if (answer instanceof ThrowsException) {
+ validateException((ThrowsException) answer, methodInfo);
+ }
+
+ if (answer instanceof Returns) {
+ validateReturnValue((Returns) answer, methodInfo);
+ }
+
+ if (answer instanceof DoesNothing) {
+ validateDoNothing((DoesNothing) answer, methodInfo);
+ }
+
+ if (answer instanceof CallsRealMethods) {
+ validateMockingConcreteClass((CallsRealMethods) answer, methodInfo);
+ }
+
+ if (answer instanceof ReturnsArgumentAt) {
+ ReturnsArgumentAt returnsArgumentAt = (ReturnsArgumentAt) answer;
+ validateReturnArgIdentity(returnsArgumentAt, invocation);
+ }
+ }
+
+ private void validateReturnArgIdentity(ReturnsArgumentAt returnsArgumentAt, Invocation invocation) {
+ returnsArgumentAt.validateIndexWithinInvocationRange(invocation);
+
+ MethodInfo methodInfo = new MethodInfo(invocation);
+ if (!methodInfo.isValidReturnType(returnsArgumentAt.returnedTypeOnSignature(invocation))) {
+ throw wrongTypeOfArgumentToReturn(invocation, methodInfo.printMethodReturnType(),
+ returnsArgumentAt.returnedTypeOnSignature(invocation),
+ returnsArgumentAt.wantedArgumentPosition());
+ }
+
+ }
+
+ private void validateMockingConcreteClass(CallsRealMethods answer, MethodInfo methodInfo) {
+ if (methodInfo.isAbstract()) {
+ throw cannotCallAbstractRealMethod();
+ }
+ }
+
+ private void validateDoNothing(DoesNothing answer, MethodInfo methodInfo) {
+ if (!methodInfo.isVoid()) {
+ throw onlyVoidMethodsCanBeSetToDoNothing();
+ }
+ }
+
+ private void validateReturnValue(Returns answer, MethodInfo methodInfo) {
+ if (methodInfo.isVoid()) {
+ throw cannotStubVoidMethodWithAReturnValue(methodInfo.getMethodName());
+ }
+
+ if (answer.returnsNull() && methodInfo.returnsPrimitive()) {
+ throw wrongTypeOfReturnValue(methodInfo.printMethodReturnType(), "null", methodInfo.getMethodName());
+ }
+
+ if (!answer.returnsNull() && !methodInfo.isValidReturnType(answer.getReturnType())) {
+ throw wrongTypeOfReturnValue(methodInfo.printMethodReturnType(), answer.printReturnType(), methodInfo.getMethodName());
+ }
+ }
+
+ private void validateException(ThrowsException answer, MethodInfo methodInfo) {
+ Throwable throwable = answer.getThrowable();
+ if (throwable == null) {
+ throw cannotStubWithNullThrowable();
+ }
+
+ if (throwable instanceof RuntimeException || throwable instanceof Error) {
+ return;
+ }
+
+ if (!methodInfo.isValidException(throwable)) {
+ throw checkedExceptionInvalid(throwable);
+ }
+ }
+
+ public void validateDefaultAnswerReturnedValue(Invocation invocation, Object returnedValue) {
+ MethodInfo methodInfo = new MethodInfo(invocation);
+ if (returnedValue != null && !methodInfo.isValidReturnType(returnedValue.getClass())) {
+ throw wrongTypeReturnedByDefaultAnswer(
+ invocation.getMock(),
+ methodInfo.printMethodReturnType(),
+ returnedValue.getClass().getSimpleName(),
+ methodInfo.getMethodName());
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/CallsRealMethods.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/CallsRealMethods.java
new file mode 100644
index 0000000..e4cf7f8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/CallsRealMethods.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import static org.mockito.Answers.RETURNS_DEFAULTS;
+import java.io.Serializable;
+import java.lang.reflect.Modifier;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Optional Answer that adds partial mocking support
+ * <p>
+ * {@link Answer} can be used to define the return values of unstubbed invocations.
+ * <p>
+ * This implementation can be helpful when working with legacy code.
+ * When this implementation is used, unstubbed methods will delegate to the real implementation.
+ * This is a way to create a partial mock object that calls real methods by default.
+ * <p>
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ * <p>
+ */
+public class CallsRealMethods implements Answer<Object>, Serializable {
+ private static final long serialVersionUID = 9057165148930624087L;
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ if (Modifier.isAbstract(invocation.getMethod().getModifiers())) {
+ return RETURNS_DEFAULTS.answer(invocation);
+ }
+ return invocation.callRealMethod();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/ClonesArguments.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/ClonesArguments.java
new file mode 100644
index 0000000..897e87c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/ClonesArguments.java
@@ -0,0 +1,28 @@
+/*
+ * 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.configuration.plugins.Plugins;
+import org.mockito.internal.creation.instance.Instantiator;
+import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
+import org.mockito.internal.util.reflection.LenientCopyTool;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+//TODO this needs documentation and further analysis - what if someone changes the answer?
+//we might think about implementing it straight on MockSettings
+public class ClonesArguments implements Answer<Object> {
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Object[] arguments = invocation.getArguments();
+ for (int i = 0; i < arguments.length; i++) {
+ Object from = arguments[i];
+ Instantiator instantiator = Plugins.getInstantiatorProvider().getInstantiator(null);
+ Object newInstance = instantiator.newInstance(from.getClass());
+ new LenientCopyTool().copyToRealObject(from, newInstance);
+ arguments[i] = newInstance;
+ }
+ return new ReturnsEmptyValues().answer(invocation);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/DoesNothing.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/DoesNothing.java
new file mode 100644
index 0000000..7aa0de7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/DoesNothing.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import java.io.Serializable;
+
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+public class DoesNothing implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = 4840880517740698416L;
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/MethodInfo.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/MethodInfo.java
new file mode 100644
index 0000000..ce9915e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/MethodInfo.java
@@ -0,0 +1,72 @@
+/*
+ * 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.invocation.AbstractAwareMethod;
+import org.mockito.internal.util.Primitives;
+import org.mockito.invocation.Invocation;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+/**
+ * by Szczepan Faber, created at: 3/31/12
+ */
+public class MethodInfo implements AbstractAwareMethod {
+
+ private final Method method;
+
+ public MethodInfo(Invocation theInvocation) {
+ this.method = theInvocation.getMethod();
+ }
+
+ public boolean isValidException(Throwable throwable) {
+ Class<?>[] exceptions = method.getExceptionTypes();
+ Class<?> throwableClass = throwable.getClass();
+ for (Class<?> exception : exceptions) {
+ if (exception.isAssignableFrom(throwableClass)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public boolean isValidReturnType(Class<?> clazz) {
+ if (method.getReturnType().isPrimitive() || clazz.isPrimitive()) {
+ return Primitives.primitiveTypeOf(clazz) == Primitives.primitiveTypeOf(method.getReturnType());
+ } else {
+ return method.getReturnType().isAssignableFrom(clazz);
+ }
+ }
+
+ public boolean isVoid() {
+ return this.method.getReturnType() == Void.TYPE;
+ }
+
+ public String printMethodReturnType() {
+ return method.getReturnType().getSimpleName();
+ }
+
+ public String getMethodName() {
+ return method.getName();
+ }
+
+ public boolean returnsPrimitive() {
+ return method.getReturnType().isPrimitive();
+ }
+
+ public Method getMethod() {
+ return method;
+ }
+
+ public boolean isDeclaredOnInterface() {
+ return method.getDeclaringClass().isInterface();
+ }
+
+ public boolean isAbstract() {
+ return (method.getModifiers() & Modifier.ABSTRACT) != 0;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/Returns.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/Returns.java
new file mode 100644
index 0000000..4cb3100
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/Returns.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import java.io.Serializable;
+
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+public class Returns implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = -6245608253574215396L;
+ private final Object value;
+
+ public Returns(Object value) {
+ this.value = value;
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return value;
+ }
+
+ public String printReturnType() {
+ return value.getClass().getSimpleName();
+ }
+
+ public Class<?> getReturnType() {
+ return value.getClass();
+ }
+
+ public boolean returnsNull() {
+ return value == null;
+ }
+
+ @Override
+ public String toString() {
+ return "Returns: " + value;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
new file mode 100644
index 0000000..d777d6f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/ReturnsArgumentAt.java
@@ -0,0 +1,113 @@
+/*
+ * 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.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import static org.mockito.internal.exceptions.Reporter.invalidArgumentPositionRangeAtInvocationTime;
+import static org.mockito.internal.exceptions.Reporter.invalidArgumentRangeAtIdentityAnswerCreationTime;
+
+import java.io.Serializable;
+
+/**
+ * Returns the passed parameter identity at specified index.
+ *
+ * <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
+ */
+public class ReturnsArgumentAt implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = -589315085166295101L;
+
+ public static final int LAST_ARGUMENT = -1;
+
+ private final int wantedArgumentPosition;
+
+ /**
+ * 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.
+ */
+ public ReturnsArgumentAt(int wantedArgumentPosition) {
+ this.wantedArgumentPosition = checkWithinAllowedRange(wantedArgumentPosition);
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ validateIndexWithinInvocationRange(invocation);
+ return invocation.getArgument(actualArgumentPosition(invocation));
+ }
+
+
+ private int actualArgumentPosition(InvocationOnMock invocation) {
+ return returningLastArg() ?
+ lastArgumentIndexOf(invocation) :
+ argumentIndexOf(invocation);
+ }
+
+ private boolean returningLastArg() {
+ return wantedArgumentPosition == LAST_ARGUMENT;
+ }
+
+ private int argumentIndexOf(InvocationOnMock invocation) {
+ return wantedArgumentPosition;
+ }
+
+ private int lastArgumentIndexOf(InvocationOnMock invocation) {
+ return invocation.getArguments().length - 1;
+ }
+
+ private int checkWithinAllowedRange(int argumentPosition) {
+ if (argumentPosition != LAST_ARGUMENT && argumentPosition < 0) {
+ throw invalidArgumentRangeAtIdentityAnswerCreationTime();
+ }
+ return argumentPosition;
+ }
+
+ public int wantedArgumentPosition() {
+ return wantedArgumentPosition;
+ }
+
+ public void validateIndexWithinInvocationRange(InvocationOnMock invocation) {
+ if (!argumentPositionInRange(invocation)) {
+ throw invalidArgumentPositionRangeAtInvocationTime(invocation,
+ returningLastArg(),
+ wantedArgumentPosition);
+ }
+ }
+
+ private boolean argumentPositionInRange(InvocationOnMock invocation) {
+ int actualArgumentPosition = actualArgumentPosition(invocation);
+ if (actualArgumentPosition < 0) {
+ return false;
+ }
+ if (!invocation.getMethod().isVarArgs()) {
+ return invocation.getArguments().length > actualArgumentPosition;
+ }
+ // for all varargs accepts positive ranges
+ return true;
+ }
+
+ public Class<?> returnedTypeOnSignature(InvocationOnMock invocation) {
+ int actualArgumentPosition = actualArgumentPosition(invocation);
+
+ if(!invocation.getMethod().isVarArgs()) {
+ return invocation.getMethod().getParameterTypes()[actualArgumentPosition];
+ }
+
+ Class<?>[] parameterTypes = invocation.getMethod().getParameterTypes();
+ int varargPosition = parameterTypes.length - 1;
+
+ if(actualArgumentPosition < varargPosition) {
+ return parameterTypes[actualArgumentPosition];
+ } else {
+ return parameterTypes[varargPosition].getComponentType();
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java
new file mode 100644
index 0000000..636f152
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.answers;
+
+import java.util.Collection;
+import java.util.LinkedList;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Returns elements of the collection. Keeps returning the last element forever.
+ * Might be useful on occasion when you have a collection of elements to return.
+ * <p>
+ * <pre class="code"><code class="java">
+ * //this:
+ * when(mock.foo()).thenReturn(1, 2, 3);
+ * //is equivalent to:
+ * when(mock.foo()).thenAnswer(new ReturnsElementsOf(Arrays.asList(1, 2, 3)));
+ * </code></pre>
+ * </p>
+ *
+ * <p>
+ * Also you might better want to use the static factory there
+ * {@link org.mockito.AdditionalAnswers#returnsElementsOf(java.util.Collection)}
+ * </p>
+ *
+ * @see org.mockito.AdditionalAnswers
+ */
+public class ReturnsElementsOf implements Answer<Object> {
+
+ private final LinkedList<Object> elements;
+
+ public ReturnsElementsOf(Collection<?> elements) {
+ if (elements == null) {
+ throw new MockitoException("ReturnsElementsOf does not accept null as constructor argument.\n" +
+ "Please pass a collection instance");
+ }
+ this.elements = new LinkedList<Object>(elements);
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ if (elements.size() == 1)
+ return elements.get(0);
+ else
+ return elements.poll();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/ThrowsException.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/ThrowsException.java
new file mode 100644
index 0000000..f8de566
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/ThrowsException.java
@@ -0,0 +1,36 @@
+/*
+ * 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.internal.util.MockUtil;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+
+public class ThrowsException implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = 1128820328555183980L;
+ private final Throwable throwable;
+ private final ConditionalStackTraceFilter filter = new ConditionalStackTraceFilter();
+
+ public ThrowsException(Throwable throwable) {
+ this.throwable = throwable;
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ if (MockUtil.isMock(throwable)) {
+ throw throwable;
+ }
+ Throwable t = throwable.fillInStackTrace();
+ filter.filter(t);
+ throw t;
+ }
+
+ public Throwable getThrowable() {
+ return throwable;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java b/mockito-updated/src/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java
new file mode 100644
index 0000000..ef7baad
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/ThrowsExceptionClass.java
@@ -0,0 +1,44 @@
+/*
+ * 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/mockito-updated/src/org/mockito/internal/stubbing/answers/package.html b/mockito-updated/src/org/mockito/internal/stubbing/answers/package.html
new file mode 100644
index 0000000..3fdeb8d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/answers/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Answers for stubbed calls
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
new file mode 100644
index 0000000..c70675f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocations.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.defaultanswers;
+
+import static org.mockito.internal.exceptions.Reporter.delegatedMethodDoesNotExistOnDelegate;
+import static org.mockito.internal.exceptions.Reporter.delegatedMethodHasWrongReturnType;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Internal answer to forward invocations on a real instance.
+ *
+ * @since 1.9.5
+ */
+public class ForwardsInvocations implements Answer<Object>, Serializable {
+ private static final long serialVersionUID = -8343690268123254910L;
+
+ private Object delegatedObject = null ;
+
+ public ForwardsInvocations(Object delegatedObject) {
+ this.delegatedObject = delegatedObject ;
+ }
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Method mockMethod = invocation.getMethod();
+
+ try {
+ Method delegateMethod = getDelegateMethod(mockMethod);
+
+ if (!compatibleReturnTypes(mockMethod.getReturnType(), delegateMethod.getReturnType())) {
+ throw delegatedMethodHasWrongReturnType(mockMethod, delegateMethod, invocation.getMock(), delegatedObject);
+ }
+
+ Object[] rawArguments = ((Invocation) invocation).getRawArguments();
+ return delegateMethod.invoke(delegatedObject, rawArguments);
+ } catch (NoSuchMethodException e) {
+ throw delegatedMethodDoesNotExistOnDelegate(mockMethod, invocation.getMock(), delegatedObject);
+ } catch (InvocationTargetException e) {
+ // propagate the original exception from the delegate
+ throw e.getCause();
+ }
+ }
+
+ private Method getDelegateMethod(Method mockMethod) throws NoSuchMethodException {
+ if (mockMethod.getDeclaringClass().isAssignableFrom(delegatedObject.getClass())) {
+ // Compatible class. Return original method.
+ return mockMethod;
+ } else {
+ // Return method of delegate object with the same signature as mockMethod.
+ return delegatedObject.getClass().getMethod(mockMethod.getName(), mockMethod.getParameterTypes());
+ }
+ }
+
+ private static boolean compatibleReturnTypes(Class<?> superType, Class<?> subType) {
+ return superType.equals(subType) || superType.isAssignableFrom(subType);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/GloballyConfiguredAnswer.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/GloballyConfiguredAnswer.java
new file mode 100644
index 0000000..d168160
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/GloballyConfiguredAnswer.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.defaultanswers;
+
+import java.io.Serializable;
+
+import org.mockito.configuration.IMockitoConfiguration;
+import org.mockito.internal.configuration.GlobalConfiguration;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Globally configured Answer.
+ * <p>
+ * See javadoc for {@link IMockitoConfiguration}
+ */
+public class GloballyConfiguredAnswer implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = 3585893470101750917L;
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return new GlobalConfiguration().getDefaultAnswer().answer(invocation);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
new file mode 100644
index 0000000..9367a89
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsDeepStubs.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.defaultanswers;
+
+import org.mockito.MockSettings;
+import org.mockito.Mockito;
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.MockitoCore;
+import org.mockito.internal.creation.settings.CreationSettings;
+import org.mockito.internal.stubbing.InvocationContainerImpl;
+import org.mockito.internal.stubbing.StubbedInvocationMatcher;
+import org.mockito.internal.util.MockUtil;
+import org.mockito.internal.util.reflection.GenericMetadataSupport;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.stubbing.Answer;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+import static org.mockito.Mockito.withSettings;
+
+/**
+ * Returning deep stub implementation.
+ *
+ * Will return previously created mock if the invocation matches.
+ *
+ * <p>Supports nested generic information, with this answer you can write code like this :
+ *
+ * <pre class="code"><code class="java">
+ * interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
+ *
+ * GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
+ * Number number = mock.entrySet().iterator().next().getValue().iterator().next();
+ * </code></pre>
+ * </p>
+ *
+ * @see org.mockito.Mockito#RETURNS_DEEP_STUBS
+ * @see org.mockito.Answers#RETURNS_DEEP_STUBS
+ */
+public class ReturnsDeepStubs implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = -7105341425736035847L;
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ GenericMetadataSupport returnTypeGenericMetadata =
+ actualParameterizedType(invocation.getMock()).resolveGenericReturnType(invocation.getMethod());
+
+ Class<?> rawType = returnTypeGenericMetadata.rawType();
+ if (!mockitoCore().isTypeMockable(rawType)) {
+ return delegate().returnValueFor(rawType);
+ }
+
+ return deepStub(invocation, returnTypeGenericMetadata);
+ }
+
+ private Object deepStub(InvocationOnMock invocation, GenericMetadataSupport returnTypeGenericMetadata) throws Throwable {
+ InternalMockHandler<Object> handler = MockUtil.getMockHandler(invocation.getMock());
+ InvocationContainerImpl container = (InvocationContainerImpl) handler.getInvocationContainer();
+
+ // matches invocation for verification
+ for (StubbedInvocationMatcher stubbedInvocationMatcher : container.getStubbedInvocations()) {
+ if (container.getInvocationForStubbing().matches(stubbedInvocationMatcher.getInvocation())) {
+ return stubbedInvocationMatcher.answer(invocation);
+ }
+ }
+
+ // record deep stub answer
+ return recordDeepStubAnswer(
+ newDeepStubMock(returnTypeGenericMetadata, invocation.getMock()),
+ container
+ );
+ }
+
+ /**
+ * Creates a mock using the Generics Metadata.
+ *
+ * <li>Finally as we want to mock the actual type, but we want to pass along the contextual generics meta-data
+ * that was resolved for the current return type, for this to happen we associate to the mock an new instance of
+ * {@link ReturnsDeepStubs} answer in which we will store the returned type generic metadata.
+ *
+ * @param returnTypeGenericMetadata The metadata to use to create the new mock.
+ * @param parentMock The parent of the current deep stub mock.
+ * @return The mock
+ */
+ private Object newDeepStubMock(GenericMetadataSupport returnTypeGenericMetadata, Object parentMock) {
+ MockCreationSettings parentMockSettings = MockUtil.getMockSettings(parentMock);
+ return mockitoCore().mock(
+ returnTypeGenericMetadata.rawType(),
+ withSettingsUsing(returnTypeGenericMetadata, parentMockSettings)
+ );
+ }
+
+ private MockSettings withSettingsUsing(GenericMetadataSupport returnTypeGenericMetadata, MockCreationSettings parentMockSettings) {
+ MockSettings mockSettings = returnTypeGenericMetadata.hasRawExtraInterfaces() ?
+ withSettings().extraInterfaces(returnTypeGenericMetadata.rawExtraInterfaces())
+ : withSettings();
+
+ return propagateSerializationSettings(mockSettings, parentMockSettings)
+ .defaultAnswer(returnsDeepStubsAnswerUsing(returnTypeGenericMetadata));
+ }
+
+ private MockSettings propagateSerializationSettings(MockSettings mockSettings, MockCreationSettings parentMockSettings) {
+ return mockSettings.serializable(parentMockSettings.getSerializableMode());
+ }
+
+ private ReturnsDeepStubs returnsDeepStubsAnswerUsing(final GenericMetadataSupport returnTypeGenericMetadata) {
+ return new ReturnsDeepStubsSerializationFallback(returnTypeGenericMetadata);
+ }
+
+ private Object recordDeepStubAnswer(final Object mock, InvocationContainerImpl container) {
+ container.addAnswer(new DeeplyStubbedAnswer(mock), false);
+ return mock;
+ }
+
+ protected GenericMetadataSupport actualParameterizedType(Object mock) {
+ CreationSettings mockSettings = (CreationSettings) MockUtil.getMockHandler(mock).getMockSettings();
+ return GenericMetadataSupport.inferFrom(mockSettings.getTypeToMock());
+ }
+
+
+ private static class ReturnsDeepStubsSerializationFallback extends ReturnsDeepStubs implements Serializable {
+ @SuppressWarnings("serial") // not gonna be serialized
+ private final GenericMetadataSupport returnTypeGenericMetadata;
+
+ public ReturnsDeepStubsSerializationFallback(GenericMetadataSupport returnTypeGenericMetadata) {
+ this.returnTypeGenericMetadata = returnTypeGenericMetadata;
+ }
+
+ @Override
+ protected GenericMetadataSupport actualParameterizedType(Object mock) {
+ return returnTypeGenericMetadata;
+ }
+ private Object writeReplace() throws IOException {
+ return Mockito.RETURNS_DEEP_STUBS;
+ }
+ }
+
+
+ private static class DeeplyStubbedAnswer implements Answer<Object>, Serializable {
+ @SuppressWarnings("serial") // serialization will fail with a nice message if mock not serializable
+ private final Object mock;
+
+ DeeplyStubbedAnswer(Object mock) {
+ this.mock = mock;
+ }
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ return mock;
+ }
+ }
+
+
+ private static MockitoCore mockitoCore() {
+ return LazyHolder.MOCKITO_CORE;
+ }
+
+ private static ReturnsEmptyValues delegate() {
+ return LazyHolder.DELEGATE;
+ }
+
+ private static class LazyHolder {
+ private static final MockitoCore MOCKITO_CORE = new MockitoCore();
+ private static final ReturnsEmptyValues DELEGATE = new ReturnsEmptyValues();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
new file mode 100644
index 0000000..7a74810
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
@@ -0,0 +1,115 @@
+package org.mockito.internal.stubbing.defaultanswers;
+
+import org.mockito.internal.util.JavaEightUtil;
+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;
+import org.mockito.stubbing.Answer;
+
+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 (see issue 191).
+ * </li>
+ * <li>
+ * Returns null for everything else
+ * </li>
+ * </ul>
+ */
+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();
+ MockName name = MockUtil.getMockName(mock);
+ if (name.isDefault()) {
+ return "Mock for " + MockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + ", hashCode: " + mock.hashCode();
+ } else {
+ return name.toString();
+ }
+ } else if (isCompareToMethod(invocation.getMethod())) {
+ //see issue 184.
+ //mocks by default should return 0 if references are the same, otherwise some other value because they are not the same. Hence we return 1 (anything but 0 is good).
+ //Only for compareTo() method by the Comparable interface
+ return invocation.getMock() == invocation.getArgument(0) ? 0 : 1;
+ }
+
+ Class<?> returnType = invocation.getMethod().getReturnType();
+ return returnValueFor(returnType);
+ }
+
+ Object returnValueFor(Class<?> type) {
+ if (Primitives.isPrimitiveOrWrapper(type)) {
+ return Primitives.defaultValue(type);
+ //new instances are used instead of Collections.emptyList(), etc.
+ //to avoid UnsupportedOperationException if code under test modifies returned collection
+ } else if (type == Iterable.class) {
+ return new ArrayList<Object>(0);
+ } else if (type == Collection.class) {
+ return new LinkedList<Object>();
+ } else if (type == Set.class) {
+ return new HashSet<Object>();
+ } else if (type == HashSet.class) {
+ return new HashSet<Object>();
+ } else if (type == SortedSet.class) {
+ return new TreeSet<Object>();
+ } else if (type == TreeSet.class) {
+ return new TreeSet<Object>();
+ } else if (type == LinkedHashSet.class) {
+ return new LinkedHashSet<Object>();
+ } else if (type == List.class) {
+ return new LinkedList<Object>();
+ } else if (type == LinkedList.class) {
+ return new LinkedList<Object>();
+ } else if (type == ArrayList.class) {
+ return new ArrayList<Object>();
+ } else if (type == Map.class) {
+ return new HashMap<Object, Object>();
+ } else if (type == HashMap.class) {
+ return new HashMap<Object, Object>();
+ } else if (type == SortedMap.class) {
+ return new TreeMap<Object, Object>();
+ } else if (type == TreeMap.class) {
+ 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.stream.Stream".equals(type.getName())) {
+ return JavaEightUtil.emptyStream();
+ }
+
+ //Let's not care about the rest of collections.
+ return null;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java
new file mode 100755
index 0000000..d557b20
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsMocks.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.defaultanswers;
+
+import org.mockito.internal.MockitoCore;
+import org.mockito.internal.creation.MockSettingsImpl;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+
+public class ReturnsMocks implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = -6755257986994634579L;
+ private final MockitoCore mockitoCore = new MockitoCore();
+ private final Answer<Object> delegate = new ReturnsMoreEmptyValues();
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Object ret = delegate.answer(invocation);
+ if (ret != null) {
+ return ret;
+ }
+
+ return returnValueFor(invocation.getMethod().getReturnType());
+ }
+
+ Object returnValueFor(Class<?> clazz) {
+ if (!mockitoCore.isTypeMockable(clazz)) {
+ return null;
+ }
+
+ return mockitoCore.mock(clazz, new MockSettingsImpl().defaultAnswer(this));
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
new file mode 100644
index 0000000..2c20525
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsMoreEmptyValues.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.stubbing.defaultanswers;
+
+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>
+ * Currently <b>used only</b> by {@link Mockito#RETURNS_SMART_NULLS}
+ * <p>
+ * Current version of Mockito mocks by deafult 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>
+ * </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) {
+ return ret;
+ }
+
+ Class<?> returnType = invocation.getMethod().getReturnType();
+ return returnValueFor(returnType);
+ }
+
+ Object returnValueFor(Class<?> type) {
+ if (type == String.class) {
+ return "";
+ } else if (type.isArray()) {
+ Class<?> componenetType = type.getComponentType();
+ return Array.newInstance(componenetType, 0);
+ }
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
new file mode 100644
index 0000000..7487e89
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.stubbing.defaultanswers;
+
+import static org.mockito.internal.exceptions.Reporter.smartNullPointerException;
+import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
+
+import java.io.Serializable;
+import java.lang.reflect.Modifier;
+
+import org.mockito.Mockito;
+import org.mockito.internal.debugging.LocationImpl;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.invocation.Location;
+import org.mockito.stubbing.Answer;
+
+/**
+ * Optional Answer that can be used with
+ * {@link Mockito#mock(Class, Answer)}
+ * <p>
+ * This implementation can be helpful when working with legacy code. Unstubbed
+ * methods often return null. If your code uses the object returned by an
+ * unstubbed call you get a NullPointerException. This implementation of
+ * Answer returns SmartNulls instead of nulls.
+ * SmartNull 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>
+ * ReturnsSmartNulls first tries to return ordinary return values (see
+ * {@link ReturnsMoreEmptyValues}) then it tries to return SmartNull. If the
+ * return type is not mockable (e.g. final) then ordinary null is returned.
+ * <p>
+ * ReturnsSmartNulls will be probably the default return values strategy in
+ * Mockito 2.1.0
+ */
+public class ReturnsSmartNulls implements Answer<Object>, Serializable {
+
+ private static final long serialVersionUID = 7618312406617949441L;
+
+ private final Answer<Object> delegate = new ReturnsMoreEmptyValues();
+
+ public Object answer(final InvocationOnMock invocation) throws Throwable {
+ Object defaultReturnValue = delegate.answer(invocation);
+ if (defaultReturnValue != null) {
+ return defaultReturnValue;
+ }
+ Class<?> type = invocation.getMethod().getReturnType();
+ if (!type.isPrimitive() && !Modifier.isFinal(type.getModifiers())) {
+ final Location location = new LocationImpl();
+ return Mockito.mock(type, new ThrowsSmartNullPointer(invocation, location));
+ }
+ return null;
+ }
+
+ private static class ThrowsSmartNullPointer implements Answer {
+ private final InvocationOnMock unstubbedInvocation;
+ private final Location location;
+
+ public ThrowsSmartNullPointer(InvocationOnMock unstubbedInvocation, Location location) {
+ this.unstubbedInvocation = unstubbedInvocation;
+ this.location = location;
+ }
+
+ public Object answer(InvocationOnMock currentInvocation) throws Throwable {
+ if (isToStringMethod(currentInvocation.getMethod())) {
+ return "SmartNull returned by this unstubbed method call on a mock:\n" +
+ unstubbedInvocation.toString();
+ }
+
+ throw smartNullPointerException(unstubbedInvocation.toString(), location);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java
new file mode 100644
index 0000000..db76dcf
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/TriesToReturnSelf.java
@@ -0,0 +1,25 @@
+package org.mockito.internal.stubbing.defaultanswers;
+
+import org.mockito.internal.util.MockUtil;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+
+public class TriesToReturnSelf implements Answer<Object>, Serializable{
+
+ private final ReturnsEmptyValues defaultReturn = new ReturnsEmptyValues();
+
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ Class<?> methodReturnType = invocation.getMethod().getReturnType();
+ Object mock = invocation.getMock();
+ Class<?> mockType = MockUtil.getMockHandler(mock).getMockSettings().getTypeToMock();
+
+ if (methodReturnType.isAssignableFrom(mockType)) {
+ return invocation.getMock();
+ }
+
+ return defaultReturn.returnValueFor(methodReturnType);
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/package.html b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/package.html
new file mode 100644
index 0000000..f2dee90
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/defaultanswers/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Implementations of Answer
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/stubbing/package.html b/mockito-updated/src/org/mockito/internal/stubbing/package.html
new file mode 100644
index 0000000..4f6d4e8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/stubbing/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Stubbing logic.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/Checks.java b/mockito-updated/src/org/mockito/internal/util/Checks.java
new file mode 100644
index 0000000..9731dbe
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/Checks.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.util;
+
+/**
+ * Pre-made preconditions
+ */
+public class Checks {
+
+ public static <T> T checkNotNull(T value, String checkedValue) {
+ if(value == null) {
+ throw new IllegalArgumentException(checkedValue + " should not be null");
+ }
+ return value;
+ }
+
+ public static <T extends Iterable<?>> T checkItemsNotNull(T iterable, String checkedIterable) {
+ checkNotNull(iterable, checkedIterable);
+ for (Object item : iterable) {
+ checkNotNull(item, "item in " + checkedIterable);
+ }
+ return iterable;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/ConsoleMockitoLogger.java b/mockito-updated/src/org/mockito/internal/util/ConsoleMockitoLogger.java
new file mode 100644
index 0000000..d8df8eb
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/ConsoleMockitoLogger.java
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+public class ConsoleMockitoLogger implements MockitoLogger {
+
+ /* (non-Javadoc)
+ * @see org.mockito.internal.util.Logger#print(java.lang.Object)
+ */
+ public void log(Object what) {
+ System.out.println(what);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/Decamelizer.java b/mockito-updated/src/org/mockito/internal/util/Decamelizer.java
new file mode 100644
index 0000000..32bf8e9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/Decamelizer.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+//TODO SF move to matchers.text
+public class Decamelizer {
+
+private static final Pattern CAPS = Pattern.compile("([A-Z\\d][^A-Z\\d]*)");
+
+ public static String decamelizeMatcher(String className) {
+ if (className.length() == 0) {
+ return "<custom argument matcher>";
+ }
+
+ String decamelized = decamelizeClassName(className);
+
+ if (decamelized.length() == 0) {
+ return "<" + className + ">";
+ }
+
+ return "<" + decamelized + ">";
+ }
+
+ private static String decamelizeClassName(String className) {
+ Matcher match = CAPS.matcher(className);
+ StringBuilder deCameled = new StringBuilder();
+ while(match.find()) {
+ if (deCameled.length() == 0) {
+ deCameled.append(match.group());
+ } else {
+ deCameled.append(" ");
+ deCameled.append(match.group().toLowerCase());
+ }
+ }
+ return deCameled.toString();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/DefaultMockingDetails.java b/mockito-updated/src/org/mockito/internal/util/DefaultMockingDetails.java
new file mode 100644
index 0000000..7114a46
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/DefaultMockingDetails.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+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;
+import org.mockito.mock.MockCreationSettings;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.TreeSet;
+
+import static org.mockito.internal.util.MockUtil.getMockHandler;
+
+/**
+ * Class to inspect any object, and identify whether a particular object is either a mock or a spy. This is
+ * a wrapper for {@link org.mockito.internal.util.MockUtil}.
+ */
+public class DefaultMockingDetails implements MockingDetails {
+
+ private final Object toInspect;
+
+ public DefaultMockingDetails(Object toInspect){
+ this.toInspect = toInspect;
+ }
+
+ @Override
+ public boolean isMock(){
+ return MockUtil.isMock(toInspect);
+ }
+
+ @Override
+ public boolean isSpy(){
+ return MockUtil.isSpy(toInspect);
+ }
+
+ @Override
+ public Collection<Invocation> getInvocations() {
+ return mockHandler().getInvocationContainer().getInvocations();
+ }
+
+ @Override
+ public MockCreationSettings<?> getMockCreationSettings() {
+ return mockHandler().getMockSettings();
+ }
+
+ @Override
+ public Collection<Stubbing> getStubbings() {
+ List<? extends Stubbing> stubbings = mockHandler().getInvocationContainer().getStubbedInvocations();
+ TreeSet<Stubbing> out = new TreeSet<Stubbing>(new StubbingComparator());
+ out.addAll(stubbings);
+ return out;
+ }
+
+ @Override
+ public String printInvocations() {
+ assertGoodMock();
+ return new InvocationsPrinter().printInvocations(toInspect);
+ }
+
+ private InternalMockHandler<Object> mockHandler() {
+ assertGoodMock();
+ return getMockHandler(toInspect);
+ }
+
+ private void assertGoodMock() {
+ if (toInspect == null) {
+ throw new NotAMockException("Argument passed to Mockito.mockingDetails() should be a mock, but is null!");
+ } else if (!isMock()) {
+ throw new NotAMockException("Argument passed to Mockito.mockingDetails() should be a mock, but is an instance of " + toInspect.getClass() + "!");
+ }
+ }
+}
+
diff --git a/mockito-updated/src/org/mockito/internal/util/JavaEightUtil.java b/mockito-updated/src/org/mockito/internal/util/JavaEightUtil.java
new file mode 100644
index 0000000..7e26445
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/JavaEightUtil.java
@@ -0,0 +1,63 @@
+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, Optional#empty() is already a safe singleton.
+ private static Object emptyOptional;
+
+ private JavaEightUtil() {
+ // utility class
+ }
+
+ /**
+ * Creates an empty Optional using reflection to stay backwards-compatible with older
+ * JDKs (see issue 191).
+ *
+ * @return an empty Optional.
+ */
+ public static Object emptyOptional() {
+ // no need for double-checked locking
+ if (emptyOptional != null) {
+ return emptyOptional;
+ }
+
+ try {
+ final Class<?> optionalClass = Class.forName("java.util.Optional");
+ final Method emptyMethod = optionalClass.getMethod("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 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.
+ try {
+ final Class<?> optionalClass = Class.forName("java.util.stream.Stream");
+ final Method emptyMethod = optionalClass.getMethod("empty");
+
+ return emptyMethod.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);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/MockCreationValidator.java b/mockito-updated/src/org/mockito/internal/util/MockCreationValidator.java
new file mode 100644
index 0000000..5dba346
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/MockCreationValidator.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+import static org.mockito.internal.exceptions.Reporter.cannotMockClass;
+import static org.mockito.internal.exceptions.Reporter.extraInterfacesCannotContainMockedType;
+import static org.mockito.internal.exceptions.Reporter.mockedTypeIsInconsistentWithDelegatedInstanceType;
+import static org.mockito.internal.exceptions.Reporter.mockedTypeIsInconsistentWithSpiedInstanceType;
+import static org.mockito.internal.exceptions.Reporter.usingConstructorWithFancySerializable;
+
+import java.util.Collection;
+
+import org.mockito.mock.SerializableMode;
+import org.mockito.plugins.MockMaker.TypeMockability;
+
+@SuppressWarnings("unchecked")
+public class MockCreationValidator {
+
+ public void validateType(Class<?> classToMock) {
+ TypeMockability typeMockability = MockUtil.typeMockabilityOf(classToMock);
+ if (!typeMockability.mockable()) {
+ throw cannotMockClass(classToMock, typeMockability.nonMockableReason());
+ }
+ }
+
+ public void validateExtraInterfaces(Class<?> classToMock, Collection<Class<?>> extraInterfaces) {
+ if (extraInterfaces == null) {
+ return;
+ }
+
+ for (Class<?> i : extraInterfaces) {
+ if (classToMock == i) {
+ throw extraInterfacesCannotContainMockedType(classToMock);
+ }
+ }
+ }
+
+ public void validateMockedType(Class<?> classToMock, Object spiedInstance) {
+ if (classToMock == null || spiedInstance == null) {
+ return;
+ }
+ if (!classToMock.equals(spiedInstance.getClass())) {
+ throw mockedTypeIsInconsistentWithSpiedInstanceType(classToMock, spiedInstance);
+ }
+ }
+
+ public void validateDelegatedInstance(Class<?> classToMock, Object delegatedInstance) {
+ if (classToMock == null || delegatedInstance == null) {
+ return;
+ }
+ if (delegatedInstance.getClass().isAssignableFrom(classToMock)) {
+ throw mockedTypeIsInconsistentWithDelegatedInstanceType(classToMock, delegatedInstance);
+ }
+ }
+
+ public void validateConstructorUse(boolean usingConstructor, SerializableMode mode) {
+ if (usingConstructor && mode == SerializableMode.ACROSS_CLASSLOADERS) {
+ throw usingConstructorWithFancySerializable(mode);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/MockNameImpl.java b/mockito-updated/src/org/mockito/internal/util/MockNameImpl.java
new file mode 100644
index 0000000..28bc4a6
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/MockNameImpl.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+import org.mockito.mock.MockName;
+
+import java.io.Serializable;
+
+public class MockNameImpl implements MockName, Serializable {
+
+ private static final long serialVersionUID = 8014974700844306925L;
+ private final String mockName;
+ private boolean defaultName;
+
+ @SuppressWarnings("unchecked")
+ public MockNameImpl(String mockName, Class<?> classToMock) {
+ if (mockName == null) {
+ this.mockName = toInstanceName(classToMock);
+ this.defaultName = true;
+ } else {
+ this.mockName = mockName;
+ }
+ }
+
+ public MockNameImpl(String mockName) {
+ this.mockName = mockName;
+ }
+
+ private static String toInstanceName(Class<?> clazz) {
+ String className = clazz.getSimpleName();
+ if (className.length() == 0) {
+ //it's an anonymous class, let's get name from the parent
+ className = clazz.getSuperclass().getSimpleName();
+ }
+ //lower case first letter
+ return className.substring(0, 1).toLowerCase() + className.substring(1);
+ }
+
+ public boolean isDefault() {
+ return defaultName;
+ }
+
+ @Override
+ public String toString() {
+ return mockName;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/MockUtil.java b/mockito-updated/src/org/mockito/internal/util/MockUtil.java
new file mode 100644
index 0000000..6c2b195
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/MockUtil.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+import static org.mockito.internal.handler.MockHandlerFactory.createMockHandler;
+
+import org.mockito.Mockito;
+import org.mockito.exceptions.misusing.NotAMockException;
+import org.mockito.internal.InternalMockHandler;
+import org.mockito.internal.configuration.plugins.Plugins;
+import org.mockito.internal.creation.settings.CreationSettings;
+import org.mockito.internal.util.reflection.LenientCopyTool;
+import org.mockito.invocation.MockHandler;
+import org.mockito.mock.MockCreationSettings;
+import org.mockito.mock.MockName;
+import org.mockito.plugins.MockMaker;
+import org.mockito.plugins.MockMaker.TypeMockability;
+
+@SuppressWarnings("unchecked")
+public class MockUtil {
+
+ private static final MockMaker mockMaker = Plugins.getMockMaker();
+
+ private MockUtil() {}
+
+ public static TypeMockability typeMockabilityOf(Class<?> type) {
+ return mockMaker.isTypeMockable(type);
+ }
+
+ public static <T> T createMock(MockCreationSettings<T> settings) {
+ MockHandler mockHandler = createMockHandler(settings);
+
+ T mock = mockMaker.createMock(settings, mockHandler);
+
+ Object spiedInstance = settings.getSpiedInstance();
+ if (spiedInstance != null) {
+ new LenientCopyTool().copyToMock(spiedInstance, mock);
+ }
+
+ return mock;
+ }
+
+ public static <T> void resetMock(T mock) {
+ InternalMockHandler oldHandler = (InternalMockHandler) getMockHandler(mock);
+ MockCreationSettings settings = oldHandler.getMockSettings();
+ MockHandler newHandler = createMockHandler(settings);
+
+ mockMaker.resetMock(mock, newHandler, settings);
+ }
+
+ public static <T> InternalMockHandler<T> getMockHandler(T mock) {
+ if (mock == null) {
+ throw new NotAMockException("Argument should be a mock, but is null!");
+ }
+
+ if (isMockitoMock(mock)) {
+ MockHandler handler = mockMaker.getHandler(mock);
+ return (InternalMockHandler) handler;
+ } else {
+ throw new NotAMockException("Argument should be a mock, but is: " + mock.getClass());
+ }
+ }
+
+ public static boolean isMock(Object mock) {
+ // double check to avoid classes that have the same interfaces, could be great to have a custom mockito field in the proxy instead of relying on instance fields
+ return isMockitoMock(mock);
+ }
+
+ public static boolean isSpy(Object mock) {
+ return isMockitoMock(mock) && getMockSettings(mock).getDefaultAnswer() == Mockito.CALLS_REAL_METHODS;
+ }
+
+ private static <T> boolean isMockitoMock(T mock) {
+ return mock != null && mockMaker.getHandler(mock) != null;
+ }
+
+ public static MockName getMockName(Object mock) {
+ return getMockHandler(mock).getMockSettings().getMockName();
+ }
+
+ public static void maybeRedefineMockName(Object mock, String newName) {
+ MockName mockName = getMockName(mock);
+ //TODO SF hacky...
+ MockCreationSettings mockSettings = getMockHandler(mock).getMockSettings();
+ if (mockName.isDefault() && mockSettings instanceof CreationSettings) {
+ ((CreationSettings) mockSettings).setMockName(new MockNameImpl(newName));
+ }
+ }
+
+ public static MockCreationSettings getMockSettings(Object mock) {
+ return getMockHandler(mock).getMockSettings();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/MockitoLogger.java b/mockito-updated/src/org/mockito/internal/util/MockitoLogger.java
new file mode 100644
index 0000000..5f850e3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/MockitoLogger.java
@@ -0,0 +1,11 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+public interface MockitoLogger {
+
+ void log(Object what);
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/ObjectMethodsGuru.java b/mockito-updated/src/org/mockito/internal/util/ObjectMethodsGuru.java
new file mode 100644
index 0000000..3897f97
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/ObjectMethodsGuru.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+import java.lang.reflect.Method;
+import org.mockito.internal.creation.DelegatingMethod;
+import org.mockito.internal.invocation.MockitoMethod;
+
+public class ObjectMethodsGuru{
+
+ private ObjectMethodsGuru() {
+ }
+
+ public static boolean isToStringMethod(Method method) {
+ MockitoMethod m = new DelegatingMethod(method);
+ return m.getReturnType() == String.class &&
+ m.getParameterTypes().length == 0 &&
+ m.getName().equals("toString");
+ }
+
+ public static boolean isCompareToMethod(Method method) {
+ return Comparable.class.isAssignableFrom(method.getDeclaringClass())
+ && method.getName().equals("compareTo")
+ && method.getParameterTypes().length == 1
+ && method.getParameterTypes()[0] == method.getDeclaringClass();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/Platform.java b/mockito-updated/src/org/mockito/internal/util/Platform.java
new file mode 100644
index 0000000..c899b20
--- /dev/null
+++ b/mockito-updated/src/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/mockito-updated/src/org/mockito/internal/util/Primitives.java b/mockito-updated/src/org/mockito/internal/util/Primitives.java
new file mode 100644
index 0000000..1540326
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/Primitives.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+import java.util.HashMap;
+import java.util.Map;
+
+@SuppressWarnings("unchecked")
+public class Primitives {
+
+ private static final Map<Class<?>, Class<?>> PRIMITIVE_TYPES = new HashMap<Class<?>, Class<?>>();
+ private static final Map<Class<?>, Object> PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES = new HashMap<Class<?>, Object>();
+
+
+ /**
+ * Returns the primitive type of the given class.
+ * <p/>
+ * The passed class can be any class : <code>boolean.class</code>, <code>Integer.class</code>
+ * in witch case this method will return <code>boolean.class</code>, even <code>SomeObject.class</code>
+ * in which case <code>null</code> will be returned.
+ *
+ * @param clazz The class from which primitive type has to be retrieved
+ * @param <T> The type
+ * @return The primitive type if relevant, otherwise <code>null</code>
+ */
+ public static <T> Class<T> primitiveTypeOf(Class<T> clazz) {
+ if (clazz.isPrimitive()) {
+ return clazz;
+ }
+ return (Class<T>) PRIMITIVE_TYPES.get(clazz);
+ }
+
+ /**
+ * Indicates if the given class is primitive type or a primitive wrapper.
+ *
+ * @param type The type to check
+ * @return <code>true</code> if primitive or wrapper, <code>false</code> otherwise.
+ */
+ public static boolean isPrimitiveOrWrapper(Class<?> type) {
+ return PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.containsKey(type);
+ }
+
+ public static boolean isAssignableFromWrapper(Class<?> valueClass, Class<?> referenceType) {
+ if(isPrimitiveOrWrapper(valueClass) && isPrimitiveOrWrapper(referenceType)) {
+ return Primitives.primitiveTypeOf(valueClass).isAssignableFrom(referenceType);
+ }
+ return false;
+ }
+
+ /**
+ * Returns the boxed default value for a primitive or a primitive wrapper.
+ *
+ * @param primitiveOrWrapperType The type to lookup the default value
+ * @return The boxed default values as defined in Java Language Specification,
+ * <code>null</code> if the type is neither a primitive nor a wrapper
+ */
+ public static <T> T defaultValue(Class<T> primitiveOrWrapperType) {
+ return (T) PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.get(primitiveOrWrapperType);
+ }
+
+
+ static {
+ PRIMITIVE_TYPES.put(Boolean.class, Boolean.TYPE);
+ PRIMITIVE_TYPES.put(Character.class, Character.TYPE);
+ PRIMITIVE_TYPES.put(Byte.class, Byte.TYPE);
+ PRIMITIVE_TYPES.put(Short.class, Short.TYPE);
+ PRIMITIVE_TYPES.put(Integer.class, Integer.TYPE);
+ PRIMITIVE_TYPES.put(Long.class, Long.TYPE);
+ PRIMITIVE_TYPES.put(Float.class, Float.TYPE);
+ PRIMITIVE_TYPES.put(Double.class, Double.TYPE);
+ }
+
+ static {
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Boolean.class, false);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Character.class, '\u0000');
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Byte.class, (byte) 0);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Short.class, (short) 0);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Integer.class, 0);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Long.class, 0L);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Float.class, 0F);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(Double.class, 0D);
+
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(boolean.class, false);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(char.class, '\u0000');
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(byte.class, (byte) 0);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(short.class, (short) 0);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(int.class, 0);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(long.class, 0L);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(float.class, 0F);
+ PRIMITIVE_OR_WRAPPER_DEFAULT_VALUES.put(double.class, 0D);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/RemoveFirstLine.java b/mockito-updated/src/org/mockito/internal/util/RemoveFirstLine.java
new file mode 100644
index 0000000..5af9aa8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/RemoveFirstLine.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+public class RemoveFirstLine {
+
+ /**
+ * @param text to have the first line removed
+ * @return less first line
+ */
+ public String of(String text) {
+ return text.replaceFirst(".*?\n", "");
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/StringJoiner.java b/mockito-updated/src/org/mockito/internal/util/StringJoiner.java
new file mode 100644
index 0000000..061ebf0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/StringJoiner.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.util;
+
+import static java.util.Arrays.asList;
+
+/**
+ * Joins Strings together producing yet another String
+ */
+public class StringJoiner {
+
+ //TODO where's the unit test?
+
+ /**
+ * Joins Strings with line break character. It adds line break in front, too.
+ * This makes it something like 'format' no really 'join'.
+ */
+ @SuppressWarnings("unchecked")
+ public static String join(Object ... linesToBreak) {
+ return join("\n", asList(linesToBreak));
+ }
+
+ /**
+ * Joins Strings with EOL character
+ */
+ public static String join(String start, Iterable<?> lines) {
+ StringBuilder out = new StringBuilder(start);
+ for (Object line : lines) {
+ out.append(line.toString()).append("\n");
+ }
+ int lastBreak = out.lastIndexOf("\n");
+ return out.replace(lastBreak, lastBreak+1, "").toString();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/Timer.java b/mockito-updated/src/org/mockito/internal/util/Timer.java
new file mode 100644
index 0000000..dc0f18a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/Timer.java
@@ -0,0 +1,39 @@
+package org.mockito.internal.util;
+
+import static org.mockito.internal.exceptions.Reporter.cannotCreateTimerWithNegativeDurationTime;
+
+public class Timer {
+
+ private final long durationMillis;
+ private long startTime = -1;
+
+ public Timer(long durationMillis) {
+ validateInput(durationMillis);
+ this.durationMillis = durationMillis;
+ }
+
+ /**
+ * Informs whether the timer is still counting down.
+ */
+ public boolean isCounting() {
+ assert startTime != -1;
+ return System.currentTimeMillis() - startTime <= durationMillis;
+ }
+
+ /**
+ * Starts the timer count down.
+ */
+ public void start() {
+ startTime = System.currentTimeMillis();
+ }
+
+ private void validateInput(long durationMillis) {
+ if (durationMillis < 0) {
+ throw cannotCreateTimerWithNegativeDurationTime(durationMillis);
+ }
+ }
+
+ public long duration() {
+ return durationMillis;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java b/mockito-updated/src/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java
new file mode 100644
index 0000000..d8b581c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.collections;
+
+import org.mockito.internal.util.MockUtil;
+
+/**
+ * hashCode and equals safe mock wrapper.
+ *
+ * <p>
+ * It doesn't use the actual mock {@link Object#hashCode} and {@link Object#equals} method as they might
+ * throw an NPE if those method cannot be stubbed <em>even internally</em>.
+ * </p>
+ *
+ * <p>
+ * Instead the strategy is :
+ * <ul>
+ * <li>For hashCode : <strong>use {@link System#identityHashCode}</strong></li>
+ * <li>For equals : <strong>use the object reference equality</strong></li>
+ * </ul>
+ * </p>
+ *
+ * @see HashCodeAndEqualsSafeSet
+ */
+public class HashCodeAndEqualsMockWrapper {
+
+ private final Object mockInstance;
+
+ public HashCodeAndEqualsMockWrapper(Object mockInstance) {
+ this.mockInstance = mockInstance;
+ }
+
+ public Object get() {
+ return mockInstance;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof HashCodeAndEqualsMockWrapper)) return false;
+
+ HashCodeAndEqualsMockWrapper that = (HashCodeAndEqualsMockWrapper) o;
+
+ return mockInstance == that.mockInstance;
+ }
+
+ @Override
+ public int hashCode() {
+ return System.identityHashCode(mockInstance);
+ }
+
+ public static HashCodeAndEqualsMockWrapper of(Object mock) {
+ return new HashCodeAndEqualsMockWrapper(mock);
+ }
+
+ @Override public String toString() {
+ return "HashCodeAndEqualsMockWrapper{" +
+ "mockInstance=" + (MockUtil.isMock(mockInstance) ? MockUtil.getMockName(mockInstance) : typeInstanceString()) +
+ '}';
+ }
+
+ private String typeInstanceString() {
+ return mockInstance.getClass().getSimpleName() + "(" + System.identityHashCode(mockInstance) + ")";
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java b/mockito-updated/src/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java
new file mode 100644
index 0000000..d422dba
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSet.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.collections;
+
+import org.mockito.internal.util.Checks;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import static java.lang.reflect.Array.*;
+
+/**
+ * hashCode and equals safe hash based set.
+ *
+ * <p>
+ * Useful for holding mocks that have un-stubbable hashCode or equals method,
+ * meaning that in this scenario the real code is always called and will most probably
+ * cause an {@link NullPointerException}.
+ * </p>
+ * <p>
+ * This collection wraps the mock in an augmented type {@link HashCodeAndEqualsMockWrapper}
+ * that have his own implementation.
+ * </p>
+ *
+ * @see HashCodeAndEqualsMockWrapper
+ */
+public class HashCodeAndEqualsSafeSet implements Set<Object> {
+
+ private final HashSet<HashCodeAndEqualsMockWrapper> backingHashSet = new HashSet<HashCodeAndEqualsMockWrapper>();
+
+ public Iterator<Object> iterator() {
+ return new Iterator<Object>() {
+ private final Iterator<HashCodeAndEqualsMockWrapper> iterator = backingHashSet.iterator();
+
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ public Object next() {
+ return iterator.next().get();
+ }
+
+ public void remove() {
+ iterator.remove();
+ }
+ };
+ }
+
+ public int size() {
+ return backingHashSet.size();
+ }
+
+ public boolean isEmpty() {
+ return backingHashSet.isEmpty();
+ }
+
+ public boolean contains(Object mock) {
+ return backingHashSet.contains(HashCodeAndEqualsMockWrapper.of(mock));
+ }
+
+ public boolean add(Object mock) {
+ return backingHashSet.add(HashCodeAndEqualsMockWrapper.of(mock));
+ }
+
+ public boolean remove(Object mock) {
+ return backingHashSet.remove(HashCodeAndEqualsMockWrapper.of(mock));
+ }
+
+ public void clear() {
+ backingHashSet.clear();
+ }
+
+ @Override public Object clone() throws CloneNotSupportedException {
+ throw new CloneNotSupportedException();
+ }
+
+ @Override public boolean equals(Object o) {
+ if (!(o instanceof HashCodeAndEqualsSafeSet)) {
+ return false;
+ }
+ HashCodeAndEqualsSafeSet that = (HashCodeAndEqualsSafeSet) o;
+ return backingHashSet.equals(that.backingHashSet);
+ }
+
+ @Override public int hashCode() {
+ return backingHashSet.hashCode();
+ }
+
+ public Object[] toArray() {
+ return unwrapTo(new Object[size()]);
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T> T[] unwrapTo(T[] array) {
+ Iterator<Object> iterator = iterator();
+ for (int i = 0, objectsLength = array.length; i < objectsLength; i++) {
+ if (iterator.hasNext()) {
+ array[i] = (T) iterator.next();
+ }
+ }
+ return array;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T[] toArray(T[] typedArray) {
+ T[] array = typedArray.length >= size() ? typedArray : (T[]) newInstance(typedArray.getClass().getComponentType(), size());
+ return unwrapTo(array);
+ }
+
+ public boolean removeAll(Collection<?> mocks) {
+ return backingHashSet.removeAll(asWrappedMocks(mocks));
+ }
+
+ public boolean containsAll(Collection<?> mocks) {
+ return backingHashSet.containsAll(asWrappedMocks(mocks));
+ }
+
+ public boolean addAll(Collection<?> mocks) {
+ return backingHashSet.addAll(asWrappedMocks(mocks));
+ }
+
+ public boolean retainAll(Collection<?> mocks) {
+ return backingHashSet.retainAll(asWrappedMocks(mocks));
+ }
+
+ private HashSet<HashCodeAndEqualsMockWrapper> asWrappedMocks(Collection<?> mocks) {
+ Checks.checkNotNull(mocks, "Passed collection should notify() be null");
+ HashSet<HashCodeAndEqualsMockWrapper> hashSet = new HashSet<HashCodeAndEqualsMockWrapper>();
+ for (Object mock : mocks) {
+ assert ! (mock instanceof HashCodeAndEqualsMockWrapper) : "WRONG";
+ hashSet.add(HashCodeAndEqualsMockWrapper.of(mock));
+ }
+ return hashSet;
+ }
+
+ @Override public String toString() {
+ return backingHashSet.toString();
+ }
+
+ public static HashCodeAndEqualsSafeSet of(Object... mocks) {
+ return of(Arrays.asList(mocks));
+ }
+
+ public static HashCodeAndEqualsSafeSet of(Iterable<Object> objects) {
+ HashCodeAndEqualsSafeSet hashCodeAndEqualsSafeSet = new HashCodeAndEqualsSafeSet();
+ if (objects != null) {
+ for (Object mock : objects) {
+ hashCodeAndEqualsSafeSet.add(mock);
+ }
+ }
+ return hashCodeAndEqualsSafeSet;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/collections/IdentitySet.java b/mockito-updated/src/org/mockito/internal/util/collections/IdentitySet.java
new file mode 100644
index 0000000..0863717
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/collections/IdentitySet.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.collections;
+
+import java.util.LinkedList;
+
+@SuppressWarnings("unchecked")
+public class IdentitySet {
+
+ private final LinkedList list = new LinkedList();
+
+ public boolean contains(Object o) {
+ for(Object existing:list) {
+ if (existing == o) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void add(Object o) {
+ list.add(o);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/collections/Iterables.java b/mockito-updated/src/org/mockito/internal/util/collections/Iterables.java
new file mode 100644
index 0000000..9aba368
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/collections/Iterables.java
@@ -0,0 +1,22 @@
+package org.mockito.internal.util.collections;
+
+import java.util.Enumeration;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * Utilities for Iterables
+ */
+public class Iterables {
+
+ /**
+ * Converts enumeration into iterable
+ */
+ public static <T> Iterable<T> toIterable(Enumeration<T> in) {
+ List<T> out = new LinkedList<T>();
+ while(in.hasMoreElements()) {
+ out.add(in.nextElement());
+ }
+ return out;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/collections/ListUtil.java b/mockito-updated/src/org/mockito/internal/util/collections/ListUtil.java
new file mode 100644
index 0000000..b426bb2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/collections/ListUtil.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.util.collections;
+
+import java.util.Collection;
+import java.util.LinkedList;
+
+public class ListUtil {
+
+ public static <T> LinkedList<T> filter(Collection<T> collection, Filter<T> filter) {
+ LinkedList<T> filtered = new LinkedList<T>();
+ for (T t : collection) {
+ if (!filter.isOut(t)) {
+ filtered.add(t);
+ }
+ }
+ return filtered;
+ }
+
+ public interface Filter<T> {
+ boolean isOut(T object);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/collections/Sets.java b/mockito-updated/src/org/mockito/internal/util/collections/Sets.java
new file mode 100644
index 0000000..a5a80f1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/collections/Sets.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.collections;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import static java.util.Arrays.asList;
+
+public abstract class Sets {
+ public static Set<Object> newMockSafeHashSet(Iterable<Object> mocks) {
+ return HashCodeAndEqualsSafeSet.of(mocks);
+ }
+
+ public static Set<Object> newMockSafeHashSet(Object... mocks) {
+ return HashCodeAndEqualsSafeSet.of(mocks);
+ }
+
+ public static IdentitySet newIdentitySet() {
+ return new IdentitySet();
+ }
+
+ public static <T> Set<T> newSet(T ... elements) {
+ if (elements == null) {
+ throw new IllegalArgumentException("Expected an array of elements (or empty array) but received a null.");
+ }
+ return new LinkedHashSet<T>(asList(elements));
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/concurrent/DetachedThreadLocal.java b/mockito-updated/src/org/mockito/internal/util/concurrent/DetachedThreadLocal.java
new file mode 100644
index 0000000..c46405a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/concurrent/DetachedThreadLocal.java
@@ -0,0 +1,134 @@
+package org.mockito.internal.util.concurrent;
+
+/**
+ * <p>
+ * A detached local that allows for explicit control of setting and removing values from a thread-local
+ * context.
+ * </p>
+ * Instances of this class are non-blocking and fully thread safe.
+ */
+public class DetachedThreadLocal<T> implements Runnable {
+
+ final WeakConcurrentMap<Thread, T> map;
+
+ public DetachedThreadLocal(Cleaner cleaner) {
+ switch (cleaner) {
+ case THREAD:
+ case MANUAL:
+ map = new WeakConcurrentMap<Thread, T>(cleaner == Cleaner.THREAD) {
+ @Override
+ protected T defaultValue(Thread key) {
+ return DetachedThreadLocal.this.initialValue(key);
+ }
+ };
+ break;
+ case INLINE:
+ map = new WeakConcurrentMap.WithInlinedExpunction<Thread, T>() {
+ @Override
+ protected T defaultValue(Thread key) {
+ return DetachedThreadLocal.this.initialValue(key);
+ }
+ };
+ break;
+ default:
+ throw new AssertionError();
+ }
+ }
+
+ public T get() {
+ return map.get(Thread.currentThread());
+ }
+
+ public void set(T value) {
+ map.put(Thread.currentThread(), value);
+ }
+
+ public void clear() {
+ map.remove(Thread.currentThread());
+ }
+
+ /**
+ * Clears all thread local references for all threads.
+ */
+ public void clearAll() {
+ map.clear();
+ }
+
+ /**
+ * @param thread The thread to which this thread's thread local value should be pushed.
+ * @return The value being set.
+ */
+ public T pushTo(Thread thread) {
+ T value = get();
+ if (value != null) {
+ map.put(thread, inheritValue(value));
+ }
+ return value;
+ }
+
+ /**
+ * @param thread The thread from which the thread thread local value should be fetched.
+ * @return The value being set.
+ */
+ public T fetchFrom(Thread thread) {
+ T value = map.get(thread);
+ if (value != null) {
+ set(inheritValue(value));
+ }
+ return value;
+ }
+
+ /**
+ * @param thread The thread for which to set a thread-local value.
+ * @return The value accociated with this thread.
+ */
+ public T get(Thread thread) {
+ return map.get(thread);
+ }
+
+ /**
+ * @param thread The thread for which to set a thread-local value.
+ * @param value The value to set.
+ */
+ public void define(Thread thread, T value) {
+ map.put(thread, value);
+ }
+
+ /**
+ * @param thread The thread for which an initial value is created.
+ * @return The initial value for any thread local. If no default is set, the default value is {@code null}.
+ */
+ protected T initialValue(Thread thread) {
+ return null;
+ }
+
+ /**
+ * @param value The value that is inherited.
+ * @return The inherited value.
+ */
+ protected T inheritValue(T value) {
+ return value;
+ }
+
+ /**
+ * @return The weak map that backs this detached thread local.
+ */
+ public WeakConcurrentMap<Thread, T> getBackingMap() {
+ return map;
+ }
+
+ @Override
+ public void run() {
+ map.run();
+ }
+
+ /**
+ * Determines the cleaning format. A reference is removed either by an explicitly started cleaner thread
+ * associated with this instance ({@link Cleaner#THREAD}), as a result of interacting with this thread local
+ * from any thread ({@link Cleaner#INLINE} or manually by submitting the detached thread local to a thread
+ * ({@link Cleaner#MANUAL}).
+ */
+ public enum Cleaner {
+ THREAD, INLINE, MANUAL
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/concurrent/LICENSE b/mockito-updated/src/org/mockito/internal/util/concurrent/LICENSE
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/concurrent/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/mockito-updated/src/org/mockito/internal/util/concurrent/README.md b/mockito-updated/src/org/mockito/internal/util/concurrent/README.md
new file mode 100644
index 0000000..ea18bb4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/concurrent/README.md
@@ -0,0 +1,19 @@
+This is a miniature implementation of a concurrent, lock-free (as in lock-less) hash map with weak keys where keys respect reference equality. Such a hash map removes entries containing collected keys by either:
+
+1. Inline removal (entries that contain to collected keys are removed as a result of interaction with the map).
+2. Implicit concurrent removal (entries that contain collected keys are removed by an external thread).
+3. Explicit concurrent removal (explicit interaction with the map's reference queue).
+
+As a wrapper around this `WeakConcurrentMap`, this package also contains a `DetachedThreadLocal` which describes a weak concurrent map where the current thread serves as a key of the map. Also, this package delivers a `WeakConcurrentSet` as a wrapper around a weak concurrent map.
+
+This map does not implement the `java.util.Map` interface to simplify the implementation. Writes to the map might cause blocking if many threads write to the map concurrently (this is implied by the maps backing by a `ConcurrentHashMap` and a `ReferenceQueue`), the performance of the map is however significantly better than using a synchronized wrapper around a concurrent hash map.
+
+The library is hosted on *Maven Central* and *JCenter*:
+
+```xml
+<dependency>
+ <groupId>com.blogspot.mydailyjava</groupId>
+ <artifactId>weak-lock-free</artifactId>
+ <version>0.11</version>
+</dependency>
+```
diff --git a/mockito-updated/src/org/mockito/internal/util/concurrent/WeakConcurrentMap.java b/mockito-updated/src/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
new file mode 100644
index 0000000..de75f19
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
@@ -0,0 +1,360 @@
+package org.mockito.internal.util.concurrent;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * <p>
+ * A thread-safe map with weak keys. Entries are based on a key's system hash code and keys are considered
+ * equal only by reference equality.
+ * </p>
+ * This class does not implement the {@link java.util.Map} interface because this implementation is incompatible
+ * with the map contract. While iterating over a map's entries, any key that has not passed iteration is referenced non-weakly.
+ */
+public class WeakConcurrentMap<K, V> extends ReferenceQueue<K> implements Runnable, Iterable<Map.Entry<K, V>> {
+
+ private static final AtomicLong ID = new AtomicLong();
+
+ final ConcurrentMap<WeakKey<K>, V> target;
+
+ private final Thread thread;
+
+ /**
+ * @param cleanerThread {@code true} if a thread should be started that removes stale entries.
+ */
+ public WeakConcurrentMap(boolean cleanerThread) {
+ target = new ConcurrentHashMap<WeakKey<K>, V>();
+ if (cleanerThread) {
+ thread = new Thread(this);
+ thread.setName("weak-ref-cleaner-" + ID.getAndIncrement());
+ thread.setPriority(Thread.MIN_PRIORITY);
+ thread.setDaemon(true);
+ thread.start();
+ } else {
+ thread = null;
+ }
+ }
+
+ /**
+ * @param key The key of the entry.
+ * @return The value of the entry or the default value if it did not exist.
+ */
+ public V get(K key) {
+ if (key == null) throw new NullPointerException();
+ V value = target.get(new LatentKey<K>(key));
+ if (value == null) {
+ value = defaultValue(key);
+ if (value != null) {
+ V previousValue = target.putIfAbsent(new WeakKey<K>(key, this), value);
+ if (previousValue != null) {
+ value = previousValue;
+ }
+ }
+ }
+ return value;
+ }
+
+ /**
+ * @param key The key of the entry.
+ * @return {@code true} if the key already defines a value.
+ */
+ public boolean containsKey(K key) {
+ if (key == null) throw new NullPointerException();
+ return target.containsKey(new LatentKey<K>(key));
+ }
+
+ /**
+ * @param key The key of the entry.
+ * @param value The value of the entry.
+ * @return The previous entry or {@code null} if it does not exist.
+ */
+ public V put(K key, V value) {
+ if (key == null || value == null) throw new NullPointerException();
+ return target.put(new WeakKey<K>(key, this), value);
+ }
+
+ /**
+ * @param key The key of the entry.
+ * @return The removed entry or {@code null} if it does not exist.
+ */
+ public V remove(K key) {
+ if (key == null) throw new NullPointerException();
+ return target.remove(new LatentKey<K>(key));
+ }
+
+ /**
+ * Clears the entire map.
+ */
+ public void clear() {
+ target.clear();
+ }
+
+ /**
+ * Creates a default value. There is no guarantee that the requested value will be set as a once it is created
+ * in case that another thread requests a value for a key concurrently.
+ *
+ * @param key The key for which to create a default value.
+ * @return The default value for a key without value or {@code null} for not defining a default value.
+ */
+ protected V defaultValue(K key) {
+ return null;
+ }
+
+ /**
+ * @return The cleaner thread or {@code null} if no such thread was set.
+ */
+ public Thread getCleanerThread() {
+ return thread;
+ }
+
+ /**
+ * Cleans all unused references.
+ */
+ public void expungeStaleEntries() {
+ Reference<?> reference;
+ while ((reference = poll()) != null) {
+ target.remove(reference);
+ }
+ }
+
+ /**
+ * Returns the approximate size of this map where the returned number is at least as big as the actual number of entries.
+ *
+ * @return The minimum size of this map.
+ */
+ public int approximateSize() {
+ return target.size();
+ }
+
+ @Override
+ public void run() {
+ try {
+ while (true) {
+ target.remove(remove());
+ }
+ } catch (InterruptedException ignored) {
+ clear();
+ }
+ }
+
+ @Override
+ public Iterator<Map.Entry<K, V>> iterator() {
+ return new EntryIterator(target.entrySet().iterator());
+ }
+
+ /*
+ * Why this works:
+ * ---------------
+ *
+ * Note that this map only supports reference equality for keys and uses system hash codes. Also, for the
+ * WeakKey instances to function correctly, we are voluntarily breaking the Java API contract for
+ * hashCode/equals of these instances.
+ *
+ *
+ * System hash codes are immutable and can therefore be computed prematurely and are stored explicitly
+ * within the WeakKey instances. This way, we always know the correct hash code of a key and always
+ * end up in the correct bucket of our target map. This remains true even after the weakly referenced
+ * key is collected.
+ *
+ * If we are looking up the value of the current key via WeakConcurrentMap::get or any other public
+ * API method, we know that any value associated with this key must still be in the map as the mere
+ * existence of this key makes it ineligible for garbage collection. Therefore, looking up a value
+ * using another WeakKey wrapper guarantees a correct result.
+ *
+ * If we are looking up the map entry of a WeakKey after polling it from the reference queue, we know
+ * that the actual key was already collected and calling WeakKey::get returns null for both the polled
+ * instance and the instance within the map. Since we explicitly stored the identity hash code for the
+ * referenced value, it is however trivial to identify the correct bucket. From this bucket, the first
+ * weak key with a null reference is removed. Due to hash collision, we do not know if this entry
+ * represents the weak key. However, we do know that the reference queue polls at least as many weak
+ * keys as there are stale map entries within the target map. If no key is ever removed from the map
+ * explicitly, the reference queue eventually polls exactly as many weak keys as there are stale entries.
+ *
+ * Therefore, we can guarantee that there is no memory leak.
+ */
+
+ private static class WeakKey<T> extends WeakReference<T> {
+
+ private final int hashCode;
+
+ WeakKey(T key, ReferenceQueue<? super T> queue) {
+ super(key, queue);
+ hashCode = System.identityHashCode(key);
+ }
+
+ @Override
+ public int hashCode() {
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof LatentKey<?>) {
+ return ((LatentKey<?>) other).key == get();
+ } else {
+ return ((WeakKey<?>) other).get() == get();
+ }
+ }
+ }
+
+ /*
+ * A latent key must only be used for looking up instances within a map. For this to work, it implements an identical contract for
+ * hash code and equals as the WeakKey implementation. At the same time, the latent key implementation does not extend WeakReference
+ * and avoids the overhead that a weak reference implies.
+ */
+
+ private static class LatentKey<T> {
+
+ final T key;
+
+ private final int hashCode;
+
+ LatentKey(T key) {
+ this.key = key;
+ hashCode = System.identityHashCode(key);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof LatentKey<?>) {
+ return ((LatentKey<?>) other).key == key;
+ } else {
+ return ((WeakKey<?>) other).get() == key;
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return hashCode;
+ }
+ }
+
+ /**
+ * A {@link WeakConcurrentMap} where stale entries are removed as a side effect of interacting with this map.
+ */
+ public static class WithInlinedExpunction<K, V> extends WeakConcurrentMap<K, V> {
+
+ public WithInlinedExpunction() {
+ super(false);
+ }
+
+ @Override
+ public V get(K key) {
+ expungeStaleEntries();
+ return super.get(key);
+ }
+
+ @Override
+ public boolean containsKey(K key) {
+ expungeStaleEntries();
+ return super.containsKey(key);
+ }
+
+ @Override
+ public V put(K key, V value) {
+ expungeStaleEntries();
+ return super.put(key, value);
+ }
+
+ @Override
+ public V remove(K key) {
+ expungeStaleEntries();
+ return super.remove(key);
+ }
+
+ @Override
+ public Iterator<Map.Entry<K, V>> iterator() {
+ expungeStaleEntries();
+ return super.iterator();
+ }
+
+ @Override
+ public int approximateSize() {
+ expungeStaleEntries();
+ return super.approximateSize();
+ }
+ }
+
+ private class EntryIterator implements Iterator<Map.Entry<K, V>> {
+
+ private final Iterator<Map.Entry<WeakKey<K>, V>> iterator;
+
+ private Map.Entry<WeakKey<K>, V> nextEntry;
+
+ private K nextKey;
+
+ private EntryIterator(Iterator<Map.Entry<WeakKey<K>, V>> iterator) {
+ this.iterator = iterator;
+ findNext();
+ }
+
+ private void findNext() {
+ while (iterator.hasNext()) {
+ nextEntry = iterator.next();
+ nextKey = nextEntry.getKey().get();
+ if (nextKey != null) {
+ return;
+ }
+ }
+ nextEntry = null;
+ nextKey = null;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return nextKey != null;
+ }
+
+ @Override
+ public Map.Entry<K, V> next() {
+ if (nextKey == null) {
+ throw new NoSuchElementException();
+ }
+ try {
+ return new SimpleEntry(nextKey, nextEntry);
+ } finally {
+ findNext();
+ }
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private class SimpleEntry implements Map.Entry<K, V> {
+
+ private final K key;
+
+ final Map.Entry<WeakKey<K>, V> entry;
+
+ private SimpleEntry(K key, Map.Entry<WeakKey<K>, V> entry) {
+ this.key = key;
+ this.entry = entry;
+ }
+
+ @Override
+ public K getKey() {
+ return key;
+ }
+
+ @Override
+ public V getValue() {
+ return entry.getValue();
+ }
+
+ @Override
+ public V setValue(V value) {
+ if (value == null) throw new NullPointerException();
+ return entry.setValue(value);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/concurrent/WeakConcurrentSet.java b/mockito-updated/src/org/mockito/internal/util/concurrent/WeakConcurrentSet.java
new file mode 100644
index 0000000..6dcdfc2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/concurrent/WeakConcurrentSet.java
@@ -0,0 +1,128 @@
+package org.mockito.internal.util.concurrent;
+
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * <p>
+ * A thread-safe set with weak values. Entries are based on a key's system hash code and keys are considered equal only by reference equality.
+ * </p>
+ * This class does not implement the {@link java.util.Set} interface because this implementation is incompatible
+ * with the set contract. While iterating over a set's entries, any value that has not passed iteration is referenced non-weakly.
+ */
+public class WeakConcurrentSet<V> implements Runnable, Iterable<V> {
+
+ final WeakConcurrentMap<V, Boolean> target;
+
+ public WeakConcurrentSet(Cleaner cleaner) {
+ switch (cleaner) {
+ case INLINE:
+ target = new WeakConcurrentMap.WithInlinedExpunction<V, Boolean>();
+ break;
+ case THREAD:
+ case MANUAL:
+ target = new WeakConcurrentMap<V, Boolean>(cleaner == Cleaner.THREAD);
+ break;
+ default:
+ throw new AssertionError();
+ }
+ }
+
+ /**
+ * @param value The value to add to the set.
+ * @return {@code true} if the value was added to the set and was not contained before.
+ */
+ public boolean add(V value) {
+ return target.put(value, Boolean.TRUE) == null; // is null or Boolean.TRUE
+ }
+
+ /**
+ * @param value The value to check if it is contained in the set.
+ * @return {@code true} if the set contains the value.
+ */
+ public boolean contains(V value) {
+ return target.containsKey(value);
+ }
+
+ /**
+ * @param value The value to remove from the set.
+ * @return {@code true} if the value is contained in the set.
+ */
+ public boolean remove(V value) {
+ return target.remove(value);
+ }
+
+ /**
+ * Clears the set.
+ */
+ public void clear() {
+ target.clear();
+ }
+
+ /**
+ * Returns the approximate size of this set where the returned number is at least as big as the actual number of entries.
+ *
+ * @return The minimum size of this set.
+ */
+ public int approximateSize() {
+ return target.approximateSize();
+ }
+
+ @Override
+ public void run() {
+ target.run();
+ }
+
+ /**
+ * Determines the cleaning format. A reference is removed either by an explicitly started cleaner thread
+ * associated with this instance ({@link Cleaner#THREAD}), as a result of interacting with this thread local
+ * from any thread ({@link Cleaner#INLINE} or manually by submitting the detached thread local to a thread
+ * ({@link Cleaner#MANUAL}).
+ */
+ public enum Cleaner {
+ THREAD, INLINE, MANUAL
+ }
+
+ /**
+ * Cleans all unused references.
+ */
+ public void expungeStaleEntries() {
+ target.expungeStaleEntries();
+ }
+
+ /**
+ * @return The cleaner thread or {@code null} if no such thread was set.
+ */
+ public Thread getCleanerThread() {
+ return target.getCleanerThread();
+ }
+
+ @Override
+ public Iterator<V> iterator() {
+ return new ReducingIterator<V>(target.iterator());
+ }
+
+ private static class ReducingIterator<V> implements Iterator<V> {
+
+ private final Iterator<Map.Entry<V, Boolean>> iterator;
+
+ private ReducingIterator(Iterator<Map.Entry<V, Boolean>> iterator) {
+ this.iterator = iterator;
+ }
+
+ @Override
+ public void remove() {
+ iterator.remove();
+ }
+
+ @Override
+ public V next() {
+ return iterator.next().getKey();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/io/IOUtil.java b/mockito-updated/src/org/mockito/internal/util/io/IOUtil.java
new file mode 100644
index 0000000..2b90c2c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/io/IOUtil.java
@@ -0,0 +1,71 @@
+package org.mockito.internal.util.io;
+
+import org.mockito.exceptions.base.MockitoException;
+
+import java.io.*;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * IO utils. A bit of reinventing the wheel but we don't want extra dependencies at this stage and we want to be java.
+ */
+public class IOUtil {
+
+ /**
+ * Writes text to file
+ */
+ public static void writeText(String text, File output) {
+ PrintWriter pw = null;
+ try {
+ pw = new PrintWriter(new FileWriter(output));
+ pw.write(text);
+ } catch (Exception e) {
+ throw new MockitoException("Problems writing text to file: " + output, e);
+ } finally {
+ close(pw);
+ }
+ }
+
+ public static Collection<String> readLines(InputStream is) {
+ List<String> out = new LinkedList<String>();
+ BufferedReader r = new BufferedReader(new InputStreamReader(is));
+ String line;
+ try {
+ while((line = r.readLine()) != null) {
+ out.add(line);
+ }
+ } catch (IOException e) {
+ throw new MockitoException("Problems reading from: " + is, e);
+ }
+ return out;
+ }
+
+ /**
+ * Closes the target. Does nothing when target is null. Is silent.
+ *
+ * @param closeable the target, may be null
+ */
+ public static void closeQuietly(Closeable closeable) {
+ try {
+ close(closeable);
+ } catch (MockitoException ignored) {
+ //ignore, for backwards compatibility
+ }
+ }
+
+ /**
+ * Closes the target. Does nothing when target is null. Is not silent and exceptions are rethrown.
+ *
+ * @param closeable the target, may be null
+ */
+ public static void close(Closeable closeable) {
+ if (closeable != null) {
+ try {
+ closeable.close();
+ } catch (IOException e) {
+ throw new MockitoException("Problems closing stream: " + closeable, e);
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/junit/JUnitFailureHacker.java b/mockito-updated/src/org/mockito/internal/util/junit/JUnitFailureHacker.java
new file mode 100644
index 0000000..1b96af5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/junit/JUnitFailureHacker.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.junit;
+
+import org.junit.runner.notification.Failure;
+import org.mockito.internal.exceptions.ExceptionIncludingMockitoWarnings;
+
+import java.lang.reflect.Field;
+
+@Deprecated
+public class JUnitFailureHacker {
+
+ public void appendWarnings(Failure failure, String warnings) {
+ if (isEmpty(warnings)) {
+ return;
+ }
+ //TODO: this has to protect the use in case jUnit changes and this internal state logic fails
+ Throwable throwable = (Throwable) getInternalState(failure, "fThrownException");
+
+ String newMessage = "contains both: actual test failure *and* Mockito warnings.\n" +
+ warnings + "\n *** The actual failure is because of: ***\n";
+
+ ExceptionIncludingMockitoWarnings e = new ExceptionIncludingMockitoWarnings(newMessage, throwable);
+ e.setStackTrace(throwable.getStackTrace());
+ setInternalState(failure, "fThrownException", e);
+ }
+
+ private boolean isEmpty(String warnings) {
+ return warnings == null || "".equals(warnings); // isEmpty() is in JDK 6+
+ }
+
+ private static Object getInternalState(Object target, String field) {
+ Class<?> c = target.getClass();
+ try {
+ Field f = getFieldFromHierarchy(c, field);
+ f.setAccessible(true);
+ return f.get(target);
+ } catch (Exception e) {
+ throw new RuntimeException("Unable to get internal state on a private field. Please report to mockito mailing list.", e);
+ }
+ }
+
+ private static void setInternalState(Object target, String field, Object value) {
+ Class<?> c = target.getClass();
+ try {
+ Field f = getFieldFromHierarchy(c, field);
+ f.setAccessible(true);
+ f.set(target, value);
+ } catch (Exception e) {
+ throw new RuntimeException("Unable to set internal state on a private field. Please report to mockito mailing list.", e);
+ }
+ }
+
+ private static Field getFieldFromHierarchy(Class<?> clazz, String field) {
+ Field f = getField(clazz, field);
+ while (f == null && clazz != Object.class) {
+ clazz = clazz.getSuperclass();
+ f = getField(clazz, field);
+ }
+ if (f == null) {
+ throw new RuntimeException(
+ "You want me to get this field: '" + field +
+ "' on this class: '" + clazz.getSimpleName() +
+ "' but this field is not declared within the hierarchy of this class!");
+ }
+ return f;
+ }
+
+ private static Field getField(Class<?> clazz, String field) {
+ try {
+ return clazz.getDeclaredField(field);
+ } catch (NoSuchFieldException e) {
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/package.html b/mockito-updated/src/org/mockito/internal/util/package.html
new file mode 100644
index 0000000..b86ca1c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Static utils
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/AccessibilityChanger.java b/mockito-updated/src/org/mockito/internal/util/reflection/AccessibilityChanger.java
new file mode 100644
index 0000000..203b57a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/AccessibilityChanger.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.AccessibleObject;
+
+public class AccessibilityChanger {
+
+ private Boolean wasAccessible = null;
+
+ /**
+ * safely disables access
+ */
+ public void safelyDisableAccess(AccessibleObject accessibleObject) {
+ assert wasAccessible != null : "accessibility info shall not be null";
+ try {
+ accessibleObject.setAccessible(wasAccessible);
+ } catch (Throwable t) {
+ //ignore
+ }
+ }
+
+ /**
+ * changes the accessibleObject accessibility and returns true if accessibility was changed
+ */
+ public void enableAccess(AccessibleObject accessibleObject) {
+ wasAccessible = accessibleObject.isAccessible();
+ accessibleObject.setAccessible(true);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/BeanPropertySetter.java b/mockito-updated/src/org/mockito/internal/util/reflection/BeanPropertySetter.java
new file mode 100644
index 0000000..9ef9481
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/BeanPropertySetter.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Locale;
+
+/**
+ * This utility class will call the setter of the property to inject a new value.
+ */
+public class BeanPropertySetter {
+
+ private static final String SET_PREFIX = "set";
+
+ private final Object target;
+ private final boolean reportNoSetterFound;
+ private final Field field;
+
+ /**
+ * New BeanPropertySetter
+ * @param target The target on which the setter must be invoked
+ * @param propertyField The field that should be accessed with the setter
+ * @param reportNoSetterFound Allow the set method to raise an Exception if the setter cannot be found
+ */
+ public BeanPropertySetter(final Object target, final Field propertyField, boolean reportNoSetterFound) {
+ this.field = propertyField;
+ this.target = target;
+ this.reportNoSetterFound = reportNoSetterFound;
+ }
+
+ /**
+ * New BeanPropertySetter that don't report failure
+ * @param target The target on which the setter must be invoked
+ * @param propertyField The propertyField that must be accessed through a setter
+ */
+ public BeanPropertySetter(final Object target, final Field propertyField) {
+ this(target, propertyField, false);
+ }
+
+ /**
+ * Set the value to the property represented by this {@link BeanPropertySetter}
+ * @param value the new value to pass to the property setter
+ * @return <code>true</code> if the value has been injected, <code>false</code> otherwise
+ * @throws RuntimeException Can be thrown if the setter threw an exception, if the setter is not accessible
+ * or, if <code>reportNoSetterFound</code> and setter could not be found.
+ */
+ public boolean set(final Object value) {
+
+ AccessibilityChanger changer = new AccessibilityChanger();
+ Method writeMethod = null;
+ try {
+ writeMethod = target.getClass().getMethod(setterName(field.getName()), field.getType());
+
+ changer.enableAccess(writeMethod);
+ writeMethod.invoke(target, value);
+ return true;
+ } catch (InvocationTargetException e) {
+ throw new RuntimeException("Setter '" + writeMethod + "' of '" + target + "' with value '" + value + "' threw exception : '" + e.getTargetException() + "'", e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException("Access not authorized on field '" + field + "' of object '" + target + "' with value: '" + value + "'", e);
+ } catch (NoSuchMethodException e) {
+ reportNoSetterFound();
+ } finally {
+ if(writeMethod != null) {
+ changer.safelyDisableAccess(writeMethod);
+ }
+ }
+
+ reportNoSetterFound();
+ return false;
+ }
+
+ /**
+ * Retrieve the setter name from the field name.
+ *
+ * <p>Implementation is based on the code of {@link java.beans.Introspector}.</p>
+ *
+ * @param fieldName the Field name
+ * @return Setter name.
+ */
+ private String setterName(String fieldName) {
+ return new StringBuilder(SET_PREFIX)
+ .append(fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH))
+ .append(fieldName.substring(1))
+ .toString();
+ }
+
+ private void reportNoSetterFound() {
+ if(reportNoSetterFound) {
+ throw new RuntimeException("Problems setting value on object: [" + target + "] for property : [" + field.getName() + "], setter not found");
+ }
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/Constructors.java b/mockito-updated/src/org/mockito/internal/util/reflection/Constructors.java
new file mode 100644
index 0000000..909de8c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/Constructors.java
@@ -0,0 +1,20 @@
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Constructor;
+
+public abstract class Constructors {
+
+ /**
+ * Returns the no arg constructor of the type if any.
+ *
+ * @param classToMock The type to look for a no-arg constructor
+ * @return The no-arg constructor or null if none is declared.
+ */
+ public static Constructor<?> noArgConstructorOf(Class<?> classToMock) {
+ try {
+ return classToMock.getDeclaredConstructor();
+ } catch (NoSuchMethodException e) {
+ return null;
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/FieldCopier.java b/mockito-updated/src/org/mockito/internal/util/reflection/FieldCopier.java
new file mode 100644
index 0000000..67f7203
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/FieldCopier.java
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Field;
+
+public class FieldCopier {
+
+ public <T> void copyValue(T from, T to, Field field) throws IllegalAccessException {
+ Object value = field.get(from);
+ field.set(to, value);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/FieldInitializationReport.java b/mockito-updated/src/org/mockito/internal/util/reflection/FieldInitializationReport.java
new file mode 100644
index 0000000..9a0b778
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/FieldInitializationReport.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.util.reflection;
+
+/**
+ * Report on field initialization
+ */
+public class FieldInitializationReport {
+ private final Object fieldInstance;
+ private final boolean wasInitialized;
+ private final boolean wasInitializedUsingConstructorArgs;
+
+ public FieldInitializationReport(Object fieldInstance, boolean wasInitialized, boolean wasInitializedUsingConstructorArgs) {
+ this.fieldInstance = fieldInstance;
+ this.wasInitialized = wasInitialized;
+ this.wasInitializedUsingConstructorArgs = wasInitializedUsingConstructorArgs;
+ }
+
+ /**
+ * Returns the actual field instance.
+ *
+ * @return the actual instance
+ */
+ public Object fieldInstance() {
+ return fieldInstance;
+ }
+
+ /**
+ * Indicate wether the field was created during the process or not.
+ *
+ * @return <code>true</code> if created, <code>false</code> if the field did already hold an instance.
+ */
+ public boolean fieldWasInitialized() {
+ return wasInitialized;
+ }
+
+ /**
+ * Indicate wether the field was created using constructor args.
+ *
+ * @return <code>true</code> if field was created using constructor parameters.
+ */
+ public boolean fieldWasInitializedUsingContructorArgs() {
+ return wasInitializedUsingConstructorArgs;
+ }
+
+ /**
+ * Returns the class of the actual instance in the field.
+ *
+ * @return Class of the instance
+ */
+ public Class<?> fieldClass() {
+ return fieldInstance != null ? fieldInstance.getClass() : null;
+ }
+}
+
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/FieldInitializer.java b/mockito-updated/src/org/mockito/internal/util/reflection/FieldInitializer.java
new file mode 100644
index 0000000..fdc6975
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/FieldInitializer.java
@@ -0,0 +1,303 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.MockUtil;
+
+import static java.lang.reflect.Modifier.isStatic;
+import static org.mockito.internal.util.reflection.FieldSetter.setField;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Initialize a field with type instance if a default constructor can be found.
+ *
+ * <p>
+ * If the given field is already initialized, then <strong>the actual instance is returned</strong>.
+ * This initializer doesn't work with inner classes, local classes, interfaces or abstract types.
+ * </p>
+ *
+ */
+public class FieldInitializer {
+
+ private final Object fieldOwner;
+ private final Field field;
+ private final ConstructorInstantiator instantiator;
+
+
+ /**
+ * Prepare initializer with the given field on the given instance.
+ *
+ * <p>
+ * This constructor fail fast if the field type cannot be handled.
+ * </p>
+ *
+ * @param fieldOwner Instance of the test.
+ * @param field Field to be initialize.
+ */
+ public FieldInitializer(Object fieldOwner, Field field) {
+ this(fieldOwner, field, new NoArgConstructorInstantiator(fieldOwner, field));
+ }
+
+ /**
+ * Prepare initializer with the given field on the given instance.
+ *
+ * <p>
+ * This constructor fail fast if the field type cannot be handled.
+ * </p>
+ *
+ * @param fieldOwner Instance of the test.
+ * @param field Field to be initialize.
+ * @param argResolver Constructor parameters resolver
+ */
+ public FieldInitializer(Object fieldOwner, Field field, ConstructorArgumentResolver argResolver) {
+ this(fieldOwner, field, new ParameterizedConstructorInstantiator(fieldOwner, field, argResolver));
+ }
+
+ private FieldInitializer(Object fieldOwner, Field field, ConstructorInstantiator instantiator) {
+ if(new FieldReader(fieldOwner, field).isNull()) {
+ checkNotLocal(field);
+ checkNotInner(field);
+ checkNotInterface(field);
+ checkNotEnum(field);
+ checkNotAbstract(field);
+
+ }
+ this.fieldOwner = fieldOwner;
+ this.field = field;
+ this.instantiator = instantiator;
+ }
+
+ /**
+ * Initialize field if not initialized and return the actual instance.
+ *
+ * @return Actual field instance.
+ */
+ public FieldInitializationReport initialize() {
+ final AccessibilityChanger changer = new AccessibilityChanger();
+ changer.enableAccess(field);
+
+ try {
+ return acquireFieldInstance();
+ } catch(IllegalAccessException e) {
+ throw new MockitoException("Problems initializing field '" + field.getName() + "' of type '" + field.getType().getSimpleName() + "'", e);
+ } finally {
+ changer.safelyDisableAccess(field);
+ }
+ }
+
+ private void checkNotLocal(Field field) {
+ if(field.getType().isLocalClass()) {
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is a local class.");
+ }
+ }
+
+ private void checkNotInner(Field field) {
+ Class<?> type = field.getType();
+ if(type.isMemberClass() && !isStatic(type.getModifiers())) {
+ throw new MockitoException("the type '" + type.getSimpleName() + "' is an inner non static class.");
+ }
+ }
+
+ private void checkNotInterface(Field field) {
+ if(field.getType().isInterface()) {
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an interface.");
+ }
+ }
+
+ private void checkNotAbstract(Field field) {
+ if(Modifier.isAbstract(field.getType().getModifiers())) {
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an abstract class.");
+ }
+ }
+
+ private void checkNotEnum(Field field) {
+ if(field.getType().isEnum()) {
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' is an enum.");
+ }
+ }
+
+
+ private FieldInitializationReport acquireFieldInstance() throws IllegalAccessException {
+ Object fieldInstance = field.get(fieldOwner);
+ if(fieldInstance != null) {
+ return new FieldInitializationReport(fieldInstance, false, false);
+ }
+
+ return instantiator.instantiate();
+ }
+
+ /**
+ * Represents the strategy used to resolve actual instances
+ * to be given to a constructor given the argument types.
+ */
+ public interface ConstructorArgumentResolver {
+
+ /**
+ * Try to resolve instances from types.
+ *
+ * <p>
+ * Checks on the real argument type or on the correct argument number
+ * will happen during the field initialization {@link FieldInitializer#initialize()}.
+ * I.e the only responsibility of this method, is to provide instances <strong>if possible</strong>.
+ * </p>
+ *
+ * @param argTypes Constructor argument types, should not be null.
+ * @return The argument instances to be given to the constructor, should not be null.
+ */
+ Object[] resolveTypeInstances(Class<?>... argTypes);
+ }
+
+ private interface ConstructorInstantiator {
+ FieldInitializationReport instantiate();
+ }
+
+ /**
+ * Constructor instantiating strategy for no-arg constructor.
+ *
+ * <p>
+ * If a no-arg constructor can be found then the instance is created using
+ * this constructor.
+ * Otherwise a technical MockitoException is thrown.
+ * </p>
+ */
+ static class NoArgConstructorInstantiator implements ConstructorInstantiator {
+ private final Object testClass;
+ private final Field field;
+
+ /**
+ * Internal, checks are done by FieldInitializer.
+ * Fields are assumed to be accessible.
+ */
+ NoArgConstructorInstantiator(Object testClass, Field field) {
+ this.testClass = testClass;
+ this.field = field;
+ }
+
+ public FieldInitializationReport instantiate() {
+ final AccessibilityChanger changer = new AccessibilityChanger();
+ Constructor<?> constructor = null;
+ try {
+ constructor = field.getType().getDeclaredConstructor();
+ changer.enableAccess(constructor);
+
+ final Object[] noArg = new Object[0];
+ Object newFieldInstance = constructor.newInstance(noArg);
+ setField(testClass, field,newFieldInstance);
+
+ return new FieldInitializationReport(field.get(testClass), true, false);
+ } catch (NoSuchMethodException e) {
+ throw new MockitoException("the type '" + field.getType().getSimpleName() + "' has no default constructor", e);
+ } catch (InvocationTargetException e) {
+ throw new MockitoException("the default constructor of type '" + field.getType().getSimpleName() + "' has raised an exception (see the stack trace for cause): " + e.getTargetException().toString(), e);
+ } catch (InstantiationException e) {
+ throw new MockitoException("InstantiationException (see the stack trace for cause): " + e.toString(), e);
+ } catch (IllegalAccessException e) {
+ throw new MockitoException("IllegalAccessException (see the stack trace for cause): " + e.toString(), e);
+ } finally {
+ if(constructor != null) {
+ changer.safelyDisableAccess(constructor);
+ }
+ }
+ }
+ }
+
+ /**
+ * Constructor instantiating strategy for parameterized constructors.
+ *
+ * <p>
+ * Choose the constructor with the highest number of parameters, then
+ * call the ConstructorArgResolver to get actual argument instances.
+ * If the argResolver fail, then a technical MockitoException is thrown is thrown.
+ * Otherwise the instance is created with the resolved arguments.
+ * </p>
+ */
+ static class ParameterizedConstructorInstantiator implements ConstructorInstantiator {
+ private final Object testClass;
+ private final Field field;
+ private final ConstructorArgumentResolver argResolver;
+ private final Comparator<Constructor<?>> byParameterNumber = new Comparator<Constructor<?>>() {
+ public int compare(Constructor<?> constructorA, Constructor<?> constructorB) {
+ int argLengths = constructorB.getParameterTypes().length - constructorA.getParameterTypes().length;
+ if (argLengths == 0) {
+ int constructorAMockableParamsSize = countMockableParams(constructorA);
+ int constructorBMockableParamsSize = countMockableParams(constructorB);
+ return constructorBMockableParamsSize - constructorAMockableParamsSize;
+ }
+ return argLengths;
+ }
+
+ private int countMockableParams(Constructor<?> constructor) {
+ int constructorMockableParamsSize = 0;
+ for (Class<?> aClass : constructor.getParameterTypes()) {
+ if(MockUtil.typeMockabilityOf(aClass).mockable()){
+ constructorMockableParamsSize++;
+ }
+ }
+ return constructorMockableParamsSize;
+ }
+ };
+
+ /**
+ * Internal, checks are done by FieldInitializer.
+ * Fields are assumed to be accessible.
+ */
+ ParameterizedConstructorInstantiator(Object testClass, Field field, ConstructorArgumentResolver argumentResolver) {
+ this.testClass = testClass;
+ this.field = field;
+ this.argResolver = argumentResolver;
+ }
+
+ public FieldInitializationReport instantiate() {
+ final AccessibilityChanger changer = new AccessibilityChanger();
+ Constructor<?> constructor = null;
+ try {
+ constructor = biggestConstructor(field.getType());
+ changer.enableAccess(constructor);
+
+ final Object[] args = argResolver.resolveTypeInstances(constructor.getParameterTypes());
+ Object newFieldInstance = constructor.newInstance(args);
+ setField(testClass, field,newFieldInstance);
+
+ return new FieldInitializationReport(field.get(testClass), false, true);
+ } catch (IllegalArgumentException e) {
+ throw new MockitoException("internal error : argResolver provided incorrect types for constructor " + constructor + " of type " + field.getType().getSimpleName(), e);
+ } catch (InvocationTargetException e) {
+ throw new MockitoException("the constructor of type '" + field.getType().getSimpleName() + "' has raised an exception (see the stack trace for cause): " + e.getTargetException().toString(), e);
+ } catch (InstantiationException e) {
+ throw new MockitoException("InstantiationException (see the stack trace for cause): " + e.toString(), e);
+ } catch (IllegalAccessException e) {
+ throw new MockitoException("IllegalAccessException (see the stack trace for cause): " + e.toString(), e);
+ } finally {
+ if(constructor != null) {
+ changer.safelyDisableAccess(constructor);
+ }
+ }
+ }
+
+ private void checkParameterized(Constructor<?> constructor, Field field) {
+ if(constructor.getParameterTypes().length == 0) {
+ throw new MockitoException("the field " + field.getName() + " of type " + field.getType() + " has no parameterized constructor");
+ }
+ }
+
+ private Constructor<?> biggestConstructor(Class<?> clazz) {
+ final List<? extends Constructor<?>> constructors = Arrays.asList(clazz.getDeclaredConstructors());
+ Collections.sort(constructors, byParameterNumber);
+
+ Constructor<?> constructor = constructors.get(0);
+ checkParameterized(constructor, field);
+ return constructor;
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/FieldReader.java b/mockito-updated/src/org/mockito/internal/util/reflection/FieldReader.java
new file mode 100644
index 0000000..1cae117
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/FieldReader.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import org.mockito.exceptions.base.MockitoException;
+
+import java.lang.reflect.Field;
+
+public class FieldReader {
+
+ final Object target;
+ final Field field;
+ final AccessibilityChanger changer = new AccessibilityChanger();
+
+ public FieldReader(Object target, Field field) {
+ this.target = target;
+ this.field = field;
+ changer.enableAccess(field);
+ }
+
+ public boolean isNull() {
+ return read() == null;
+ }
+
+ public Object read() {
+ try {
+ return field.get(target);
+ } catch (Exception e) {
+ throw new MockitoException("Cannot read state from field: " + field + ", on instance: " + target);
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/FieldSetter.java b/mockito-updated/src/org/mockito/internal/util/reflection/FieldSetter.java
new file mode 100644
index 0000000..69b5b16
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/FieldSetter.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Field;
+
+public class FieldSetter {
+
+ private FieldSetter(){}
+
+ public static void setField(Object target, Field field,Object value) {
+ AccessibilityChanger changer = new AccessibilityChanger();
+ changer.enableAccess(field);
+ try {
+ field.set(target, value);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException("Access not authorized on field '" + field + "' of object '" + target + "' with value: '" + value + "'", e);
+ } catch (IllegalArgumentException e) {
+ throw new RuntimeException("Wrong argument on field '" + field + "' of object '" + target + "' with value: '" + value + "', \n" +
+ "reason : " + e.getMessage(), e);
+ }
+ changer.safelyDisableAccess(field);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/Fields.java b/mockito-updated/src/org/mockito/internal/util/reflection/Fields.java
new file mode 100644
index 0000000..1d1befe
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/Fields.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import org.mockito.internal.util.Checks;
+import org.mockito.internal.util.collections.ListUtil;
+import org.mockito.internal.util.collections.ListUtil.Filter;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Small fluent reflection tools to work with fields.
+ *
+ * Code is very new and might need rework.
+ */
+public abstract class Fields {
+
+ /**
+ * Instance fields declared in the class and superclasses of the given instance.
+ *
+ * @param instance Instance from which declared fields will be retrieved.
+ * @return InstanceFields of this object instance.
+ */
+ public static InstanceFields allDeclaredFieldsOf(Object instance) {
+ List<InstanceField> instanceFields = new ArrayList<InstanceField>();
+ for (Class<?> clazz = instance.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
+ instanceFields.addAll(instanceFieldsIn(instance, clazz.getDeclaredFields()));
+ }
+ return new InstanceFields(instance, instanceFields);
+ }
+
+ /**
+ * Instance fields declared in the class of the given instance.
+ *
+ * @param instance Instance from which declared fields will be retrieved.
+ * @return InstanceFields of this object instance.
+ */
+ public static InstanceFields declaredFieldsOf(Object instance) {
+ List<InstanceField> instanceFields = new ArrayList<InstanceField>();
+ instanceFields.addAll(instanceFieldsIn(instance, instance.getClass().getDeclaredFields()));
+ return new InstanceFields(instance, instanceFields);
+ }
+
+ private static List<InstanceField> instanceFieldsIn(Object instance, Field[] fields) {
+ List<InstanceField> instanceDeclaredFields = new ArrayList<InstanceField>();
+ for (Field field : fields) {
+ InstanceField instanceField = new InstanceField(field, instance);
+ instanceDeclaredFields.add(instanceField);
+ }
+ return instanceDeclaredFields;
+ }
+
+ /**
+ * Accept fields annotated by the given annotations.
+ *
+ * @param annotations Annotation types to check.
+ * @return The filter.
+ */
+ @SuppressWarnings({"unchecked", "vararg"})
+ public static Filter<InstanceField> annotatedBy(final Class<? extends Annotation>... annotations) {
+ return new Filter<InstanceField>() {
+ public boolean isOut(InstanceField instanceField) {
+ Checks.checkNotNull(annotations, "Provide at least one annotation class");
+
+ for (Class<? extends Annotation> annotation : annotations) {
+ if(instanceField.isAnnotatedBy(annotation)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ };
+ }
+
+ /**
+ * Accept fields with non null value.
+ *
+ * @return The filter.
+ */
+ private static Filter<InstanceField> nullField() {
+ return new Filter<InstanceField>() {
+ public boolean isOut(InstanceField instanceField) {
+ return instanceField.isNull();
+ }
+ };
+ }
+
+ /**
+ * Accept fields with non null value.
+ *
+ * @return The filter.
+ */
+ public static Filter<InstanceField> syntheticField() {
+ return new Filter<InstanceField>() {
+ public boolean isOut(InstanceField instanceField) {
+ return instanceField.isSynthetic();
+ }
+ };
+ }
+
+ public static class InstanceFields {
+ private final Object instance;
+
+ private final List<InstanceField> instanceFields;
+
+ public InstanceFields(Object instance, List<InstanceField> instanceFields) {
+ this.instance = instance;
+ this.instanceFields = instanceFields;
+ }
+
+ public InstanceFields filter(Filter<InstanceField> withFilter) {
+ return new InstanceFields(instance, ListUtil.filter(instanceFields, withFilter));
+ }
+
+ public InstanceFields notNull() {
+ return filter(nullField());
+ }
+
+ public List<InstanceField> instanceFields() {
+ return new ArrayList<InstanceField>(instanceFields);
+ }
+
+ public List<Object> assignedValues() {
+ List<Object> values = new ArrayList<Object>(instanceFields.size());
+ for (InstanceField instanceField : instanceFields) {
+ values.add(instanceField.read());
+ }
+ return values;
+ }
+
+ public List<String> names() {
+ List<String> fieldNames = new ArrayList<String>(instanceFields.size());
+ for (InstanceField instanceField : instanceFields) {
+ fieldNames.add(instanceField.name());
+ }
+ return fieldNames;
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/GenericMaster.java b/mockito-updated/src/org/mockito/internal/util/reflection/GenericMaster.java
new file mode 100644
index 0000000..0fc70c8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/GenericMaster.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+public class GenericMaster {
+
+ /**
+ * Finds the generic type (parametrized type) of the field. If the field is not generic it returns Object.class.
+ *
+ * @param field the field to inspect
+ */
+ public Class<?> getGenericType(Field field) {
+ Type generic = field.getGenericType();
+ if (generic instanceof ParameterizedType) {
+ Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];
+ if (actual instanceof Class) {
+ return (Class<?>) actual;
+ } else if (actual instanceof ParameterizedType) {
+ //in case of nested generics we don't go deep
+ return (Class<?>) ((ParameterizedType) actual).getRawType();
+ }
+ }
+
+ return Object.class;
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/GenericMetadataSupport.java b/mockito-updated/src/org/mockito/internal/util/reflection/GenericMetadataSupport.java
new file mode 100644
index 0000000..8efd384
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/GenericMetadataSupport.java
@@ -0,0 +1,656 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.util.Checks;
+
+import java.lang.reflect.*;
+import java.util.*;
+
+
+/**
+ * This class can retrieve generic meta-data that the compiler stores on classes
+ * and accessible members.
+ *
+ * <p>
+ * The main idea of this code is to create a Map that will help to resolve return types.
+ * In order to actually work with nested generics, this map will have to be passed along new instances
+ * as a type context.
+ * </p>
+ *
+ * <p>
+ * Hence :
+ * <ul>
+ * <li>A new instance representing the metadata is created using the {@link #inferFrom(Type)} method from a real
+ * <code>Class</code> or from a <code>ParameterizedType</code>, other types are not yet supported.</li>
+ *
+ * <li>Then from this metadata, we can extract meta-data for a generic return type of a method, using
+ * {@link #resolveGenericReturnType(Method)}.</li>
+ * </ul>
+ * </p>
+ *
+ * <p>
+ * For now this code support the following kind of generic declarations :
+ * <pre class="code"><code class="java">
+ * interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
+ * Set<Number> remove(Object key); // override with fixed ParameterizedType
+ * List<? super Integer> returning_wildcard_with_class_lower_bound();
+ * List<? super K> returning_wildcard_with_typeVar_lower_bound();
+ * List<? extends K> returning_wildcard_with_typeVar_upper_bound();
+ * K returningK();
+ * <O extends K> List<O> paramType_with_type_params();
+ * <S, T extends S> T two_type_params();
+ * <O extends K> O typeVar_with_type_params();
+ * Number returningNonGeneric();
+ * }
+ * </code></pre>
+ *
+ * @see #inferFrom(Type)
+ * @see #resolveGenericReturnType(Method)
+ * @see org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs
+ */
+public abstract class GenericMetadataSupport {
+
+ // public static MockitoLogger logger = new ConsoleMockitoLogger();
+
+ /**
+ * Represents actual type variables resolved for current class.
+ */
+ protected Map<TypeVariable<?>, Type> contextualActualTypeParameters = new HashMap<TypeVariable<?>, Type>();
+
+ /**
+ * Registers the type variables for the given type and all of its superclasses and superinterfaces.
+ */
+ protected void registerAllTypeVariables(Type classType) {
+ Queue<Type> typesToRegister = new LinkedList<Type>();
+ Set<Type> registeredTypes = new HashSet<Type>();
+ typesToRegister.add(classType);
+
+ while (!typesToRegister.isEmpty()) {
+ Type typeToRegister = typesToRegister.poll();
+ if (typeToRegister == null || registeredTypes.contains(typeToRegister)) {
+ continue;
+ }
+
+ registerTypeVariablesOn(typeToRegister);
+ registeredTypes.add(typeToRegister);
+
+ Class<?> rawType = extractRawTypeOf(typeToRegister);
+ typesToRegister.add(rawType.getGenericSuperclass());
+ typesToRegister.addAll(Arrays.asList(rawType.getGenericInterfaces()));
+ }
+ }
+
+ protected Class<?> extractRawTypeOf(Type type) {
+ if (type instanceof Class) {
+ return (Class<?>) type;
+ }
+ if (type instanceof ParameterizedType) {
+ return (Class<?>) ((ParameterizedType) type).getRawType();
+ }
+ if (type instanceof BoundedType) {
+ return extractRawTypeOf(((BoundedType) type).firstBound());
+ }
+ if (type instanceof TypeVariable) {
+ /*
+ * If type is a TypeVariable, then it is needed to gather data elsewhere. Usually TypeVariables are declared
+ * on the class definition, such as such as List<E>.
+ */
+ return extractRawTypeOf(contextualActualTypeParameters.get(type));
+ }
+ throw new MockitoException("Raw extraction not supported for : '" + type + "'");
+ }
+
+ protected void registerTypeVariablesOn(Type classType) {
+ if (!(classType instanceof ParameterizedType)) {
+ return;
+ }
+ ParameterizedType parameterizedType = (ParameterizedType) classType;
+ TypeVariable<?>[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters();
+ Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
+ for (int i = 0; i < actualTypeArguments.length; i++) {
+ TypeVariable<?> typeParameter = typeParameters[i];
+ Type actualTypeArgument = actualTypeArguments[i];
+
+ if (actualTypeArgument instanceof WildcardType) {
+ contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));
+ } else if (typeParameter != actualTypeArgument) {
+ contextualActualTypeParameters.put(typeParameter, actualTypeArgument);
+ }
+ // logger.log("For '" + parameterizedType + "' found type variable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualTypeArgument + "(" + System.identityHashCode(typeParameter) + ")" + "' }");
+ }
+ }
+
+ protected void registerTypeParametersOn(TypeVariable<?>[] typeParameters) {
+ for (TypeVariable<?> type : typeParameters) {
+ registerTypeVariableIfNotPresent(type);
+ }
+ }
+
+ private void registerTypeVariableIfNotPresent(TypeVariable<?> typeVariable) {
+ if (!contextualActualTypeParameters.containsKey(typeVariable)) {
+ contextualActualTypeParameters.put(typeVariable, boundsOf(typeVariable));
+ // logger.log("For '" + typeVariable.getGenericDeclaration() + "' found type variable : { '" + typeVariable + "(" + System.identityHashCode(typeVariable) + ")" + "' : '" + boundsOf(typeVariable) + "' }");
+ }
+ }
+
+ /**
+ * @param typeParameter The TypeVariable parameter
+ * @return A {@link BoundedType} for easy bound information, if first bound is a TypeVariable
+ * then retrieve BoundedType of this TypeVariable
+ */
+ private BoundedType boundsOf(TypeVariable<?> typeParameter) {
+ if (typeParameter.getBounds()[0] instanceof TypeVariable) {
+ return boundsOf((TypeVariable<?>) typeParameter.getBounds()[0]);
+ }
+ return new TypeVarBoundedType(typeParameter);
+ }
+
+ /**
+ * @param wildCard The WildCard type
+ * @return A {@link BoundedType} for easy bound information, if first bound is a TypeVariable
+ * then retrieve BoundedType of this TypeVariable
+ */
+ private BoundedType boundsOf(WildcardType wildCard) {
+ /*
+ * According to JLS(http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.5.1):
+ * - Lower and upper can't coexist: (for instance, this is not allowed: <? extends List<String> & super MyInterface>)
+ * - Multiple bounds are not supported (for instance, this is not allowed: <? extends List<String> & MyInterface>)
+ */
+
+ WildCardBoundedType wildCardBoundedType = new WildCardBoundedType(wildCard);
+ if (wildCardBoundedType.firstBound() instanceof TypeVariable) {
+ return boundsOf((TypeVariable<?>) wildCardBoundedType.firstBound());
+ }
+
+ return wildCardBoundedType;
+ }
+
+ /**
+ * @return Raw type of the current instance.
+ */
+ public abstract Class<?> rawType();
+
+ /**
+ * @return Returns extra interfaces <strong>if relevant</strong>, otherwise empty List.
+ */
+ public List<Type> extraInterfaces() {
+ return Collections.emptyList();
+ }
+
+ /**
+ * @return Returns an array with the raw types of {@link #extraInterfaces()} <strong>if relevant</strong>.
+ */
+ public Class<?>[] rawExtraInterfaces() {
+ return new Class[0];
+ }
+
+ /**
+ * @return Returns true if metadata knows about extra-interfaces {@link #extraInterfaces()} <strong>if relevant</strong>.
+ */
+ public boolean hasRawExtraInterfaces() {
+ return rawExtraInterfaces().length > 0;
+ }
+
+ /**
+ * @return Actual type arguments matching the type variables of the raw type represented by this {@link GenericMetadataSupport} instance.
+ */
+ public Map<TypeVariable<?>, Type> actualTypeArguments() {
+ TypeVariable<?>[] typeParameters = rawType().getTypeParameters();
+ LinkedHashMap<TypeVariable<?>, Type> actualTypeArguments = new LinkedHashMap<TypeVariable<?>, Type>();
+
+ for (TypeVariable<?> typeParameter : typeParameters) {
+
+ Type actualType = getActualTypeArgumentFor(typeParameter);
+
+ actualTypeArguments.put(typeParameter, actualType);
+ // logger.log("For '" + rawType().getCanonicalName() + "' returning explicit TypeVariable : { '" + typeParameter + "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualType +"' }");
+ }
+
+ return actualTypeArguments;
+ }
+
+ protected Type getActualTypeArgumentFor(TypeVariable<?> typeParameter) {
+ Type type = this.contextualActualTypeParameters.get(typeParameter);
+ if (type instanceof TypeVariable) {
+ TypeVariable<?> typeVariable = (TypeVariable<?>) type;
+ return getActualTypeArgumentFor(typeVariable);
+ }
+
+ return type;
+ }
+
+ /**
+ * Resolve current method generic return type to a {@link GenericMetadataSupport}.
+ *
+ * @param method Method to resolve the return type.
+ * @return {@link GenericMetadataSupport} representing this generic return type.
+ */
+ public GenericMetadataSupport resolveGenericReturnType(Method method) {
+ Type genericReturnType = method.getGenericReturnType();
+ // logger.log("Method '" + method.toGenericString() + "' has return type : " + genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType);
+
+ int arity = 0;
+ while(genericReturnType instanceof GenericArrayType) {
+ arity++;
+ genericReturnType = ((GenericArrayType) genericReturnType).getGenericComponentType();
+ }
+
+ GenericMetadataSupport genericMetadataSupport = resolveGenericType(genericReturnType, method);
+ if (arity == 0) {
+ return genericMetadataSupport;
+ } else {
+ return new GenericArrayReturnType(genericMetadataSupport, arity);
+ }
+ }
+
+ private GenericMetadataSupport resolveGenericType(Type type, Method method) {
+
+ if (type instanceof Class) {
+ return new NotGenericReturnTypeSupport(this, type);
+ }
+ if (type instanceof ParameterizedType) {
+ return new ParameterizedReturnType(this, method.getTypeParameters(), (ParameterizedType) type);
+ }
+ if (type instanceof TypeVariable) {
+ return new TypeVariableReturnType(this, method.getTypeParameters(), (TypeVariable<?>) type);
+ }
+
+ throw new MockitoException("Ouch, it shouldn't happen, type '" + type.getClass().getCanonicalName() + "' on method : '" + method.toGenericString() + "' is not supported : " + type);
+ }
+
+ /**
+ * Create an new instance of {@link GenericMetadataSupport} inferred from a {@link Type}.
+ *
+ * <p>
+ * At the moment <code>type</code> can only be a {@link Class} or a {@link ParameterizedType}, otherwise
+ * it'll throw a {@link MockitoException}.
+ * </p>
+ *
+ * @param type The class from which the {@link GenericMetadataSupport} should be built.
+ * @return The new {@link GenericMetadataSupport}.
+ * @throws MockitoException Raised if type is not a {@link Class} or a {@link ParameterizedType}.
+ */
+ public static GenericMetadataSupport inferFrom(Type type) {
+ Checks.checkNotNull(type, "type");
+ if (type instanceof Class) {
+ return new FromClassGenericMetadataSupport((Class<?>) type);
+ }
+ if (type instanceof ParameterizedType) {
+ return new FromParameterizedTypeGenericMetadataSupport((ParameterizedType) type);
+ }
+
+ throw new MockitoException("Type meta-data for this Type (" + type.getClass().getCanonicalName() + ") is not supported : " + type);
+ }
+
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ //// Below are specializations of GenericMetadataSupport that could handle retrieval of possible Types
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Generic metadata implementation for {@link Class}.
+ *
+ * Offer support to retrieve generic metadata on a {@link Class} by reading type parameters and type variables on
+ * the class and its ancestors and interfaces.
+ */
+ private static class FromClassGenericMetadataSupport extends GenericMetadataSupport {
+ private final Class<?> clazz;
+
+ public FromClassGenericMetadataSupport(Class<?> clazz) {
+ this.clazz = clazz;
+
+ registerTypeParametersOn(clazz.getTypeParameters());
+ registerAllTypeVariables(clazz);
+ }
+
+ @Override
+ public Class<?> rawType() {
+ return clazz;
+ }
+ }
+
+ /**
+ * Generic metadata implementation for "standalone" {@link ParameterizedType}.
+ *
+ * Offer support to retrieve generic metadata on a {@link ParameterizedType} by reading type variables of
+ * the related raw type and declared type variable of this parameterized type.
+ *
+ * This class is not designed to work on ParameterizedType returned by {@link Method#getGenericReturnType()}, as
+ * the ParameterizedType instance return in these cases could have Type Variables that refer to type declaration(s).
+ * That's what meant the "standalone" word at the beginning of the Javadoc.
+ * Instead use {@link ParameterizedReturnType}.
+ */
+ private static class FromParameterizedTypeGenericMetadataSupport extends GenericMetadataSupport {
+ private final ParameterizedType parameterizedType;
+
+ public FromParameterizedTypeGenericMetadataSupport(ParameterizedType parameterizedType) {
+ this.parameterizedType = parameterizedType;
+ readActualTypeParameters();
+ }
+
+ private void readActualTypeParameters() {
+ registerAllTypeVariables(parameterizedType);
+ }
+
+ @Override
+ public Class<?> rawType() {
+ return (Class<?>) parameterizedType.getRawType();
+ }
+ }
+
+ /**
+ * Generic metadata specific to {@link ParameterizedType} returned via {@link Method#getGenericReturnType()}.
+ */
+ private static class ParameterizedReturnType extends GenericMetadataSupport {
+ private final ParameterizedType parameterizedType;
+ private final TypeVariable<?>[] typeParameters;
+
+ public ParameterizedReturnType(GenericMetadataSupport source, TypeVariable<?>[] typeParameters, ParameterizedType parameterizedType) {
+ this.parameterizedType = parameterizedType;
+ this.typeParameters = typeParameters;
+ this.contextualActualTypeParameters = source.contextualActualTypeParameters;
+
+ readTypeParameters();
+ readTypeVariables();
+ }
+
+ private void readTypeParameters() {
+ registerTypeParametersOn(typeParameters);
+ }
+
+ private void readTypeVariables() {
+ registerTypeVariablesOn(parameterizedType);
+ }
+
+ @Override
+ public Class<?> rawType() {
+ return (Class<?>) parameterizedType.getRawType();
+ }
+
+ }
+
+ /**
+ * Generic metadata for {@link TypeVariable} returned via {@link Method#getGenericReturnType()}.
+ */
+ private static class TypeVariableReturnType extends GenericMetadataSupport {
+ private final TypeVariable<?> typeVariable;
+ private final TypeVariable<?>[] typeParameters;
+ private Class<?> rawType;
+
+ public TypeVariableReturnType(GenericMetadataSupport source, TypeVariable<?>[] typeParameters, TypeVariable<?> typeVariable) {
+ this.typeParameters = typeParameters;
+ this.typeVariable = typeVariable;
+ this.contextualActualTypeParameters = source.contextualActualTypeParameters;
+
+ readTypeParameters();
+ readTypeVariables();
+ }
+
+ private void readTypeParameters() {
+ registerTypeParametersOn(typeParameters);
+ }
+
+ private void readTypeVariables() {
+ for (Type type : typeVariable.getBounds()) {
+ registerTypeVariablesOn(type);
+ }
+ registerTypeParametersOn(new TypeVariable[] { typeVariable });
+ registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));
+ }
+
+ @Override
+ public Class<?> rawType() {
+ if (rawType == null) {
+ rawType = extractRawTypeOf(typeVariable);
+ }
+ return rawType;
+ }
+
+ @Override
+ public List<Type> extraInterfaces() {
+ Type type = extractActualBoundedTypeOf(typeVariable);
+ if (type instanceof BoundedType) {
+ return Arrays.asList(((BoundedType) type).interfaceBounds());
+ }
+ if (type instanceof ParameterizedType) {
+ return Collections.singletonList(type);
+ }
+ if (type instanceof Class) {
+ return Collections.emptyList();
+ }
+ throw new MockitoException("Cannot extract extra-interfaces from '" + typeVariable + "' : '" + type + "'");
+ }
+
+ /**
+ * @return Returns an array with the extracted raw types of {@link #extraInterfaces()}.
+ * @see #extractRawTypeOf(java.lang.reflect.Type)
+ */
+ public Class<?>[] rawExtraInterfaces() {
+ List<Type> extraInterfaces = extraInterfaces();
+ List<Class<?>> rawExtraInterfaces = new ArrayList<Class<?>>();
+ for (Type extraInterface : extraInterfaces) {
+ Class<?> rawInterface = extractRawTypeOf(extraInterface);
+ // avoid interface collision with actual raw type (with typevariables, resolution ca be quite aggressive)
+ if(!rawType().equals(rawInterface)) {
+ rawExtraInterfaces.add(rawInterface);
+ }
+ }
+ return rawExtraInterfaces.toArray(new Class[rawExtraInterfaces.size()]);
+ }
+
+ private Type extractActualBoundedTypeOf(Type type) {
+ if (type instanceof TypeVariable) {
+ /*
+ If type is a TypeVariable, then it is needed to gather data elsewhere. Usually TypeVariables are declared
+ on the class definition, such as such as List<E>.
+ */
+ return extractActualBoundedTypeOf(contextualActualTypeParameters.get(type));
+ }
+ if (type instanceof BoundedType) {
+ Type actualFirstBound = extractActualBoundedTypeOf(((BoundedType) type).firstBound());
+ if (!(actualFirstBound instanceof BoundedType)) {
+ return type; // avoid going one step further, ie avoid : O(TypeVar) -> K(TypeVar) -> Some ParamType
+ }
+ return actualFirstBound;
+ }
+ return type; // irrelevant, we don't manage other types as they are not bounded.
+ }
+ }
+
+ private static class GenericArrayReturnType extends GenericMetadataSupport {
+
+ private final GenericMetadataSupport genericArrayType;
+
+ private final int arity;
+
+ public GenericArrayReturnType(GenericMetadataSupport genericArrayType, int arity) {
+ this.genericArrayType = genericArrayType;
+ this.arity = arity;
+ }
+
+ @Override
+ public Class<?> rawType() {
+ Class<?> rawComponentType = genericArrayType.rawType();
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < arity; i++) {
+ stringBuilder.append("[");
+ }
+ try {
+ return Class.forName(stringBuilder.append("L").append(rawComponentType.getName()).append(";").toString(), false, rawComponentType.getClassLoader());
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("This was not supposed to happend", e);
+ }
+ }
+ }
+
+ /**
+ * Non-Generic metadata for {@link Class} returned via {@link Method#getGenericReturnType()}.
+ */
+ private static class NotGenericReturnTypeSupport extends GenericMetadataSupport {
+ private final Class<?> returnType;
+
+ public NotGenericReturnTypeSupport(GenericMetadataSupport source, Type genericReturnType) {
+ returnType = (Class<?>) genericReturnType;
+ this.contextualActualTypeParameters = source.contextualActualTypeParameters;
+
+ registerAllTypeVariables(returnType);
+ }
+
+ @Override
+ public Class<?> rawType() {
+ return returnType;
+ }
+ }
+
+
+
+ /**
+ * Type representing bounds of a type
+ *
+ * @see TypeVarBoundedType
+ * @see <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4">http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4</a>
+ * @see WildCardBoundedType
+ * @see <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.5.1">http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.5.1</a>
+ */
+ public interface BoundedType extends Type {
+ Type firstBound();
+
+ Type[] interfaceBounds();
+ }
+
+ /**
+ * Type representing bounds of a type variable, allows to keep all bounds information.
+ *
+ * <p>It uses the first bound in the array, as this array is never null and always contains at least
+ * one element (Object is always here if no bounds are declared).</p>
+ *
+ * <p>If upper bounds are declared with SomeClass and additional interfaces, then firstBound will be SomeClass and
+ * interfacesBound will be an array of the additional interfaces.
+ *
+ * i.e. <code>SomeClass</code>.
+ * <pre class="code"><code class="java">
+ * interface UpperBoundedTypeWithClass<E extends Comparable<E> & Cloneable> {
+ * E get();
+ * }
+ * // will return Comparable type
+ * </code></pre>
+ * </p>
+ *
+ * @see <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4">http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4</a>
+ */
+ public static class TypeVarBoundedType implements BoundedType {
+ private final TypeVariable<?> typeVariable;
+
+ public TypeVarBoundedType(TypeVariable<?> typeVariable) {
+ this.typeVariable = typeVariable;
+ }
+
+ /**
+ * @return either a class or an interface (parameterized or not), if no bounds declared Object is returned.
+ */
+ public Type firstBound() {
+ return typeVariable.getBounds()[0]; //
+ }
+
+ /**
+ * On a Type Variable (typeVar extends C_0 & I_1 & I_2 & etc), will return an array
+ * containing I_1 and I_2.
+ *
+ * @return other bounds for this type, these bounds can only be only interfaces as the JLS says,
+ * empty array if no other bound declared.
+ */
+ public Type[] interfaceBounds() {
+ Type[] interfaceBounds = new Type[typeVariable.getBounds().length - 1];
+ System.arraycopy(typeVariable.getBounds(), 1, interfaceBounds, 0, typeVariable.getBounds().length - 1);
+ return interfaceBounds;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ return typeVariable.equals(((TypeVarBoundedType) o).typeVariable);
+
+ }
+
+ @Override
+ public int hashCode() {
+ return typeVariable.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "{firstBound=" + firstBound() + ", interfaceBounds=" + Arrays.deepToString(interfaceBounds()) + '}';
+ }
+
+ public TypeVariable<?> typeVariable() {
+ return typeVariable;
+ }
+ }
+
+ /**
+ * Type representing bounds of a wildcard, allows to keep all bounds information.
+ *
+ * <p>The JLS says that lower bound and upper bound are mutually exclusive, and that multiple bounds
+ * are not allowed.
+ *
+ * @see <a href="http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4">http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.4</a>
+ */
+ public static class WildCardBoundedType implements BoundedType {
+ private final WildcardType wildcard;
+
+
+ public WildCardBoundedType(WildcardType wildcard) {
+ this.wildcard = wildcard;
+ }
+
+ /**
+ * @return The first bound, either a type or a reference to a TypeVariable
+ */
+ public Type firstBound() {
+ Type[] lowerBounds = wildcard.getLowerBounds();
+ Type[] upperBounds = wildcard.getUpperBounds();
+
+ return lowerBounds.length != 0 ? lowerBounds[0] : upperBounds[0];
+ }
+
+ /**
+ * @return An empty array as, wildcard don't support multiple bounds.
+ */
+ public Type[] interfaceBounds() {
+ return new Type[0];
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ return wildcard.equals(((TypeVarBoundedType) o).typeVariable);
+
+ }
+
+ @Override
+ public int hashCode() {
+ return wildcard.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "{firstBound=" + firstBound() + ", interfaceBounds=[]}";
+ }
+
+ public WildcardType wildCard() {
+ return wildcard;
+ }
+ }
+
+}
+
+
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/GenericTypeExtractor.java b/mockito-updated/src/org/mockito/internal/util/reflection/GenericTypeExtractor.java
new file mode 100644
index 0000000..a9fd336
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/GenericTypeExtractor.java
@@ -0,0 +1,84 @@
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+/**
+ * Attempts to extract generic type of given target base class or target interface
+ */
+public class GenericTypeExtractor {
+
+ /**
+ * Extract generic type of root class either from the target base class or from target base interface.
+ * Examples:
+ * <p>
+ * 1. Foo implements IFoo[Integer]:
+ * genericTypeOf(Foo.class, Object.class, IFoo.class) returns Integer
+ * <p>
+ * 2. Foo extends BaseFoo[String]:
+ * genericTypeOf(Foo.class, BaseFoo.class, IFoo.class) returns String
+ * <p>
+ * 3. Foo extends BaseFoo; BaseFoo implements IFoo[String]:
+ * genericTypeOf(Foo.class, BaseFoo.class, Object.class) returns String
+ * <p>
+ * Does not support nested generics, only supports single type parameter.
+ *
+ * @param rootClass - the root class that the search begins from
+ * @param targetBaseClass - if one of the classes in the root class' hierarchy extends this base class
+ * it will be used for generic type extraction
+ * @param targetBaseInterface - if one of the interfaces in the root class' hierarchy implements this interface
+ * it will be used for generic type extraction
+ * @return generic interface if found, Object.class if not found.
+ */
+ public static Class<?> genericTypeOf(Class<?> rootClass, Class<?> targetBaseClass, Class<?> targetBaseInterface) {
+ //looking for candidates in the hierarchy of rootClass
+ Class<?> match = rootClass;
+ while(match != Object.class) {
+ //check the super class first
+ if (match.getSuperclass() == targetBaseClass) {
+ return extractGeneric(match.getGenericSuperclass());
+ }
+ //check the interfaces (recursively)
+ Type genericInterface = findGenericInteface(match, targetBaseInterface);
+ if (genericInterface != null) {
+ return extractGeneric(genericInterface);
+ }
+ //recurse the hierarchy
+ match = match.getSuperclass();
+ }
+ return Object.class;
+ }
+
+ /**
+ * Finds generic interface implementation based on the source class and the target interface.
+ * Returns null if not found. Recurses the interface hierarchy.
+ */
+ private static Type findGenericInteface(Class<?> sourceClass, Class<?> targetBaseInterface) {
+ for (int i = 0; i < sourceClass.getInterfaces().length; i++) {
+ Class<?> inter = sourceClass.getInterfaces()[i];
+ if (inter == targetBaseInterface) {
+ return sourceClass.getGenericInterfaces()[0];
+ } else {
+ Type deeper = findGenericInteface(inter, targetBaseInterface);
+ if (deeper != null) {
+ return deeper;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Attempts to extract generic parameter type of given type.
+ * If there is no generic parameter it returns Object.class
+ */
+ private static Class<?> extractGeneric(Type type) {
+ if (type instanceof ParameterizedType) {
+ Type[] genericTypes = ((ParameterizedType) type).getActualTypeArguments();
+ if (genericTypes.length > 0 && genericTypes[0] instanceof Class) {
+ return (Class<?>) genericTypes[0];
+ }
+ }
+ return Object.class;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/InstanceField.java b/mockito-updated/src/org/mockito/internal/util/reflection/InstanceField.java
new file mode 100644
index 0000000..8756e6a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/InstanceField.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import org.mockito.internal.util.Checks;
+
+import static org.mockito.internal.util.reflection.FieldSetter.setField;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+
+/**
+ * Represents an accessible instance field.
+ *
+ * Contains the instance reference on which the field can be read adn write.
+ */
+public class InstanceField {
+ private final Field field;
+ private final Object instance;
+ private FieldReader fieldReader;
+
+ /**
+ * Create a new InstanceField.
+ *
+ * @param field The field that should be accessed, note that no checks are performed to ensure
+ * the field belong to this instance class.
+ * @param instance The instance from which the field shall be accessed.
+ */
+ public InstanceField(Field field, Object instance) {
+ this.field = Checks.checkNotNull(field, "field");
+ this.instance = Checks.checkNotNull(instance, "instance");
+ }
+
+ /**
+ * Safely read the field.
+ *
+ * @return the field value.
+ * @see FieldReader
+ */
+ public Object read() {
+ return reader().read();
+ }
+
+ /**
+ * Set the given value to the field of this instance.
+ *
+ * @param value The value that should be written to the field.
+ * @see FieldSetter
+ */
+ public void set(Object value) {
+ setField(instance, field,value);
+ }
+
+ /**
+ * Check that the field is not null.
+ *
+ * @return <code>true</code> if <code>null</code>, else <code>false</code>.
+ */
+ public boolean isNull() {
+ return reader().isNull();
+ }
+
+ /**
+ * Check if the field is annotated by the given annotation.
+ *
+ * @param annotationClass The annotation type to check.
+ * @return <code>true</code> if the field is annotated by this annotation, else <code>false</code>.
+ */
+ public boolean isAnnotatedBy(Class<? extends Annotation> annotationClass) {
+ return field.isAnnotationPresent(annotationClass);
+ }
+
+ /**
+ * Check if the field is synthetic.
+ *
+ * @return <code>true</code> if the field is synthetic, else <code>false</code>.
+ */
+ public boolean isSynthetic() {
+ return field.isSynthetic();
+ }
+
+ /**
+ * Returns the annotation instance for the given annotation type.
+ *
+ * @param annotationClass Tha annotation type to retrieve.
+ * @param <A> Type of the annotation.
+ * @return The annotation instance.
+ */
+ public <A extends Annotation> A annotation(Class<A> annotationClass) {
+ return field.getAnnotation(annotationClass);
+ }
+
+ /**
+ * Returns the JDK {@link Field} instance.
+ *
+ * @return The actual {@link Field} instance.
+ */
+ public Field jdkField() {
+ return field;
+ }
+
+ private FieldReader reader() {
+ if (fieldReader == null) {
+ fieldReader = new FieldReader(instance, field);
+ }
+ return fieldReader;
+ }
+
+ /**
+ * Returns the name of the field.
+ *
+ * @return Name of the field.
+ */
+ public String name() {
+ return field.getName();
+ }
+
+ @Override
+ public String toString() {
+ return name();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ InstanceField that = (InstanceField) o;
+ return field.equals(that.field) && instance.equals(that.instance);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = field.hashCode();
+ result = 31 * result + instance.hashCode();
+ return result;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/LenientCopyTool.java b/mockito-updated/src/org/mockito/internal/util/reflection/LenientCopyTool.java
new file mode 100644
index 0000000..c999c69
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/LenientCopyTool.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+
+@SuppressWarnings("unchecked")
+public class LenientCopyTool {
+
+ FieldCopier fieldCopier = new FieldCopier();
+
+ public <T> void copyToMock(T from, T mock) {
+ copy(from, mock, from.getClass());
+ }
+
+ public <T> void copyToRealObject(T from, T to) {
+ copy(from, to, from.getClass());
+ }
+
+ private <T> void copy(T from, T to, Class<?> fromClazz) {
+ while (fromClazz != Object.class) {
+ copyValues(from, to, fromClazz);
+ fromClazz = fromClazz.getSuperclass();
+ }
+ }
+
+ private <T> void copyValues(T from, T mock, Class<?> classFrom) {
+ Field[] fields = classFrom.getDeclaredFields();
+
+ for (Field field : fields) {
+ // ignore static fields
+ if (Modifier.isStatic(field.getModifiers())) {
+ continue;
+ }
+ AccessibilityChanger accessibilityChanger = new AccessibilityChanger();
+ try {
+ accessibilityChanger.enableAccess(field);
+ fieldCopier.copyValue(from, mock, field);
+ } catch (Throwable t) {
+ //Ignore - be lenient - if some field cannot be copied then let's be it
+ } finally {
+ accessibilityChanger.safelyDisableAccess(field);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/SuperTypesLastSorter.java b/mockito-updated/src/org/mockito/internal/util/reflection/SuperTypesLastSorter.java
new file mode 100644
index 0000000..60f2ba1
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/SuperTypesLastSorter.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2015 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.util.reflection;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Sort fields in an order suitable for injection, by name with superclasses
+ * moved after their subclasses.
+ */
+public class SuperTypesLastSorter {
+
+ private SuperTypesLastSorter() {
+ }
+
+ /**
+ * Return a new collection with the fields sorted first by name,
+ * then with any fields moved after their supertypes.
+ */
+ public static List<Field> sortSuperTypesLast(Collection<? extends Field> unsortedFields) {
+ List<Field> fields = new ArrayList<Field>(unsortedFields);
+
+ Collections.sort(fields, compareFieldsByName);
+
+ int i = 0;
+
+ while (i < fields.size() - 1) {
+ Field f = fields.get(i);
+ Class<?> ft = f.getType();
+ int newPos = i;
+ for (int j = i + 1; j < fields.size(); j++) {
+ Class<?> t = fields.get(j).getType();
+
+ if (ft != t && ft.isAssignableFrom(t)) {
+ newPos = j;
+ }
+ }
+
+ if (newPos == i) {
+ i++;
+ } else {
+ fields.remove(i);
+ fields.add(newPos, f);
+ }
+ }
+
+ return fields;
+ }
+
+
+ private static final Comparator<Field> compareFieldsByName = new Comparator<Field>() {
+ @Override
+ public int compare(Field o1, Field o2) {
+ return o1.getName().compareTo(o2.getName());
+ }
+ };
+}
diff --git a/mockito-updated/src/org/mockito/internal/util/reflection/package.html b/mockito-updated/src/org/mockito/internal/util/reflection/package.html
new file mode 100644
index 0000000..ac2eca0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/util/reflection/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+reflection utilities
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/AtLeast.java b/mockito-updated/src/org/mockito/internal/verification/AtLeast.java
new file mode 100644
index 0000000..7dbe439
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/AtLeast.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import static org.mockito.internal.verification.checkers.AtLeastXNumberOfInvocationsChecker.checkAtLeastNumberOfInvocations;
+import static org.mockito.internal.verification.checkers.MissingInvocationChecker.checkMissingInvocation;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.internal.verification.api.VerificationDataInOrder;
+import org.mockito.internal.verification.api.VerificationInOrderMode;
+import org.mockito.verification.VerificationMode;
+
+public class AtLeast implements VerificationInOrderMode, VerificationMode {
+
+ final int wantedCount;
+
+ public AtLeast(int wantedNumberOfInvocations) {
+ if (wantedNumberOfInvocations < 0) {
+ throw new MockitoException("Negative value is not allowed here");
+ }
+ this.wantedCount = wantedNumberOfInvocations;
+ }
+
+ @Override
+ public void verify(VerificationData data) {
+ if (wantedCount == 1) {
+ checkMissingInvocation(data.getAllInvocations(), data.getWanted());
+ }
+ checkAtLeastNumberOfInvocations(data.getAllInvocations(), data.getWanted(), wantedCount);
+ }
+
+ @Override
+ public void verifyInOrder(VerificationDataInOrder data) {
+ if (wantedCount == 1) {
+ checkMissingInvocation(data.getAllInvocations(), data.getWanted(), data.getOrderingContext());
+ }
+ checkAtLeastNumberOfInvocations(data.getAllInvocations(), data.getWanted(), wantedCount, data.getOrderingContext());
+ }
+
+ @Override
+ public String toString() {
+ return "Wanted invocations count: at least " + wantedCount;
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/AtMost.java b/mockito-updated/src/org/mockito/internal/verification/AtMost.java
new file mode 100644
index 0000000..8d9c750
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/AtMost.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import static org.mockito.internal.exceptions.Reporter.wantedAtMostX;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
+import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
+
+import java.util.Iterator;
+import java.util.List;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.invocation.Invocation;
+import org.mockito.verification.VerificationMode;
+
+public class AtMost implements VerificationMode {
+
+ private final int maxNumberOfInvocations;
+
+ public AtMost(int maxNumberOfInvocations) {
+ if (maxNumberOfInvocations < 0) {
+ throw new MockitoException("Negative value is not allowed here");
+ }
+ this.maxNumberOfInvocations = maxNumberOfInvocations;
+ }
+
+ public void verify(VerificationData data) {
+ List<Invocation> invocations = data.getAllInvocations();
+ InvocationMatcher wanted = data.getWanted();
+
+ List<Invocation> found = findInvocations(invocations, wanted);
+ int foundSize = found.size();
+ if (foundSize > maxNumberOfInvocations) {
+ throw wantedAtMostX(maxNumberOfInvocations, foundSize);
+ }
+
+ removeAlreadyVerified(found);
+ markVerified(found, wanted);
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+
+ private void removeAlreadyVerified(List<Invocation> invocations) {
+ for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
+ Invocation i = iterator.next();
+ if (i.isVerified()) {
+ iterator.remove();
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/Calls.java b/mockito-updated/src/org/mockito/internal/verification/Calls.java
new file mode 100644
index 0000000..dc4c278
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/Calls.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.invocation.InvocationMatcher;
+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.*;
+import org.mockito.invocation.Invocation;
+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;
+
+ public Calls(int wantedNumberOfInvocations) {
+ if( wantedNumberOfInvocations <= 0 ) {
+ throw new MockitoException( "Negative and zero values are not allowed here" );
+ }
+ this.wantedCount = wantedNumberOfInvocations;
+ }
+
+ public void verify(VerificationData data) {
+ throw new MockitoException( "calls is only intended to work with InOrder" );
+ }
+
+ public void verifyInOrder(VerificationDataInOrder data) {
+ List<Invocation> allInvocations = data.getAllInvocations();
+ InvocationMatcher wanted = data.getWanted();
+
+ checkMissingInvocation(allInvocations, wanted, data.getOrderingContext());
+ check( allInvocations, wanted, wantedCount, data.getOrderingContext());
+ }
+
+ @Override
+ public String toString() {
+ return "Wanted invocations count (non-greedy): " + wantedCount;
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/DefaultRegisteredInvocations.java b/mockito-updated/src/org/mockito/internal/verification/DefaultRegisteredInvocations.java
new file mode 100644
index 0000000..6841882
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/DefaultRegisteredInvocations.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import org.mockito.internal.util.ObjectMethodsGuru;
+import org.mockito.internal.util.collections.ListUtil;
+import org.mockito.internal.util.collections.ListUtil.Filter;
+import org.mockito.invocation.Invocation;
+
+import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
+
+import java.io.Serializable;
+import java.util.LinkedList;
+import java.util.List;
+
+
+public class DefaultRegisteredInvocations implements RegisteredInvocations, Serializable {
+
+ private static final long serialVersionUID = -2674402327380736290L;
+ private final LinkedList<Invocation> invocations = new LinkedList<Invocation>();
+
+ public void add(Invocation invocation) {
+ synchronized (invocations) {
+ invocations.add(invocation);
+ }
+ }
+
+ public void removeLast() {
+ //TODO: add specific test for synchronization of this block (it is tested by InvocationContainerImplTest at the moment)
+ synchronized (invocations) {
+ if (! invocations.isEmpty()) {
+ invocations.removeLast();
+ }
+ }
+ }
+
+ public List<Invocation> getAll() {
+ List<Invocation> copiedList;
+ synchronized (invocations) {
+ copiedList = new LinkedList<Invocation>(invocations) ;
+ }
+
+ return ListUtil.filter(copiedList, new RemoveToString());
+ }
+
+ public void clear() {
+ synchronized (invocations) {
+ invocations.clear();
+ }
+ }
+
+ public boolean isEmpty() {
+ synchronized (invocations) {
+ return invocations.isEmpty();
+ }
+ }
+
+ private static class RemoveToString implements Filter<Invocation> {
+ public boolean isOut(Invocation invocation) {
+ return isToStringMethod(invocation.getMethod());
+ }
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/Description.java b/mockito-updated/src/org/mockito/internal/verification/Description.java
new file mode 100644
index 0000000..aa5c74b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/Description.java
@@ -0,0 +1,47 @@
+package org.mockito.internal.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.verification.VerificationMode;
+
+/**
+ * Description verification mode wraps an existing verification mode and prepends
+ * a custom message to the assertion error if verification fails.
+ * @author Geoff.Schoeman
+ * @since 2.1.0
+ */
+public class Description implements VerificationMode {
+
+ private final VerificationMode verification;
+ private final String description;
+
+ /**
+ * Constructs a verification mode which wraps the given verification mode.
+ * @param verification The implementation to use for verification
+ * @param description The failure message to prepend if verification fails
+ */
+ public Description(VerificationMode verification, String description) {
+ this.verification = verification;
+ this.description = description;
+ }
+
+ /**
+ * Performs verification using the wrapped verification mode implementation.
+ * Prepends the custom failure message if verification fails.
+ * @param data the data to be verified
+ */
+ @Override
+ public void verify(VerificationData data) {
+ try {
+ verification.verify(data);
+
+ } catch (MockitoAssertionError e) {
+ throw new MockitoAssertionError(e, description);
+ }
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/InOrderContextImpl.java b/mockito-updated/src/org/mockito/internal/verification/InOrderContextImpl.java
new file mode 100644
index 0000000..ed9f611
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/InOrderContextImpl.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import org.mockito.internal.util.collections.IdentitySet;
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.invocation.Invocation;
+
+public class InOrderContextImpl implements InOrderContext {
+
+ final IdentitySet verified = new IdentitySet();
+
+ public boolean isVerified(Invocation invocation) {
+ return verified.contains(invocation);
+ }
+
+ public void markVerified(Invocation i) {
+ verified.add(i);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/InOrderWrapper.java b/mockito-updated/src/org/mockito/internal/verification/InOrderWrapper.java
new file mode 100644
index 0000000..9402444
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/InOrderWrapper.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import org.mockito.internal.InOrderImpl;
+import org.mockito.internal.invocation.finder.VerifiableInvocationsFinder;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.internal.verification.api.VerificationDataInOrderImpl;
+import org.mockito.internal.verification.api.VerificationInOrderMode;
+import org.mockito.invocation.Invocation;
+import org.mockito.verification.VerificationMode;
+
+import java.util.List;
+
+public class InOrderWrapper implements VerificationMode {
+
+ private final VerificationInOrderMode mode;
+ private final InOrderImpl inOrder;
+
+ public InOrderWrapper(VerificationInOrderMode mode, InOrderImpl inOrder) {
+ this.mode = mode;
+ this.inOrder = inOrder;
+ }
+
+ public void verify(VerificationData data) {
+ List<Invocation> invocations = VerifiableInvocationsFinder.find(inOrder.getMocksToBeVerifiedInOrder());
+ VerificationDataInOrderImpl dataInOrder = new VerificationDataInOrderImpl(inOrder, invocations, data.getWanted());
+ mode.verifyInOrder(dataInOrder);
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/MockAwareVerificationMode.java b/mockito-updated/src/org/mockito/internal/verification/MockAwareVerificationMode.java
new file mode 100644
index 0000000..70ee7fe
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/MockAwareVerificationMode.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.verification.VerificationMode;
+
+public class MockAwareVerificationMode implements VerificationMode {
+
+ private final Object mock;
+ private final VerificationMode mode;
+
+ public MockAwareVerificationMode(Object mock, VerificationMode mode) {
+ this.mock = mock;
+ this.mode = mode;
+ }
+
+ public void verify(VerificationData data) {
+ mode.verify(data);
+ }
+
+ public Object getMock() {
+ return mock;
+ }
+
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/NoMoreInteractions.java b/mockito-updated/src/org/mockito/internal/verification/NoMoreInteractions.java
new file mode 100644
index 0000000..61caa18
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/NoMoreInteractions.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import static org.mockito.internal.exceptions.Reporter.noMoreInteractionsWanted;
+import static org.mockito.internal.exceptions.Reporter.noMoreInteractionsWantedInOrder;
+import static org.mockito.internal.invocation.InvocationsFinder.findFirstUnverified;
+import static org.mockito.internal.invocation.InvocationsFinder.findFirstUnverifiedInOrder;
+
+import java.util.List;
+
+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.verification.VerificationMode;
+
+public class NoMoreInteractions implements VerificationMode, VerificationInOrderMode {
+
+ @SuppressWarnings("unchecked")
+ public void verify(VerificationData data) {
+ Invocation unverified = findFirstUnverified(data.getAllInvocations());
+ if (unverified != null) {
+ throw noMoreInteractionsWanted(unverified, (List) data.getAllInvocations());
+ }
+ }
+
+ public void verifyInOrder(VerificationDataInOrder data) {
+ List<Invocation> invocations = data.getAllInvocations();
+ Invocation unverified = findFirstUnverifiedInOrder(data.getOrderingContext(), invocations);
+
+ if (unverified != null) {
+ throw noMoreInteractionsWantedInOrder(unverified);
+ }
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/Only.java b/mockito-updated/src/org/mockito/internal/verification/Only.java
new file mode 100644
index 0000000..56864e2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/Only.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import static org.mockito.internal.exceptions.Reporter.noMoreInteractionsWanted;
+import static org.mockito.internal.exceptions.Reporter.wantedButNotInvoked;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
+import static org.mockito.internal.invocation.InvocationsFinder.findFirstUnverified;
+import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
+
+import java.util.List;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.invocation.Invocation;
+import org.mockito.verification.VerificationMode;
+
+public class Only implements VerificationMode {
+
+ @SuppressWarnings("unchecked")
+ public void verify(VerificationData data) {
+ InvocationMatcher wantedMatcher = data.getWanted();
+ List<Invocation> invocations = data.getAllInvocations();
+ List<Invocation> chunk = findInvocations(invocations,wantedMatcher);
+ if (invocations.size() != 1 && chunk.size() > 0) {
+ Invocation unverified = findFirstUnverified(invocations);
+ throw noMoreInteractionsWanted(unverified, (List) invocations);
+ }
+ if (invocations.size() != 1 || chunk.size() == 0) {
+ throw wantedButNotInvoked(wantedMatcher);
+ }
+ markVerified(chunk.get(0), wantedMatcher);
+ }
+
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/RegisteredInvocations.java b/mockito-updated/src/org/mockito/internal/verification/RegisteredInvocations.java
new file mode 100644
index 0000000..dcc49d9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/RegisteredInvocations.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import org.mockito.invocation.Invocation;
+
+import java.util.List;
+
+
+public interface RegisteredInvocations {
+
+ void add(Invocation invocation);
+
+ void removeLast();
+
+ List<Invocation> getAll();
+
+ void clear();
+
+ boolean isEmpty();
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/SingleRegisteredInvocation.java b/mockito-updated/src/org/mockito/internal/verification/SingleRegisteredInvocation.java
new file mode 100644
index 0000000..67ceafa
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/SingleRegisteredInvocation.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import org.mockito.invocation.Invocation;
+
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.List;
+
+public class SingleRegisteredInvocation implements RegisteredInvocations, Serializable {
+
+ private Invocation invocation;
+
+ public void add(Invocation invocation) {
+ this.invocation = invocation;
+ }
+
+ public void removeLast() {
+ invocation = null;
+ }
+
+ public List<Invocation> getAll() {
+ return Collections.emptyList();
+ }
+
+ public void clear() {
+ invocation = null;
+ }
+
+ public boolean isEmpty() {
+ return invocation == null;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/Times.java b/mockito-updated/src/org/mockito/internal/verification/Times.java
new file mode 100644
index 0000000..66d83d0
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/Times.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import static org.mockito.internal.verification.checkers.MissingInvocationChecker.checkMissingInvocation;
+
+import java.util.List;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.invocation.InvocationMatcher;
+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;
+
+public class Times implements VerificationInOrderMode, VerificationMode {
+
+ final int wantedCount;
+
+ public Times(int wantedNumberOfInvocations) {
+ if (wantedNumberOfInvocations < 0) {
+ throw new MockitoException("Negative value is not allowed here");
+ }
+ this.wantedCount = wantedNumberOfInvocations;
+ }
+
+ public void verify(VerificationData data) {
+ List<Invocation> invocations = data.getAllInvocations();
+ InvocationMatcher wanted = data.getWanted();
+
+ if (wantedCount > 0) {
+ checkMissingInvocation(data.getAllInvocations(), data.getWanted());
+ }
+ NumberOfInvocationsChecker numberOfInvocations = new NumberOfInvocationsChecker();
+ numberOfInvocations.check(invocations, wanted, wantedCount);
+ }
+
+ public void verifyInOrder(VerificationDataInOrder data) {
+ List<Invocation> allInvocations = data.getAllInvocations();
+ InvocationMatcher wanted = data.getWanted();
+
+ if (wantedCount > 0) {
+ checkMissingInvocation(allInvocations, wanted, data.getOrderingContext());
+ }
+ NumberOfInvocationsInOrderChecker numberOfCalls = new NumberOfInvocationsInOrderChecker();
+ numberOfCalls.check(allInvocations, wanted, wantedCount, data.getOrderingContext());
+ }
+
+ @Override
+ public String toString() {
+ return "Wanted invocations count: " + wantedCount;
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/VerificationDataImpl.java b/mockito-updated/src/org/mockito/internal/verification/VerificationDataImpl.java
new file mode 100644
index 0000000..7c979d7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/VerificationDataImpl.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.invocation.Invocation;
+
+import static org.mockito.internal.exceptions.Reporter.cannotVerifyToString;
+import static org.mockito.internal.util.ObjectMethodsGuru.isToStringMethod;
+
+import java.util.List;
+
+public class VerificationDataImpl implements VerificationData {
+
+ private final InvocationMatcher wanted;
+ private final InvocationContainer invocations;
+
+ public VerificationDataImpl(InvocationContainer invocations, InvocationMatcher wanted) {
+ this.invocations = invocations;
+ this.wanted = wanted;
+ this.assertWantedIsVerifiable();
+ }
+
+ @Override
+ public List<Invocation> getAllInvocations() {
+ return invocations.getInvocations();
+ }
+
+ @Override
+ public InvocationMatcher getWanted() {
+ return wanted;
+ }
+
+ private void assertWantedIsVerifiable() {
+ if (wanted == null) {
+ return;
+ }
+ if (isToStringMethod(wanted.getMethod())) {
+ throw cannotVerifyToString();
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/VerificationModeFactory.java b/mockito-updated/src/org/mockito/internal/verification/VerificationModeFactory.java
new file mode 100644
index 0000000..9932385
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/VerificationModeFactory.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification;
+
+import org.mockito.verification.VerificationMode;
+
+public class VerificationModeFactory {
+
+ public static VerificationMode atLeastOnce() {
+ return atLeast(1);
+ }
+
+ public static VerificationMode atLeast(int minNumberOfInvocations) {
+ return new AtLeast(minNumberOfInvocations);
+ }
+
+ public static VerificationMode only() {
+ return new Only(); //TODO make exception message nicer
+ }
+
+ public static Times times(int wantedNumberOfInvocations) {
+ return new Times(wantedNumberOfInvocations);
+ }
+
+ public static Calls calls(int wantedNumberOfInvocations) {
+ return new Calls( wantedNumberOfInvocations );
+ }
+
+ public static NoMoreInteractions noMoreInteractions() {
+ return new NoMoreInteractions();
+ }
+
+ public static VerificationMode atMost(int maxNumberOfInvocations) {
+ return new AtMost(maxNumberOfInvocations);
+ }
+
+ /**
+ * Verification mode will prepend the specified failure message if verification fails with the given implementation.
+ * @param mode Implementation used for verification
+ * @param description The custom failure message
+ * @return VerificationMode
+ * @since 2.1.0
+ */
+ public static VerificationMode description(VerificationMode mode, String description) {
+ return new Description(mode, description);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/VerificationOverTimeImpl.java b/mockito-updated/src/org/mockito/internal/verification/VerificationOverTimeImpl.java
new file mode 100644
index 0000000..aa91dab
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/VerificationOverTimeImpl.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification;
+
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.internal.util.Timer;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.verification.VerificationMode;
+
+/**
+ * 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
+ * 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 VerificationMode delegate;
+ private final boolean returnOnSuccess;
+ private final Timer timer;
+
+ /**
+ * 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 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));
+ }
+
+ /**
+ * 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 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}).
+ * @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;
+ this.delegate = delegate;
+ this.returnOnSuccess = returnOnSuccess;
+ this.timer = timer;
+ }
+
+ /**
+ * Verify the given ongoing verification data, and confirm that it satisfies the delegate verification mode
+ * before the full duration has passed.
+ *
+ * In practice, this polls the delegate verification mode until it is satisfied. If it is not satisfied once
+ * the full duration has passed, the last error returned by the delegate verification mode will be thrown
+ * here in turn. This may be thrown early if the delegate is unsatisfied and the verification mode is known
+ * to never recover from this situation (e.g. {@link AtMost}).
+ *
+ * If it is satisfied before the full duration has passed, behaviour is dependent on the returnOnSuccess parameter
+ * given in the constructor. If true, this verification mode is immediately satisfied once the delegate is. If
+ * false, this verification mode is not satisfied until the delegate is satisfied and the full time has passed.
+ *
+ * @throws MockitoAssertionError if the delegate verification mode does not succeed before the timeout
+ */
+ public void verify(VerificationData data) {
+ AssertionError error = null;
+
+ timer.start();
+ while (timer.isCounting()) {
+ try {
+ delegate.verify(data);
+
+ if (returnOnSuccess) {
+ return;
+ } else {
+ error = null;
+ }
+ } catch (MockitoAssertionError e) {
+ error = handleVerifyException(e);
+ }
+ catch (AssertionError e) {
+ error = handleVerifyException(e);
+ }
+ }
+
+ if (error != null) {
+ throw error;
+ }
+ }
+
+ private AssertionError handleVerifyException(AssertionError e) {
+ if (canRecoverFromFailure(delegate)) {
+ sleep(pollingPeriodMillis);
+ return e;
+ } else {
+ throw e;
+ }
+ }
+
+ protected boolean canRecoverFromFailure(VerificationMode verificationMode) {
+ return !(verificationMode instanceof AtMost || verificationMode instanceof NoMoreInteractions);
+ }
+
+ public VerificationOverTimeImpl copyWithVerificationMode(VerificationMode verificationMode) {
+ return new VerificationOverTimeImpl(pollingPeriodMillis, timer.duration(), verificationMode, returnOnSuccess);
+ }
+
+ private void sleep(long sleep) {
+ try {
+ Thread.sleep(sleep);
+ } catch (InterruptedException ie) {
+ throw new RuntimeException("Thread sleep has been interrupted", ie);
+ }
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+
+ public boolean isReturnOnSuccess() {
+ return returnOnSuccess;
+ }
+
+ public long getPollingPeriodMillis() {
+ return pollingPeriodMillis;
+ }
+
+ public Timer getTimer() {
+ return timer;
+ }
+
+ public VerificationMode getDelegate() {
+ return delegate;
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/VerificationWrapper.java b/mockito-updated/src/org/mockito/internal/verification/VerificationWrapper.java
new file mode 100644
index 0000000..13ad8d8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/VerificationWrapper.java
@@ -0,0 +1,44 @@
+package org.mockito.internal.verification;
+
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.verification.VerificationMode;
+
+public abstract class VerificationWrapper<WrapperType extends VerificationMode> implements VerificationMode {
+
+ protected final WrapperType wrappedVerification;
+
+ public VerificationWrapper(WrapperType wrappedVerification) {
+ this.wrappedVerification = wrappedVerification;
+ }
+
+ public void verify(VerificationData data) {
+ wrappedVerification.verify(data);
+ }
+
+ protected abstract VerificationMode copySelfWithNewVerificationMode(VerificationMode verificationMode);
+
+ public VerificationMode times(int wantedNumberOfInvocations) {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.times(wantedNumberOfInvocations));
+ }
+
+ public VerificationMode never() {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.atMost(0));
+ }
+
+ public VerificationMode atLeastOnce() {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.atLeastOnce());
+ }
+
+ public VerificationMode atLeast(int minNumberOfInvocations) {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.atLeast(minNumberOfInvocations));
+ }
+
+ public VerificationMode atMost(int maxNumberOfInvocations) {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.atMost(maxNumberOfInvocations));
+ }
+
+ public VerificationMode only() {
+ return copySelfWithNewVerificationMode(VerificationModeFactory.only());
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java b/mockito-updated/src/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
new file mode 100644
index 0000000..f04ebad
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/VerificationWrapperInOrderWrapper.java
@@ -0,0 +1,50 @@
+package org.mockito.internal.verification;
+
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.InOrderImpl;
+import org.mockito.internal.verification.api.VerificationData;
+import org.mockito.internal.verification.api.VerificationInOrderMode;
+import org.mockito.verification.VerificationMode;
+
+public class VerificationWrapperInOrderWrapper implements VerificationMode {
+ private final VerificationMode delegate;
+
+ public VerificationWrapperInOrderWrapper(VerificationWrapper<?> verificationWrapper, InOrderImpl inOrder) {
+ VerificationMode verificationMode = verificationWrapper.wrappedVerification;
+
+ VerificationMode inOrderWrappedVerificationMode = wrapInOrder(verificationWrapper, verificationMode, inOrder);
+
+ delegate = verificationWrapper.copySelfWithNewVerificationMode(inOrderWrappedVerificationMode);
+ }
+
+ @Override
+ public void verify(VerificationData data) {
+ delegate.verify(data);
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+
+ private VerificationMode wrapInOrder(VerificationWrapper<?> verificationWrapper, VerificationMode verificationMode, InOrderImpl inOrder) {
+ if (verificationMode instanceof VerificationInOrderMode) {
+ final VerificationInOrderMode verificationInOrderMode = (VerificationInOrderMode)verificationMode;
+ return new InOrderWrapper(verificationInOrderMode, inOrder);
+ }
+
+ if (verificationMode instanceof VerificationOverTimeImpl) {
+ final VerificationOverTimeImpl verificationOverTime = (VerificationOverTimeImpl)verificationMode;
+ if (verificationOverTime.isReturnOnSuccess()) {
+ return new VerificationOverTimeImpl(verificationOverTime.getPollingPeriodMillis(),
+ verificationOverTime.getTimer().duration(),
+ wrapInOrder(verificationWrapper, verificationOverTime.getDelegate(), inOrder),
+ verificationOverTime.isReturnOnSuccess());
+ }
+ }
+
+ throw new MockitoException(verificationMode.getClass().getSimpleName() +
+ " is not implemented to work with InOrder wrapped inside a " +
+ verificationWrapper.getClass().getSimpleName());
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/api/InOrderContext.java b/mockito-updated/src/org/mockito/internal/verification/api/InOrderContext.java
new file mode 100644
index 0000000..c6953be
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/api/InOrderContext.java
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.api;
+
+import org.mockito.invocation.Invocation;
+
+public interface InOrderContext {
+
+ boolean isVerified(Invocation invocation);
+
+ void markVerified(Invocation i);
+
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/api/VerificationData.java b/mockito-updated/src/org/mockito/internal/verification/api/VerificationData.java
new file mode 100644
index 0000000..52d0dd3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/api/VerificationData.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.api;
+
+import java.util.List;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+public interface VerificationData {
+
+ List<Invocation> getAllInvocations();
+
+ InvocationMatcher getWanted();
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/api/VerificationDataInOrder.java b/mockito-updated/src/org/mockito/internal/verification/api/VerificationDataInOrder.java
new file mode 100644
index 0000000..9923c99
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/api/VerificationDataInOrder.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.api;
+
+import java.util.List;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+public interface VerificationDataInOrder {
+
+ List<Invocation> getAllInvocations();
+
+ InvocationMatcher getWanted();
+
+ InOrderContext getOrderingContext();
+
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java b/mockito-updated/src/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java
new file mode 100644
index 0000000..c752a36
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/api/VerificationDataInOrderImpl.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.api;
+
+import java.util.List;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.invocation.Invocation;
+
+public class VerificationDataInOrderImpl implements VerificationDataInOrder {
+
+ private final InOrderContext inOrder;
+ private final List<Invocation> allInvocations;
+ private final InvocationMatcher wanted;
+
+ public VerificationDataInOrderImpl(InOrderContext inOrder, List<Invocation> allInvocations, InvocationMatcher wanted) {
+ this.inOrder = inOrder;
+ this.allInvocations = allInvocations;
+ this.wanted = wanted;
+ }
+
+ public List<Invocation> getAllInvocations() {
+ return allInvocations;
+ }
+
+ public InOrderContext getOrderingContext() {
+ return inOrder;
+ }
+
+ public InvocationMatcher getWanted() {
+ return wanted;
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/api/VerificationInOrderMode.java b/mockito-updated/src/org/mockito/internal/verification/api/VerificationInOrderMode.java
new file mode 100644
index 0000000..5ef4ea3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/api/VerificationInOrderMode.java
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.api;
+
+public interface VerificationInOrderMode {
+
+ void verifyInOrder(VerificationDataInOrder data);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/api/package.html b/mockito-updated/src/org/mockito/internal/verification/api/package.html
new file mode 100644
index 0000000..0001538
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/api/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+This package should be open to public once verification API is fully finished
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java b/mockito-updated/src/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java
new file mode 100644
index 0000000..cb841d2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/argumentmatching/ArgumentMatchingTool.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.argumentmatching;
+
+import org.mockito.ArgumentMatcher;
+import org.mockito.internal.matchers.ContainsExtraTypeInfo;
+
+import java.util.LinkedList;
+import java.util.List;
+
+@SuppressWarnings("unchecked")
+public class ArgumentMatchingTool {
+
+ private ArgumentMatchingTool(){}
+ /**
+ * Suspiciously not matching arguments are those that don't match, the toString() representation is the same but types are different.
+ */
+ public static Integer[] getSuspiciouslyNotMatchingArgsIndexes(List<ArgumentMatcher> matchers, Object[] arguments) {
+ if (matchers.size() != arguments.length) {
+ return new Integer[0];
+ }
+
+ List<Integer> suspicious = new LinkedList<Integer>();
+ int i = 0;
+ for (ArgumentMatcher m : matchers) {
+ if (m instanceof ContainsExtraTypeInfo
+ && !safelyMatches(m, arguments[i])
+ && toStringEquals(m, arguments[i])
+ && !((ContainsExtraTypeInfo) m).typeMatches(arguments[i])) {
+ suspicious.add(i);
+ }
+ i++;
+ }
+ return suspicious.toArray(new Integer[0]);
+ }
+
+ private static boolean safelyMatches(ArgumentMatcher m, Object arg) {
+ try {
+ return m.matches(arg);
+ } catch (Throwable t) {
+ return false;
+ }
+ }
+
+ private static boolean toStringEquals(ArgumentMatcher m, Object arg) {
+ return m.toString().equals(arg == null ? "null" : arg.toString());
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/argumentmatching/package.html b/mockito-updated/src/org/mockito/internal/verification/argumentmatching/package.html
new file mode 100644
index 0000000..d71855e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/argumentmatching/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Deals with matching arguments
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/checkers/AtLeastDiscrepancy.java b/mockito-updated/src/org/mockito/internal/verification/checkers/AtLeastDiscrepancy.java
new file mode 100644
index 0000000..48da6c7
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/AtLeastDiscrepancy.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.verification.checkers;
+
+import org.mockito.internal.reporting.Discrepancy;
+
+public class AtLeastDiscrepancy extends Discrepancy {
+
+ public AtLeastDiscrepancy(int wantedCount, int actualCount) {
+ super(wantedCount, actualCount);
+ }
+
+ @Override
+ public String getPluralizedWantedCount() {
+ return "*at least* " + super.getPluralizedWantedCount();
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java b/mockito-updated/src/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
new file mode 100644
index 0000000..0b1270c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsChecker.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.internal.verification.checkers;
+
+import java.util.Iterator;
+import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocations;
+import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocationsInOrder;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
+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 java.util.List;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
+
+public class AtLeastXNumberOfInvocationsChecker {
+
+ public static void checkAtLeastNumberOfInvocations(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount) {
+ List<Invocation> actualInvocations = findInvocations(invocations, wanted);
+
+ int actualCount = actualInvocations.size();
+ if (wantedCount > actualCount) {
+ Location lastLocation = getLastLocation(actualInvocations);
+ throw tooLittleActualInvocations(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
+ }
+
+ removeAlreadyVerified(actualInvocations);
+ markVerified(actualInvocations, wanted);
+ }
+
+ private static void removeAlreadyVerified(List<Invocation> invocations) {
+ for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
+ Invocation i = iterator.next();
+ if (i.isVerified()) {
+ iterator.remove();
+ }
+ }
+ }
+
+ public static void checkAtLeastNumberOfInvocations(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount,InOrderContext orderingContext) {
+ List<Invocation> chunk = findAllMatchingUnverifiedChunks(invocations, wanted, orderingContext);
+
+ int actualCount = chunk.size();
+
+ if (wantedCount > actualCount) {
+ Location lastLocation = getLastLocation(chunk);
+ throw tooLittleActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
+ }
+
+ markVerifiedInOrder(chunk, wanted, orderingContext);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/checkers/MissingInvocationChecker.java b/mockito-updated/src/org/mockito/internal/verification/checkers/MissingInvocationChecker.java
new file mode 100644
index 0000000..17cbe37
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/MissingInvocationChecker.java
@@ -0,0 +1,60 @@
+/*
+ * 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.argumentsAreDifferent;
+import static org.mockito.internal.exceptions.Reporter.wantedButNotInvoked;
+import static org.mockito.internal.exceptions.Reporter.wantedButNotInvokedInOrder;
+import static org.mockito.internal.invocation.InvocationsFinder.findAllMatchingUnverifiedChunks;
+import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
+import static org.mockito.internal.invocation.InvocationsFinder.findPreviousVerifiedInOrder;
+import static org.mockito.internal.invocation.InvocationsFinder.findSimilarInvocation;
+import static org.mockito.internal.verification.argumentmatching.ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes;
+
+import java.util.List;
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.reporting.SmartPrinter;
+import org.mockito.internal.verification.api.InOrderContext;
+import org.mockito.invocation.Invocation;
+
+public class MissingInvocationChecker {
+
+ private MissingInvocationChecker() {
+ }
+
+ public static void checkMissingInvocation(List<Invocation> invocations, InvocationMatcher wanted) {
+ List<Invocation> actualInvocations = findInvocations(invocations, wanted);
+
+ if (!actualInvocations.isEmpty()){
+ return;
+ }
+
+ Invocation similar = findSimilarInvocation(invocations, wanted);
+ if (similar == null) {
+ throw wantedButNotInvoked(wanted, invocations);
+ }
+
+ Integer[] indexesOfSuspiciousArgs = getSuspiciouslyNotMatchingArgsIndexes(wanted.getMatchers(), similar.getArguments());
+ SmartPrinter smartPrinter = new SmartPrinter(wanted, similar, indexesOfSuspiciousArgs);
+ throw argumentsAreDifferent(smartPrinter.getWanted(), smartPrinter.getActual(), similar.getLocation());
+
+ }
+
+ public static void checkMissingInvocation(List<Invocation> invocations, InvocationMatcher wanted, InOrderContext context) {
+ List<Invocation> chunk = findAllMatchingUnverifiedChunks(invocations, wanted, context);
+
+ if (!chunk.isEmpty()) {
+ return;
+ }
+
+ Invocation previousInOrder = findPreviousVerifiedInOrder(invocations, context);
+ if (previousInOrder != null) {
+ throw wantedButNotInvokedInOrder(wanted, previousInOrder);
+ }
+
+ checkMissingInvocation(invocations, wanted);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java b/mockito-updated/src/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
new file mode 100644
index 0000000..0d44d18
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/NonGreedyNumberOfInvocationsInOrderChecker.java
@@ -0,0 +1,38 @@
+/*
+ * 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;
+
+public class NonGreedyNumberOfInvocationsInOrderChecker {
+
+ private NonGreedyNumberOfInvocationsInOrderChecker() {}
+
+ public static void check(List<Invocation> invocations, InvocationMatcher 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/mockito-updated/src/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java b/mockito-updated/src/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
new file mode 100644
index 0000000..4f5e282
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/NumberOfInvocationsChecker.java
@@ -0,0 +1,54 @@
+/*
+ * 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.neverWantedButInvoked;
+import static org.mockito.internal.exceptions.Reporter.tooLittleActualInvocations;
+import static org.mockito.internal.exceptions.Reporter.tooManyActualInvocations;
+import static org.mockito.internal.invocation.InvocationMarker.markVerified;
+import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;
+import static org.mockito.internal.invocation.InvocationsFinder.getLastLocation;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.mockito.internal.invocation.InvocationMatcher;
+import org.mockito.internal.reporting.Discrepancy;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.Location;
+
+public class NumberOfInvocationsChecker {
+
+ public void check(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount) {
+ List<Invocation> actualInvocations = findInvocations(invocations, wanted);
+
+ int actualCount = actualInvocations.size();
+ if (wantedCount > actualCount) {
+ Location lastInvocation = getLastLocation(actualInvocations);
+ throw tooLittleActualInvocations(new Discrepancy(wantedCount, actualCount), wanted, lastInvocation);
+ }
+ if (wantedCount == 0 && actualCount > 0) {
+ Location firstUndesired = actualInvocations.get(wantedCount).getLocation();
+ throw neverWantedButInvoked(wanted, firstUndesired);
+ }
+ if (wantedCount < actualCount) {
+ Location firstUndesired = actualInvocations.get(wantedCount).getLocation();
+ throw tooManyActualInvocations(wantedCount, actualCount, wanted, firstUndesired);
+ }
+
+ removeAlreadyVerified(actualInvocations);
+ markVerified(actualInvocations, wanted);
+ }
+
+ private void removeAlreadyVerified(List<Invocation> invocations) {
+ for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
+ Invocation i = iterator.next();
+ if (i.isVerified()) {
+ iterator.remove();
+ }
+ }
+ }
+}
diff --git a/mockito-updated/src/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java b/mockito-updated/src/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
new file mode 100644
index 0000000..7be9f40
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderChecker.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.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;
+
+public class NumberOfInvocationsInOrderChecker {
+
+ public void check(List<Invocation> invocations, InvocationMatcher 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/mockito-updated/src/org/mockito/internal/verification/checkers/package.html b/mockito-updated/src/org/mockito/internal/verification/checkers/package.html
new file mode 100644
index 0000000..a248590
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/checkers/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+verification checkers
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/internal/verification/package.html b/mockito-updated/src/org/mockito/internal/verification/package.html
new file mode 100644
index 0000000..171df4b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/internal/verification/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Verification logic.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/invocation/DescribedInvocation.java b/mockito-updated/src/org/mockito/invocation/DescribedInvocation.java
new file mode 100644
index 0000000..fc975ab
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/DescribedInvocation.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.invocation;
+
+
+/**
+ * Provides information about the invocation, specifically a human readable description and the location.
+ */
+public interface DescribedInvocation {
+
+ /**
+ * Describes the invocation in the human friendly way.
+ *
+ * @return the description of this invocation.
+ */
+ String toString();
+
+ /**
+ * The place in the code where the invocation happened.
+ *
+ * @return the location of the invocation.
+ */
+ Location getLocation();
+}
diff --git a/mockito-updated/src/org/mockito/invocation/Invocation.java b/mockito-updated/src/org/mockito/invocation/Invocation.java
new file mode 100644
index 0000000..ca2d29f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/Invocation.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.invocation;
+
+/**
+ * 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.
+ * <p>
+ * The javadoc does not have lots of examples or documentation because its audience is different.
+ * Vast majority of users don't need to use the Invocation. It's mostly useful for other framework authors
+ * that extend Mockito.
+ *
+ * @since 1.9.5
+ */
+public interface Invocation extends InvocationOnMock, DescribedInvocation {
+
+ /**
+ * @return whether the invocation has been already verified.
+ * Needed for {@link org.mockito.Mockito#verifyNoMoreInteractions(Object...)}
+ */
+ boolean isVerified();
+
+ /**
+ * @return the sequence number of the Invocation. Useful to determine the order of invocations.
+ * Used by verification in order.
+ */
+ int getSequenceNumber();
+
+ /**
+ * @return the location in code of this invocation.
+ */
+ Location getLocation();
+
+ /**
+ * Returns unprocessed arguments whereas {@link #getArguments()} returns
+ * arguments already processed (e.g. varargs expended, etc.).
+ *
+ * @return unprocessed arguments, exactly as provided to this invocation.
+ */
+ Object[] getRawArguments();
+
+ /**
+ * Returns unprocessed arguments whereas {@link #getArguments()} returns
+ * arguments already processed (e.g. varargs expended, etc.).
+ *
+ * @return unprocessed arguments, exactly as provided to this invocation.
+ */
+ Class<?> getRawReturnType();
+
+ /**
+ * Marks this invocation as verified so that it will not cause verification error at
+ * {@link org.mockito.Mockito#verifyNoMoreInteractions(Object...)}
+ */
+ void markVerified();
+
+ /**
+ * @return the stubbing information for this invocation. May return null - this means
+ * the invocation was not stubbed.
+ */
+ StubInfo stubInfo();
+
+ /**
+ * Marks this invocation as stubbed.
+ *
+ * @param stubInfo the information about stubbing.
+ */
+ void markStubbed(StubInfo stubInfo);
+
+ /**
+ * Informs if the invocation participates in verify-no-more-invocations or verification in order.
+ *
+ * @return whether this invocation should be ignored for the purposes of
+ * verify-no-more-invocations or verification in order.
+ */
+ boolean isIgnoredForVerification();
+
+ /**
+ * Configures this invocation to be ignored for verify-no-more-invocations or verification in order.
+ * See also {@link #isIgnoredForVerification()}
+ */
+ void ignoreForVerification();
+}
diff --git a/mockito-updated/src/org/mockito/invocation/InvocationOnMock.java b/mockito-updated/src/org/mockito/invocation/InvocationOnMock.java
new file mode 100644
index 0000000..cde2777
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/InvocationOnMock.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.invocation;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+
+/**
+ * An invocation on a mock
+ * <p>
+ * A placeholder for mock, the method that was called and the arguments that were passed.
+ */
+public interface InvocationOnMock extends Serializable {
+
+ /**
+ * returns the mock object
+ *
+ * @return mock object
+ */
+ Object getMock();
+
+ /**
+ * returns the method
+ *
+ * @return method
+ */
+ Method getMethod();
+
+ /**
+ * returns arguments passed to the method
+ *
+ * @return arguments
+ */
+ Object[] getArguments();
+
+ /**
+ * Returns casted argument at the given index
+ * @param index argument index
+ * @return casted argument at the given index
+ * @since 2.1.0
+ */
+ <T> T getArgument(int index);
+
+
+ /**
+ * calls real method
+ * <p>
+ * <b>Warning:</b> depending on the real implementation it might throw exceptions
+ *
+ * @return whatever the real method returns / throws
+ * @throws Throwable in case real method throws
+ */
+ Object callRealMethod() throws Throwable;
+}
diff --git a/mockito-updated/src/org/mockito/invocation/Location.java b/mockito-updated/src/org/mockito/invocation/Location.java
new file mode 100644
index 0000000..e362704
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/Location.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.invocation;
+
+/**
+ * Describes the location of something in the source code.
+ */
+public interface Location {
+
+ /**
+ * @return the location
+ */
+ String toString();
+
+}
diff --git a/mockito-updated/src/org/mockito/invocation/MockHandler.java b/mockito-updated/src/org/mockito/invocation/MockHandler.java
new file mode 100644
index 0000000..1fbdf44
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/MockHandler.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.invocation;
+
+import java.io.Serializable;
+
+/**
+ * Mockito handler of an invocation on a mock. This is a core part of the API, the heart of Mockito.
+ * See also the {@link org.mockito.plugins.MockMaker}.
+ * <p>
+ * This api is work in progress. Do not provide your own implementations.
+ * Mockito will provide you with the implementation via other {@link org.mockito.plugins.MockMaker} methods.
+ */
+public interface MockHandler extends Serializable {
+ /**
+ * Takes an invocation object and handles it.
+ * <p>
+ * The default implementation provided by Mockito handles invocations by recording
+ * method calls on mocks for further verification, captures the stubbing information when mock is stubbed,
+ * returns the stubbed values for invocations that have been stubbed, and much more.
+ *
+ * @param invocation The invocation to handle
+ * @return Result
+ * @throws Throwable Throwable
+ */
+ Object handle(Invocation invocation) throws Throwable;
+}
diff --git a/mockito-updated/src/org/mockito/invocation/StubInfo.java b/mockito-updated/src/org/mockito/invocation/StubInfo.java
new file mode 100644
index 0000000..6247336
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/StubInfo.java
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.invocation;
+
+/**
+ * The information about stubbing, for example the location of stubbing.
+ */
+public interface StubInfo {
+
+ /**
+ * @return the location where the invocation was stubbed.
+ */
+ Location stubbedAt();
+}
diff --git a/mockito-updated/src/org/mockito/invocation/package.html b/mockito-updated/src/org/mockito/invocation/package.html
new file mode 100644
index 0000000..e6742e2
--- /dev/null
+++ b/mockito-updated/src/org/mockito/invocation/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Public API related to invocation
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/junit/MockitoJUnit.java b/mockito-updated/src/org/mockito/junit/MockitoJUnit.java
new file mode 100644
index 0000000..6f2c1f5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/junit/MockitoJUnit.java
@@ -0,0 +1,37 @@
+package org.mockito.junit;
+
+import org.mockito.Incubating;
+import org.mockito.internal.junit.JUnitRule;
+import org.mockito.internal.junit.VerificationCollectorImpl;
+import org.mockito.internal.util.ConsoleMockitoLogger;
+
+/**
+ * The JUnit rule can be used instead of {@link org.mockito.runners.MockitoJUnitRunner}. See {@link MockitoRule}.
+ *
+ * @since 1.10.17
+ */
+public class MockitoJUnit {
+
+ /**
+ * Creates rule instance that initiates @Mocks
+ * For more details and examples see {@link MockitoRule}.
+ *
+ * @return the rule instance
+ * @since 1.10.17
+ */
+ public static MockitoRule rule() {
+ return new JUnitRule(new ConsoleMockitoLogger(), false);
+ }
+
+ /**
+ * Creates a rule instance that can perform lazy verifications.
+ *
+ * @see VerificationCollector
+ * @return the rule instance
+ * @since 2.1.0
+ */
+ @Incubating
+ public static VerificationCollector collector() {
+ return new VerificationCollectorImpl();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/junit/MockitoRule.java b/mockito-updated/src/org/mockito/junit/MockitoRule.java
new file mode 100644
index 0000000..d46cfc6
--- /dev/null
+++ b/mockito-updated/src/org/mockito/junit/MockitoRule.java
@@ -0,0 +1,75 @@
+package org.mockito.junit;
+
+import org.junit.rules.MethodRule;
+
+/**
+ * Since 2.1.0, JUnit rule emits stubbing warnings and hints to System output
+ * (see also {@link org.mockito.quality.MockitoHint}).
+ * The JUnit rule can be used instead of {@link org.mockito.runners.MockitoJUnitRunner}.
+ * It requires JUnit at least 4.7.
+ *
+ * This rule adds following behavior:
+ * <ul>
+ * <li>
+ * Since 2.1.0, stubbing warnings and hints are printed to System output.
+ * Hints contain clickable links that take you right to the line of code that contains a possible problem.
+ * <strong>Please</strong> give us feedback about the stubbing warnings of JUnit rules in the issue tracker
+ * (<a href="https://github.com/mockito/mockito/issues/384">issue 384</a>).
+ * It's a new feature of Mockito 2.1.0. It aims to help debugging tests.
+ * If you wish the previous behavior, see {@link MockitoRule#silent()}.
+ * However, we would really like to know why do you wish to silence the warnings!
+ * See also {@link org.mockito.quality.MockitoHint}.
+ * <li>
+ * Initializes mocks annotated with {@link org.mockito.Mock},
+ * so that explicit usage of {@link org.mockito.MockitoAnnotations#initMocks(Object)} is not necessary.
+ * Mocks are initialized before each test method.
+ * <li>
+ * Validates framework usage after each test method. See javadoc for {@link org.mockito.Mockito#validateMockitoUsage()}.
+ *
+ * </ul>
+ * Example use:
+ * <pre class="code"><code class="java">
+ * public class ExampleTest {
+ *
+ * @Rule
+ * public MockitoRule rule = MockitoJUnit.rule();
+ *
+ * @Mock
+ * private List list;
+ *
+ * @Test
+ * public void shouldDoSomething() {
+ * list.add(100);
+ * }
+ * }
+ * </code></pre>
+ *
+ * @since 1.10.17
+ */
+public interface MockitoRule extends MethodRule {
+
+ /**
+ * Rule will not report stubbing warnings during test execution.
+ * By default, stubbing warnings are printed to Standard output to help debugging.
+ * <p>
+ * <strong>Please</strong> give us feedback about the stubbing warnings of JUnit rules.
+ * It's a new feature of Mockito 2.1.0. It aims to help debugging tests.
+ * We want to make sure the feature is useful.
+ * We would really like to know why do you wish to silence the warnings!
+ * See also {@link org.mockito.quality.MockitoHint}.
+ * <p>
+ *
+ * Example:
+ * <pre class="code"><code class="java">
+ * public class ExampleTest {
+ *
+ * @Rule
+ * public MockitoRule rule = MockitoJUnit.rule().silent();
+ *
+ * }
+ * </code></pre>
+ *
+ * @since 2.1.0
+ */
+ MockitoRule silent();
+}
diff --git a/mockito-updated/src/org/mockito/junit/VerificationCollector.java b/mockito-updated/src/org/mockito/junit/VerificationCollector.java
new file mode 100644
index 0000000..ffa965e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/junit/VerificationCollector.java
@@ -0,0 +1,98 @@
+package org.mockito.junit;
+
+import org.junit.rules.TestRule;
+import org.mockito.Incubating;
+import org.mockito.exceptions.base.MockitoAssertionError;
+import org.mockito.verification.VerificationMode;
+
+/**
+ * Use this rule in order to collect multiple verification failures and report at once.
+ * This new API in incubating - let us know if you find this feature useful.
+ * Should it be turned on by default with Mockito JUnit Rule?
+ * <p>
+ * Although {@code VerificationCollector} is a JUnit Rule, it does not necessarily have to be used as a Test Rule
+ * - see {@link #collectAndReport()}.
+ * <p>
+ * In the example below, the verification failure thrown by {@code byteReturningMethod()} does not block
+ * verifying against the {@code simpleMethod()}. After the test is run, a report is generated stating all
+ * collect verification failures.
+ *
+ * <pre class="code"><code class="java">
+ * @Rule
+ * public VerificationCollector collector = MockitoJUnit.collector();
+ *
+ * @Test
+ * public void should_fail() {
+ * IMethods methods = mock(IMethods.class);
+ *
+ * verify(methods).byteReturningMethod();
+ * verify(methods).simpleMethod();
+ * }
+ * </code></pre>
+ *
+ * @see org.mockito.Mockito#verify(Object)
+ * @see org.mockito.Mockito#verify(Object, VerificationMode)
+ * @since 2.1.0
+ */
+@Incubating
+public interface VerificationCollector extends TestRule {
+
+ /**
+ * Collect all lazily verified behaviour. If there were failed verifications, it will
+ * throw a MockitoAssertionError containing all messages indicating the failed verifications.
+ * <p>
+ * Normally, users don't need to call this method because it is automatically invoked when test finishes
+ * (part of the JUnit Rule behavior).
+ * However, in some circumstances and edge cases, it might be useful to collect and report verification
+ * errors in the middle of the test (for example: some scenario tests or during debugging).
+ *
+ * <pre class="code"><code class="java">
+ * @Rule
+ * public VerificationCollector collector = MockitoJUnit.collector();
+ *
+ * @Test
+ * public void should_fail() {
+ * IMethods methods = mock(IMethods.class);
+ *
+ * verify(methods).byteReturningMethod();
+ * verify(methods).simpleMethod();
+ *
+ * //report all verification errors now:
+ * collector.collectAndReport();
+ *
+ * //some other test code
+ * }
+ * </code></pre>
+ *
+ * @throws MockitoAssertionError If there were failed verifications
+ * @since 2.1.0
+ */
+ @Incubating
+ void collectAndReport() throws MockitoAssertionError;
+
+ /**
+ * Enforce all verifications are performed lazily. This method is automatically called when
+ * used as JUnitRule and normally users don't need to use it.
+ * <p>
+ * You should only use this method if you are using a VerificationCollector
+ * inside a method where only this method should be verified lazily. The other methods can
+ * still be verified directly.
+ *
+ * <pre class="code"><code class="java">
+ * @Test
+ * public void should_verify_lazily() {
+ * VerificationCollector collector = MockitoJUnit.collector().assertLazily();
+ *
+ * verify(methods).byteReturningMethod();
+ * verify(methods).simpleMethod();
+ *
+ * collector.collectAndReport();
+ * }
+ * </code></pre>
+ *
+ * @return this
+ * @since 2.1.0
+ */
+ @Incubating
+ VerificationCollector assertLazily();
+}
diff --git a/mockito-updated/src/org/mockito/listeners/InvocationListener.java b/mockito-updated/src/org/mockito/listeners/InvocationListener.java
new file mode 100644
index 0000000..5a9e38f
--- /dev/null
+++ b/mockito-updated/src/org/mockito/listeners/InvocationListener.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.listeners;
+
+import org.mockito.MockSettings;
+
+/**
+ * This listener can be notified of method invocations on a mock.
+ *
+ * For this to happen, it must be registered using {@link MockSettings#invocationListeners(InvocationListener...)}.
+ */
+public interface InvocationListener {
+
+ /**
+ * Called after the invocation of the listener's mock if it returned normally.
+ *
+ * <p>
+ * Exceptions caused by this invocationListener will raise a {@link org.mockito.exceptions.base.MockitoException}.
+ * </p>
+ *
+ * @param methodInvocationReport Information about the method call that just happened.
+ *
+ * @see MethodInvocationReport
+ */
+ void reportInvocation(MethodInvocationReport methodInvocationReport);
+}
diff --git a/mockito-updated/src/org/mockito/listeners/MethodInvocationReport.java b/mockito-updated/src/org/mockito/listeners/MethodInvocationReport.java
new file mode 100644
index 0000000..a7303e8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/listeners/MethodInvocationReport.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.listeners;
+
+import org.mockito.invocation.DescribedInvocation;
+
+/**
+ * Represent a method call on a mock.
+ *
+ * <p>
+ * Contains the information on the mock, the location of the stub
+ * the return value if it returned something (maybe null), or an
+ * exception if one was thrown when the method was invoked.
+ * </p>
+ */
+public interface MethodInvocationReport {
+ /**
+ * @return Information on the method call, never {@code null}
+ */
+ DescribedInvocation getInvocation();
+
+ /**
+ * @return The resulting value of the method invocation, may be <code>null</code>
+ */
+ Object getReturnedValue();
+
+ /**
+ * @return The throwable raised by the method invocation, maybe <code>null</code>
+ */
+ Throwable getThrowable();
+
+ /**
+ * @return <code>true</code> if an exception was raised, <code>false</code> otherwise
+ */
+ boolean threwException();
+
+ /**
+ * @return Location of the stub invocation
+ */
+ String getLocationOfStubbing();
+}
diff --git a/mockito-updated/src/org/mockito/listeners/MockCreationListener.java b/mockito-updated/src/org/mockito/listeners/MockCreationListener.java
new file mode 100644
index 0000000..d0dd4ca
--- /dev/null
+++ b/mockito-updated/src/org/mockito/listeners/MockCreationListener.java
@@ -0,0 +1,18 @@
+package org.mockito.listeners;
+
+import org.mockito.mock.MockCreationSettings;
+
+/**
+ * Notified when mock object is created.
+ * For more information on listeners see {@link org.mockito.MockitoFramework#addListener(MockitoListener)}.
+ */
+public interface MockCreationListener extends MockitoListener {
+
+ /**
+ * Mock object was just created.
+ *
+ * @param mock created mock object
+ * @param settings the settings used for creation
+ */
+ void onMockCreated(Object mock, MockCreationSettings settings);
+}
diff --git a/mockito-updated/src/org/mockito/listeners/MockitoListener.java b/mockito-updated/src/org/mockito/listeners/MockitoListener.java
new file mode 100644
index 0000000..0d34ac5
--- /dev/null
+++ b/mockito-updated/src/org/mockito/listeners/MockitoListener.java
@@ -0,0 +1,8 @@
+package org.mockito.listeners;
+
+/**
+ * Marker interface for all types of Mockito listeners.
+ * For more information, see {@link org.mockito.MockitoFramework#addListener(MockitoListener)}.
+ */
+public interface MockitoListener {
+}
diff --git a/mockito-updated/src/org/mockito/listeners/package.html b/mockito-updated/src/org/mockito/listeners/package.html
new file mode 100644
index 0000000..a81d8fb
--- /dev/null
+++ b/mockito-updated/src/org/mockito/listeners/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Public classes relative to the call listener.
+</body>
diff --git a/mockito-updated/src/org/mockito/mock/MockCreationSettings.java b/mockito-updated/src/org/mockito/mock/MockCreationSettings.java
new file mode 100644
index 0000000..d1c9c9a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/mock/MockCreationSettings.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.mock;
+
+import org.mockito.Incubating;
+import org.mockito.listeners.InvocationListener;
+import org.mockito.stubbing.Answer;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Informs about the mock settings. An immutable view of {@link org.mockito.MockSettings}.
+ */
+public interface MockCreationSettings<T> {
+
+ /**
+ * Mocked type. An interface or class the mock should implement / extend.
+ */
+ Class<T> getTypeToMock();
+
+ /**
+ * the extra interfaces the mock object should implement.
+ */
+ Set<Class<?>> getExtraInterfaces();
+
+ /**
+ * the name of this mock, as printed on verification errors; see {@link org.mockito.MockSettings#name}.
+ */
+ MockName getMockName();
+
+ /**
+ * the default answer for this mock, see {@link org.mockito.MockSettings#defaultAnswer}.
+ */
+ Answer<?> getDefaultAnswer();
+
+ /**
+ * the spied instance - needed for spies.
+ */
+ Object getSpiedInstance();
+
+ /**
+ * if the mock is serializable, see {@link org.mockito.MockSettings#serializable}.
+ */
+ boolean isSerializable();
+
+ /**
+ * @return the serializable mode of this mock
+ */
+ SerializableMode getSerializableMode();
+
+ /**
+ * Whether the mock is only for stubbing, i.e. does not remember
+ * parameters on its invocation and therefore cannot
+ * be used for verification
+ */
+ boolean isStubOnly();
+
+ /**
+ * The invocation listeners attached to this mock, see {@link org.mockito.MockSettings#invocationListeners}.
+ */
+ List<InvocationListener> getInvocationListeners();
+
+ /**
+ * Informs whether the mock instance should be created via constructor
+ *
+ * @since 1.10.12
+ */
+ @Incubating
+ boolean isUsingConstructor();
+
+ /**
+ * Used when mocking non-static inner classes in conjunction with {@link #isUsingConstructor()}
+ *
+ * @return the outer class instance used for creation of the mock object via the constructor.
+ * @since 1.10.12
+ */
+ @Incubating
+ Object getOuterClassInstance();
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/mock/MockName.java b/mockito-updated/src/org/mockito/mock/MockName.java
new file mode 100644
index 0000000..d3f6e7d
--- /dev/null
+++ b/mockito-updated/src/org/mockito/mock/MockName.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.mock;
+
+/**
+ * Represents the name of the mock as shown in the verification failure reports, etc.
+ */
+public interface MockName {
+
+ /**
+ * the name
+ */
+ String toString();
+
+ /**
+ * default name means generated by Mockito. non-default means the user has named the mock at creation.
+ */
+ boolean isDefault();
+}
diff --git a/mockito-updated/src/org/mockito/mock/SerializableMode.java b/mockito-updated/src/org/mockito/mock/SerializableMode.java
new file mode 100644
index 0000000..d10b1d6
--- /dev/null
+++ b/mockito-updated/src/org/mockito/mock/SerializableMode.java
@@ -0,0 +1,26 @@
+package org.mockito.mock;
+
+import org.mockito.Incubating;
+
+/**
+ * Mock serializable style.
+ */
+@Incubating
+public enum SerializableMode {
+
+ /**
+ * No serialization.
+ */
+ NONE,
+
+ /**
+ * Basic serializable mode for mock objects. Introduced in Mockito 1.8.1.
+ */
+ BASIC,
+
+ /**
+ * Useful if the mock is deserialized in a different classloader / vm.
+ */
+ @Incubating
+ ACROSS_CLASSLOADERS
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/package.html b/mockito-updated/src/org/mockito/package.html
new file mode 100644
index 0000000..e54efb3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Mockito is a mock library for java - see Mockito class for for usage.
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/plugins/InstantiatorProvider.java b/mockito-updated/src/org/mockito/plugins/InstantiatorProvider.java
new file mode 100644
index 0000000..098c191
--- /dev/null
+++ b/mockito-updated/src/org/mockito/plugins/InstantiatorProvider.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.plugins;
+
+import org.mockito.internal.creation.instance.Instantiator;
+import org.mockito.mock.MockCreationSettings;
+
+/**
+ * <p>
+ * Mockito will invoke this interface in order to fetch an instance instantiator provider.
+ * </p>
+ *
+ * <p>
+ * By default, an internal byte-buddy/asm/objenesis based implementation is used.
+ * </p>
+ *
+ * <h3>Using the extension point</h3>
+ *
+ * <p>
+ * The plugin mechanism of mockito works in a similar way as the
+ * {@link java.util.ServiceLoader}, however instead of looking in the <code>META-INF</code>
+ * directory, Mockito will look in <code>mockito-extensions</code> directory.
+ * <em>The reason for that is that Android SDK strips jar from the <code>META-INF</code>
+ * directory when creating an APK.</em>
+ * </p>
+ *
+ * <ol style="list-style-type: lower-alpha">
+ * <li>The implementation itself, for example
+ * <code>org.awesome.mockito.AwesomeInstantiatorProvider</code> that implements the
+ * <code>InstantiatorProvider</code>.</li>
+ * <li>A file "<code>mockito-extensions/org.mockito.plugins.InstantiatorProvider</code>".
+ * The content of this file is exactly a <strong>one</strong> line with the qualified
+ * name: <code>org.awesome.mockito.AwesomeInstantiatorProvider</code>.</li>
+ * </ol></p>
+ *
+ * <p>
+ * Note that if several <code>mockito-extensions/org.mockito.plugins.InstantiatorProvider</code>
+ * files exists in the classpath, Mockito will only use the first returned by the standard
+ * {@link ClassLoader#getResource} mechanism.
+ * <p>
+ * So just create a custom implementation of {@link InstantiatorProvider} and place the
+ * qualified name in the following file
+ * <code>mockito-extensions/org.mockito.plugins.InstantiatorProvider</code>.
+ * </p>
+ *
+ * @since 21.10.15
+ */
+public interface InstantiatorProvider {
+
+ /**
+ * Returns an instantiator, used to create new class instances.
+ */
+ Instantiator getInstantiator(MockCreationSettings<?> settings);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/plugins/MockMaker.java b/mockito-updated/src/org/mockito/plugins/MockMaker.java
new file mode 100644
index 0000000..e4b0ca8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/plugins/MockMaker.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.plugins;
+
+import org.mockito.Incubating;
+import org.mockito.invocation.MockHandler;
+import org.mockito.mock.MockCreationSettings;
+
+/**
+ * The facility to create mocks.
+ *
+ * <p>By default, an internal byte-buddy/asm/objenesis based implementation is used.</p>
+ *
+ * <p>{@code MockMaker} is an extension point that makes it possible to use custom dynamic proxies
+ * and avoid using the default byte-buddy/asm/objenesis implementation.
+ * For example, the android users can use a MockMaker that can work with Dalvik virtual machine
+ * and hence bring Mockito to android apps developers.</p>
+ *
+ * <h3>Using the extension point</h3>
+ *
+ * <p>Suppose you wrote an extension to create mocks with some <em>Awesome</em> library, in order to tell
+ * Mockito to use it you need to put in your <strong>classpath</strong>:
+ * <ol style="list-style-type: lower-alpha">
+ * <li>
+ * The implementation itself, for example <code>org.awesome.mockito.AwesomeMockMaker</code> that
+ * extends the <code>MockMaker</code>.
+ * </li>
+ * <li>
+ * A file "<code>mockito-extensions/org.mockito.plugins.MockMaker</code>". The content of this file is
+ * exactly a <strong>one</strong> line with the qualified name:
+ * <code>org.awesome.mockito.AwesomeMockMaker</code>.
+* </li>
+ * </ol>
+ * </p>
+ *
+ * <p>Note that if several <code>mockito-extensions/org.mockito.plugins.MockMaker</code> files exists in the classpath
+ * Mockito will only use the first returned by the standard {@link ClassLoader#getResource} mechanism.
+ *
+ * @see org.mockito.mock.MockCreationSettings
+ * @see org.mockito.invocation.MockHandler
+ * @since 1.9.5
+ */
+public interface MockMaker {
+
+ /**
+ * If you want to provide your own implementation of {@code MockMaker} this method should:
+ * <ul>
+ * <li>Create a proxy object that implements {@code settings.typeToMock} and potentially also {@code settings.extraInterfaces}.</li>
+ * <li>You may use the information from {@code settings} to create/configure your proxy object.</li>
+ * <li>Your proxy object should carry the {@code handler} with it. For example, if you generate byte code
+ * to create the proxy you could generate an extra field to keep the {@code handler} with the generated object.
+ * Your implementation of {@code MockMaker} is required to provide this instance of {@code handler} when
+ * {@link #getHandler(Object)} is called.
+ * </li>
+ * </ul>
+ *
+ * @param settings Mock creation settings like type to mock, extra interfaces and so on.
+ * @param handler See {@link org.mockito.invocation.MockHandler}.
+ * <b>Do not</b> provide your own implementation at this time. Make sure your implementation of
+ * {@link #getHandler(Object)} will return this instance.
+ * @param <T> Type of the mock to return, actually the <code>settings.getTypeToMock</code>.
+ * @return The mock instance.
+ * @since 1.9.5
+ */
+ <T> T createMock(
+ MockCreationSettings<T> settings,
+ MockHandler handler
+ );
+
+ /**
+ * Returns the handler for the {@code mock}. <b>Do not</b> provide your own implementations at this time
+ * because the work on the {@link MockHandler} api is not completed.
+ * Use the instance provided to you by Mockito at {@link #createMock} or {@link #resetMock}.
+ *
+ * @param mock The mock instance.
+ * @return The mock handler, but may return null - it means that there is no handler attached to provided object.
+ * This means the passed object is not really a Mockito mock.
+ * @since 1.9.5
+ */
+ MockHandler getHandler(Object mock);
+
+ /**
+ * Replaces the existing handler on {@code mock} with {@code newHandler}.
+ *
+ * <p>The invocation handler actually store invocations to achieve
+ * stubbing and verification. In order to reset the mock, we pass
+ * a new instance of the invocation handler.</p>
+ *
+ * <p>Your implementation should make sure the {@code newHandler} is correctly associated to passed {@code mock}</p>
+ *
+ * @param mock The mock instance whose invocation handler is to be replaced.
+ * @param newHandler The new invocation handler instance.
+ * @param settings The mock settings - should you need to access some of the mock creation details.
+ * @since 1.9.5
+ */
+ void resetMock(
+ Object mock,
+ MockHandler newHandler,
+ MockCreationSettings settings
+ );
+
+ /**
+ * Indicates if the given type can be mocked by this mockmaker.
+ *
+ * <p>Mockmaker may have different capabilities in term of mocking, typically
+ * Mockito 1.x's internal mockmaker cannot mock final types. Other implementations, may
+ * have different limitations.</p>
+ *
+ * @param type The type inspected for mockability.
+ * @return object that carries the information about mockability of given type.
+ * @since 2.1.0
+ */
+ @Incubating
+ TypeMockability isTypeMockable(Class<?> type);
+
+ /**
+ * Carries the mockability information
+ *
+ * @since 2.1.0
+ */
+ @Incubating
+ interface TypeMockability {
+ /**
+ * informs if type is mockable
+ */
+ boolean mockable();
+
+ /**
+ * informs why type is not mockable
+ */
+ String nonMockableReason();
+ }
+}
diff --git a/mockito-updated/src/org/mockito/plugins/PluginSwitch.java b/mockito-updated/src/org/mockito/plugins/PluginSwitch.java
new file mode 100644
index 0000000..64c584a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/plugins/PluginSwitch.java
@@ -0,0 +1,52 @@
+package org.mockito.plugins;
+
+import org.mockito.Incubating;
+
+/**
+ * Allows switching off the plugins that are discovered on classpath.
+ *
+ * <p>
+ * Mockito will invoke this interface in order to select whether a plugin is enabled or not.
+ * </p>
+ *
+ * <p>
+ * When a particular plugin is switched off, the default Mockito behavior is used.
+ * For example, if Android's dexmaker MockMaker is switched off,
+ * Mockito default MockMaker implementation is used {@link org.mockito.plugins.MockMaker}
+ * </p>
+ *
+ * <h3>Using the extension point</h3>
+ *
+ * <p>
+ * The plugin mechanism of mockito works in a similar way as the {@link java.util.ServiceLoader}, however instead of
+ * looking in the <code>META-INF</code> directory, Mockito will look in <code>mockito-extensions</code> directory.
+ * <em>The reason for that is that Android SDK strips jar from the <code>META-INF</code> directory when creating an APK.</em>
+ * </p>
+ *
+ * <ol style="list-style-type: lower-alpha">
+ * <li>The implementation itself, for example <code>org.awesome.mockito.AwesomeMockMaker</code> that extends the <code>MockMaker</code>.</li>
+ * <li>A file "<code>mockito-extensions/org.mockito.plugins.MockMaker</code>". The content of this file is
+ * exactly a <strong>one</strong> line with the qualified name: <code>org.awesome.mockito.AwesomeMockMaker</code>.</li>
+ * </ol></p>
+ *
+ * <p>Note that if several <code>mockito-extensions/org.mockito.plugins.MockMaker</code> files exists in the classpath
+ * Mockito will only use the first returned by the standard {@link ClassLoader#getResource} mechanism.
+ * <p>
+ * So just create a custom implementation of {@link PluginSwitch} and place the qualified name in the following file
+ * <code>mockito-extensions/org.mockito.plugins.PluginSwitch</code>.
+ * </p>
+ *
+ * @since 1.10.15
+ */
+@Incubating
+public interface PluginSwitch {
+
+ /**
+ * Mockito invokes this method for every plugin found in the classpath
+ * (except from the {@code PluginSwitch} implementation itself).
+ * If no custom plugins are discovered this method is not invoked.
+ *
+ * @since 1.10.15
+ */
+ boolean isEnabled(String pluginClassName);
+}
diff --git a/mockito-updated/src/org/mockito/plugins/StackTraceCleanerProvider.java b/mockito-updated/src/org/mockito/plugins/StackTraceCleanerProvider.java
new file mode 100644
index 0000000..1671795
--- /dev/null
+++ b/mockito-updated/src/org/mockito/plugins/StackTraceCleanerProvider.java
@@ -0,0 +1,24 @@
+package org.mockito.plugins;
+
+import org.mockito.exceptions.stacktrace.StackTraceCleaner;
+
+/**
+ * An extension point to register custom {@link StackTraceCleaner}.
+ * You can replace Mockito's default StackTraceCleaner.
+ * You can also 'enhance' Mockito's default behavior
+ * because the default cleaner is passed as parameter to the method.
+ * <p>
+ * Registering custom StackTraceCleaner is done in similar manner as the {@link MockMaker} implementation.
+ * <p>
+ * See the default implementation: {@link org.mockito.internal.exceptions.stacktrace.DefaultStackTraceCleanerProvider}
+ */
+public interface StackTraceCleanerProvider {
+
+ /**
+ * Allows configuring custom StackTraceCleaner.
+ *
+ * @param defaultCleaner - Mockito's default StackTraceCleaner
+ * @return StackTraceCleaner to use
+ */
+ StackTraceCleaner getStackTraceCleaner(StackTraceCleaner defaultCleaner);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/plugins/package.html b/mockito-updated/src/org/mockito/plugins/package.html
new file mode 100644
index 0000000..323f228
--- /dev/null
+++ b/mockito-updated/src/org/mockito/plugins/package.html
@@ -0,0 +1,38 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+Mockito plugins allow customization of behavior.
+For example, it is useful for Android integration via dexmaker.
+See examples in docs for MockMaker.
+
+<p>
+ The plugin mechanism of mockito works in a similar way as the {@link java.util.ServiceLoader}, however instead of
+ looking in the <code>META-INF</code> directory, Mockito will look in <code>mockito-extensions</code> directory.
+ <em>The reason for that is that Android SDK strips jars from the <code>META-INF</code> directory when creating an APK.</em>
+</p>
+
+<p>
+ For example :
+</p>
+
+<ol style="list-style-type: lower-alpha">
+ <li>
+ Create implementation itself, for example <code>org.awesome.mockito.AwesomeMockMaker</code> that extends
+ the <code>MockMaker</code>.
+ </li>
+ <li>
+ A file "<code>mockito-extensions/org.mockito.plugins.MockMaker</code>". The content of this file is exactly
+ a <strong>one</strong> line with the qualified name: <code>org.awesome.mockito.AwesomeMockMaker</code>.
+ </li>
+</ol>
+
+<p>
+ Note that if several <code>mockito-extensions/org.mockito.plugins.MockMaker</code> files exists in the classpath
+ Mockito will only use the first returned by the standard <code>ClassLoader.getResource</code> mechanism.
+</p>
+
+
+</body>
diff --git a/mockito-updated/src/org/mockito/quality/MockitoHint.java b/mockito-updated/src/org/mockito/quality/MockitoHint.java
new file mode 100644
index 0000000..00afe04
--- /dev/null
+++ b/mockito-updated/src/org/mockito/quality/MockitoHint.java
@@ -0,0 +1,66 @@
+package org.mockito.quality;
+
+/**
+ * Starting with 2.1.0 of Mockito stubbing hints / warnings are printed to standard output.
+ * Hints contain clickable links that take you right to the line of code that contains a possible problem.
+ * Those are hints - they not necessarily indicate real problems 100% of the time.
+ * This way the developer can:
+ * <ol>
+ * <li>produce cleaner tests - by detecting and removing unused stubs</li>
+ * <li>understand why test fails - by detecting stubs that were ineffective due to argument mismatch</li>
+ * </ol>
+ * We would appreciate feedback about this feature so that we can make Mockito better!
+ * Our goal is to provide maximum productivity when testing Java.
+ * Join the discussion in the tracker for <a href="https://github.com/mockito/mockito/issues/384">issue 384</a>.
+ * <p>
+ * How to take advantage of the hints? Use one of the JUnit integrations:
+ * <ul>
+ * <li>{@link org.mockito.junit.MockitoJUnit#rule()}</li>
+ * <li>{@link org.mockito.runners.MockitoJUnitRunner}</li>
+ * </ul>
+ * Currently, the feature is available with JUnit Rule and JUnit Runner only because
+ * they provide necessary hooks (the 'before' and 'after' test events).
+ * <p>
+ * <h3>Cleaner tests without unnecessary stubs</h3>
+ * Unnecessary stubs are stubbed method calls that were never realized during test execution.
+ * To find out more and see the example test code, see {@link org.mockito.exceptions.misusing.UnnecessaryStubbingException}.
+ *
+ * <h3>Better failure diagnostics by detecting mismatched stubs</h3>
+ *
+ * When the test fails for a wrong reason, sometimes it's because stubbed method was called with incorrect argument(s).
+ * In this scenario, the problem is not often obvious.
+ * Hence, Mockito generates a hint to the standard output indicating this scenario.
+ * Hint contains a clickable link to the line of code where the potential problem is.
+ * <p>
+ * Example:
+ *
+ * <p>
+ * Let's say the test fails on assertion.
+ * Let's say the underlying reason is a stubbed method that was called with different arguments:
+ * <pre class="code"><code class="java">
+ * //test:
+ * Dictionary dictionary = new Dictionary(translator);
+ * when(translator.translate("Mockito")).thenReturn("cool framework");
+ * String translated = dictionary.search("Mockito");
+ * assertEquals("cool framework", translated);
+ *
+ * //code:
+ * public String search(String word) {
+ * ...
+ * return translator.translate("oups");
+ *
+ * </code></pre>
+ * On standard output you'll see a hint with clickable links to both locations:
+ * a) stubbing declaration and b) the method call on a stub with mismatched argument.
+ * <p>
+ * Note that it is just a warning, not an assertion.
+ * The test fails on assertion because it is the assertion's duty
+ * to document what the test stands for and what behavior it proves.
+ * Hints just makes it quicker to figure out if the test fails for the right reason.
+ * <p>
+ * Feedback very welcome at <a href="https://github.com/mockito/mockito/issues/384">issue 384</a>.
+ *
+ * @since 2.1.0
+ */
+public interface MockitoHint {
+}
diff --git a/mockito-updated/src/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java b/mockito-updated/src/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java
new file mode 100644
index 0000000..134ed08
--- /dev/null
+++ b/mockito-updated/src/org/mockito/runners/ConsoleSpammingMockitoJUnitRunner.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.runners;
+
+import org.junit.runner.Description;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.Filterable;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+import org.junit.runner.notification.RunNotifier;
+import org.mockito.internal.debugging.WarningsCollector;
+import org.mockito.internal.runners.RunnerFactory;
+import org.mockito.internal.runners.RunnerImpl;
+import org.mockito.internal.util.ConsoleMockitoLogger;
+import org.mockito.internal.util.MockitoLogger;
+
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * @deprecated as of 2.1.0. Use the {@link org.mockito.runners.MockitoJUnitRunner} runner instead
+ * which contains support for detecting unused stubs.
+ * <p>
+ * If you still prefer using this runner, tell us why (create ticket in our issue tracker).
+ */
+@Deprecated
+public class ConsoleSpammingMockitoJUnitRunner extends Runner implements Filterable {
+
+ private final MockitoLogger logger;
+ private final RunnerImpl runner;
+
+ public ConsoleSpammingMockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
+ this(new ConsoleMockitoLogger(), new RunnerFactory().create(klass));
+ }
+
+ ConsoleSpammingMockitoJUnitRunner(MockitoLogger logger, RunnerImpl runnerImpl) {
+ this.runner = runnerImpl;
+ this.logger = logger;
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+ RunListener listener = new RunListener() {
+ WarningsCollector warningsCollector;
+
+ @Override
+ public void testStarted(Description description) throws Exception {
+ warningsCollector = new WarningsCollector();
+ }
+
+ @Override public void testFailure(Failure failure) throws Exception {
+ logger.log(warningsCollector.getWarnings());
+ }
+ };
+
+ notifier.addListener(listener);
+
+ runner.run(notifier);
+ }
+
+ @Override
+ public Description getDescription() {
+ return runner.getDescription();
+ }
+
+ public void filter(Filter filter) throws NoTestsRemainException {
+ //filter is required because without it UnrootedTests show up in Eclipse
+ runner.filter(filter);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/runners/MockitoJUnitRunner.java b/mockito-updated/src/org/mockito/runners/MockitoJUnitRunner.java
new file mode 100644
index 0000000..b746e23
--- /dev/null
+++ b/mockito-updated/src/org/mockito/runners/MockitoJUnitRunner.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.runners;
+
+import org.junit.runner.Description;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.Filterable;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runner.notification.RunNotifier;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.runners.RunnerFactory;
+import org.mockito.internal.runners.RunnerImpl;
+import org.mockito.internal.runners.StrictRunner;
+
+import java.lang.reflect.InvocationTargetException;
+
+
+/**
+ * Compatible with <b>JUnit 4.4 and higher</b>, this runner adds following behavior:
+ * <ul>
+ * <li>
+ * (new since Mockito 2.1.0) Detects unused stubs in the test code.
+ * See {@link org.mockito.exceptions.misusing.UnnecessaryStubbingException}.
+ * To opt-out from this feature, use {@code}@RunWith(MockitoJUnitRunner.Silent.class){@code}
+ * <li>
+ * Initializes mocks annotated with {@link Mock},
+ * so that explicit usage of {@link MockitoAnnotations#initMocks(Object)} is not necessary.
+ * Mocks are initialized before each test method.
+ * <li>
+ * validates framework usage after each test method. See javadoc for {@link Mockito#validateMockitoUsage()}.
+ * </ul>
+ *
+ * Runner is completely optional - there are other ways you can get @Mock working, for example by writing a base class.
+ * Explicitly validating framework usage is also optional because it is triggered automatically by Mockito every time you use the framework.
+ * See javadoc for {@link Mockito#validateMockitoUsage()}.
+ * <p>
+ * Read more about @Mock annotation in javadoc for {@link MockitoAnnotations}
+ * <pre class="code"><code class="java">
+ * <b>@RunWith(MockitoJUnitRunner.class)</b>
+ * public class ExampleTest {
+ *
+ * @Mock
+ * private List list;
+ *
+ * @Test
+ * public void shouldDoSomething() {
+ * list.add(100);
+ * }
+ * }
+ * </code></pre>
+ */
+public class MockitoJUnitRunner extends Runner implements Filterable {
+
+ /**
+ * This Mockito JUnit Runner implementation ignores unused stubs
+ * (e.g. it remains 'silent' even if unused stubs are present).
+ * This was the behavior of Mockito JUnit runner in versions 1.*.
+ * Using this implementation of the runner is not recommended.
+ * Engineers should care for removing unused stubbings because they are dead code,
+ * they add unnecessary details, potentially making the test code harder to comprehend.
+ * If you have good reasons to use the silent runner, let us know at the mailing list
+ * or raise an issue in our issue tracker.
+ *
+ * See also {@link org.mockito.exceptions.misusing.UnnecessaryStubbingException}
+ *
+ * @since 2.1.0
+ */
+ public static class Silent extends MockitoJUnitRunner {
+ public Silent(Class<?> klass) throws InvocationTargetException {
+ super(new RunnerFactory().create(klass));
+ }
+ }
+
+ /**
+ * Detects unused stubs and reports them as failures. Default behavior.
+ * See {@link org.mockito.exceptions.misusing.UnnecessaryStubbingException}
+ *
+ * @since 2.1.0
+ */
+ public static class Strict extends MockitoJUnitRunner {
+ public Strict(Class<?> klass) throws InvocationTargetException {
+ super(new StrictRunner(new RunnerFactory().create(klass), klass));
+ }
+ }
+
+ private final RunnerImpl runner;
+
+ public MockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
+ //by default, StrictRunner is used. We can change that potentially based on feedback from users
+ this(new StrictRunner(new RunnerFactory().create(klass), klass));
+ }
+
+ MockitoJUnitRunner(RunnerImpl runner) throws InvocationTargetException {
+ this.runner = runner;
+ }
+
+ @Override
+ public void run(final RunNotifier notifier) {
+ runner.run(notifier);
+ }
+
+ @Override
+ public Description getDescription() {
+ return runner.getDescription();
+ }
+
+ public void filter(Filter filter) throws NoTestsRemainException {
+ //filter is required because without it UnrootedTests show up in Eclipse
+ runner.filter(filter);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/runners/VerboseMockitoJUnitRunner.java b/mockito-updated/src/org/mockito/runners/VerboseMockitoJUnitRunner.java
new file mode 100644
index 0000000..076884a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/runners/VerboseMockitoJUnitRunner.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.runners;
+
+import org.junit.runner.Description;
+import org.junit.runner.Runner;
+import org.junit.runner.manipulation.Filter;
+import org.junit.runner.manipulation.Filterable;
+import org.junit.runner.manipulation.NoTestsRemainException;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunListener;
+import org.junit.runner.notification.RunNotifier;
+import org.mockito.internal.debugging.WarningsCollector;
+import org.mockito.internal.runners.RunnerFactory;
+import org.mockito.internal.runners.RunnerImpl;
+import org.mockito.internal.util.junit.JUnitFailureHacker;
+
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * @deprecated as of 2.1.0. Use the {@link org.mockito.runners.MockitoJUnitRunner} runner instead
+ * which contains support for detecting unused stubs.
+ * <p>
+ * If you still prefer using this runner, tell us why (create ticket in our issue tracker).
+ */
+@Deprecated
+public class VerboseMockitoJUnitRunner extends Runner implements Filterable {
+
+ private final RunnerImpl runner;
+
+ public VerboseMockitoJUnitRunner(Class<?> klass) throws InvocationTargetException {
+ this(new RunnerFactory().create(klass));
+ }
+
+ VerboseMockitoJUnitRunner(RunnerImpl runnerImpl) {
+ this.runner = runnerImpl;
+ }
+
+ @Override
+ public void run(RunNotifier notifier) {
+
+ //a listener that changes the failure's exception in a very hacky way...
+ RunListener listener = new RunListener() {
+
+ WarningsCollector warningsCollector;
+
+ @Override
+ public void testStarted(Description description) throws Exception {
+ warningsCollector = new WarningsCollector();
+ }
+
+ @Override
+ @SuppressWarnings("deprecation")
+ public void testFailure(final Failure failure) throws Exception {
+ String warnings = warningsCollector.getWarnings();
+ new JUnitFailureHacker().appendWarnings(failure, warnings);
+ }
+ };
+
+ notifier.addFirstListener(listener);
+
+ runner.run(notifier);
+ }
+
+ @Override
+ public Description getDescription() {
+ return runner.getDescription();
+ }
+
+ public void filter(Filter filter) throws NoTestsRemainException {
+ //filter is required because without it UnrootedTests show up in Eclipse
+ runner.filter(filter);
+ }
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/runners/package.html b/mockito-updated/src/org/mockito/runners/package.html
new file mode 100644
index 0000000..2ce69b8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/runners/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+JUnit runners.
+</body>
diff --git a/mockito-updated/src/org/mockito/stubbing/Answer.java b/mockito-updated/src/org/mockito/stubbing/Answer.java
new file mode 100644
index 0000000..71cf0e4
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Answer.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.stubbing;
+
+import org.mockito.invocation.InvocationOnMock;
+
+/**
+ * Generic interface to be used for configuring mock's answer.
+ * 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 custom answer:
+ *
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod(anyString())).thenAnswer(new Answer() {
+ * Object answer(InvocationOnMock invocation) {
+ * Object[] args = invocation.getArguments();
+ * Object mock = invocation.getMock();
+ * return "called with arguments: " + Arrays.toString(args);
+ * }
+ * });
+ *
+ * //Following prints "called with arguments: [foo]"
+ * System.out.println(mock.someMethod("foo"));
+ * </code></pre>
+ *
+ * @param <T> the type to return.
+ */
+public interface Answer<T> {
+ /**
+ * @param invocation the invocation on the mock.
+ *
+ * @return the value to be returned
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ T answer(InvocationOnMock invocation) throws Throwable;
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/stubbing/Answer1.java b/mockito-updated/src/org/mockito/stubbing/Answer1.java
new file mode 100644
index 0000000..dcc3ce9
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Answer1.java
@@ -0,0 +1,38 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * 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 <A0> type of the single argument
+ * @see Answer
+ */
+@Incubating
+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/mockito-updated/src/org/mockito/stubbing/Answer2.java b/mockito-updated/src/org/mockito/stubbing/Answer2.java
new file mode 100644
index 0000000..76ed891
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Answer2.java
@@ -0,0 +1,39 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * 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 <A0> type of the first argument
+ * @param <A1> type of the second argument
+ * @see Answer
+ */
+@Incubating
+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/mockito-updated/src/org/mockito/stubbing/Answer3.java b/mockito-updated/src/org/mockito/stubbing/Answer3.java
new file mode 100644
index 0000000..a495872
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Answer3.java
@@ -0,0 +1,42 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * 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 <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, 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/mockito-updated/src/org/mockito/stubbing/Answer4.java b/mockito-updated/src/org/mockito/stubbing/Answer4.java
new file mode 100644
index 0000000..d33484c
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Answer4.java
@@ -0,0 +1,44 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * 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 <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, 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/mockito-updated/src/org/mockito/stubbing/Answer5.java b/mockito-updated/src/org/mockito/stubbing/Answer5.java
new file mode 100644
index 0000000..6231340
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Answer5.java
@@ -0,0 +1,45 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * 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 <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, 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/mockito-updated/src/org/mockito/stubbing/OngoingStubbing.java b/mockito-updated/src/org/mockito/stubbing/OngoingStubbing.java
new file mode 100644
index 0000000..632e967
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/OngoingStubbing.java
@@ -0,0 +1,238 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.stubbing;
+
+import org.mockito.Mockito;
+
+/**
+ * Simply put: "<b>When</b> the x method is called <b>then</b> return y". E.g:
+ *
+ * <pre class="code"><code class="java">
+ * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);
+ *
+ * //you can use flexible argument matchers, e.g:
+ * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);
+ *
+ * //setting exception to be thrown:
+ * when(mock.someMethod("some arg")).thenThrow(new RuntimeException());
+ *
+ * //you can set different behavior for consecutive method calls.
+ * //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls.
+ * when(mock.someMethod("some arg"))
+ * .thenThrow(new RuntimeException())
+ * .thenReturn("foo");
+ *
+ * //There is a shorter way of consecutive stubbing:
+ * when(mock.someMethod()).thenReturn(1,2,3);
+ * when(mock.otherMethod()).thenThrow(exc1, exc2);
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito#when}
+ */
+public interface OngoingStubbing<T> {
+
+ /**
+ * Sets a return value to be returned when the method is called. E.g:
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod()).thenReturn(10);
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito#when}
+ *
+ * @param value return value
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ */
+ OngoingStubbing<T> thenReturn(T value);
+
+ /**
+ * Sets consecutive return values to be returned when the method is called. E.g:
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod()).thenReturn(1, 2, 3);
+ * </code></pre>
+ *
+ * Last return value in the sequence (in example: 3) determines the behavior of further consecutive calls.
+ * <p>
+ * See examples in javadoc for {@link Mockito#when}
+ *
+ * @param value first return value
+ * @param values next return values
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ */
+ // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation warnings (on call site)
+ @SuppressWarnings ({"unchecked", "varargs"})
+ OngoingStubbing<T> thenReturn(T value, T... values);
+
+ /**
+ * Sets Throwable objects to be thrown when the method is called. E.g:
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod()).thenThrow(new RuntimeException());
+ * </code></pre>
+ *
+ * If throwables contain a checked exception then it has to
+ * match one of the checked exceptions of method signature.
+ * <p>
+ * You can specify throwables to be thrown for consecutive calls.
+ * In that case the last throwable determines the behavior of further consecutive calls.
+ * <p>
+ * If throwable is null then exception will be thrown.
+ * <p>
+ * See examples in javadoc for {@link Mockito#when}
+ *
+ * @param throwables to be thrown on method invocation
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ */
+ OngoingStubbing<T> thenThrow(Throwable... throwables);
+
+ /**
+ * Sets a Throwable type to be thrown when the method is called. E.g:
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod()).thenThrow(RuntimeException.class);
+ * </code></pre>
+ *
+ * <p>
+ * If the throwable class is a checked exception then it has to
+ * match one of the checked exceptions of the stubbed method signature.
+ * <p>
+ * If throwable is null then exception will be thrown.
+ * <p>
+ * See examples in javadoc for {@link Mockito#when}
+ *
+ * <p>Note depending on the JVM, stack trace information may not be available in
+ * the generated throwable instance. If you require stack trace information,
+ * use {@link OngoingStubbing#thenThrow(Throwable...)} instead.
+ *
+ * @param throwableType to be thrown on method invocation
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ * @since 2.1.0
+ */
+ OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType);
+
+ /**
+ * Sets Throwable classes to be thrown when the method is called. E.g:
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod()).thenThrow(RuntimeException.class);
+ * </code></pre>
+ *
+ * <p>
+ * Each throwable class will be instantiated for each method invocation.
+ * <p>
+ * If <code>throwableTypes</code> contain a checked exception then it has to
+ * match one of the checked exceptions of method signature.
+ * <p>
+ * You can specify <code>throwableTypes</code> to be thrown for consecutive calls.
+ * In that case the last throwable determines the behavior of further consecutive calls.
+ * <p>
+ * If throwable is null then exception will be thrown.
+ * <p>
+ * See examples in javadoc for {@link Mockito#when}
+ *
+ * <p>Note since JDK 7, invoking this method will raise a compiler warning "possible heap pollution",
+ * this API is safe to use. If you don't want to see this warning it is possible to chain {@link #thenThrow(Class)}
+ * <p>Note depending on the JVM, stack trace information may not be available in
+ * the generated throwable instance. If you require stack trace information,
+ * use {@link OngoingStubbing#thenThrow(Throwable...)} instead.
+ *
+ * @param toBeThrown to be thrown on method invocation
+ * @param nextToBeThrown next to be thrown on method invocation
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ * @since 2.1.0
+ */
+ // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation warnings (on call site)
+ @SuppressWarnings ({"unchecked", "varargs"})
+ OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown);
+
+ /**
+ * Sets the real implementation to be called when the method is called on a mock object.
+ * <p>
+ * As usual you are going to read <b>the partial mock warning</b>:
+ * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
+ * How does partial mock fit into this paradigm? Well, it just doesn't...
+ * Partial mock usually means that the complexity has been moved to a different method on the same object.
+ * In most cases, this is not the way you want to design your application.
+ * <p>
+ * However, there are rare cases when partial mocks come handy:
+ * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
+ * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
+ * <pre class="code"><code class="java">
+ * // someMethod() must be safe (e.g. doesn't throw, doesn't have dependencies to the object state, etc.)
+ * // if it isn't safe then you will have trouble stubbing it using this api. Use Mockito.doCallRealMethod() instead.
+ * when(mock.someMethod()).thenCallRealMethod();
+ *
+ * // calls real method:
+ * mock.someMethod();
+ *
+ * </code></pre>
+ * See also javadoc {@link Mockito#spy(Object)} to find out more about partial mocks.
+ * <b>Mockito.spy() is a recommended way of creating partial mocks.</b>
+ * The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
+ * <p>
+ * See examples in javadoc for {@link Mockito#when}
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ */
+ OngoingStubbing<T> thenCallRealMethod();
+
+ /**
+ * Sets a generic Answer for the method. E.g:
+ * <pre class="code"><code class="java">
+ * when(mock.someMethod(10)).thenAnswer(new Answer<Integer>() {
+ * public Integer answer(InvocationOnMock invocation) throws Throwable {
+ * return (Integer) invocation.getArguments()[0];
+ * }
+ * }
+ * </code></pre>
+ *
+ * @param answer the custom answer to execute.
+ *
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ */
+ OngoingStubbing<T> thenAnswer(Answer<?> answer);
+
+ /**
+ * Sets a generic Answer for the method.
+ *
+ * This method is an alias of {@link #thenAnswer(Answer)}. This alias allows
+ * more readable tests on occasion, for example:
+ * <pre class="code"><code class="java">
+ * //using 'then' alias:
+ * when(mock.foo()).then(returnCoolValue());
+ *
+ * //versus good old 'thenAnswer:
+ * when(mock.foo()).thenAnswer(byReturningCoolValue());
+ * </code></pre>
+ *
+ * @param answer the custom answer to execute.
+ * @return iOngoingStubbing object that allows stubbing consecutive calls
+ *
+ * @see #thenAnswer(Answer)
+ * @since 1.9.0
+ */
+ OngoingStubbing<T> then(Answer<?> answer);
+
+ /**
+ * Returns the mock that was used for this stub.
+ * <p>
+ * It allows to create a stub in one line of code.
+ * This can be helpful to keep test code clean.
+ * For example, some boring stub can be created & stubbed at field initialization in a test:
+ * <pre class="code"><code class="java">
+ * public class CarTest {
+ * Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
+ *
+ * @Test public void should... {}
+ * </code></pre>
+ *
+ * @param <M> The mock type given by the variable type.
+ * @return Mock used in this ongoing stubbing.
+ * @since 1.9.0
+ */
+ <M> M getMock();
+
+}
diff --git a/mockito-updated/src/org/mockito/stubbing/Stubber.java b/mockito-updated/src/org/mockito/stubbing/Stubber.java
new file mode 100644
index 0000000..e0fd94b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Stubber.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.stubbing;
+
+import org.mockito.Mockito;
+
+/**
+ * Allows to choose a method when stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException()).when(mockedList).clear();
+ *
+ * //following throws RuntimeException:
+ * mockedList.clear();
+ * </code></pre>
+ *
+ * Also useful when stubbing consecutive calls:
+ *
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException("one")).
+ * doThrow(new RuntimeException("two"))
+ * .when(mock).someVoidMethod();
+ * </code></pre>
+ *
+ * Read more about those methods:
+ * <p>
+ * {@link Mockito#doThrow(Throwable[])}
+ * <p>
+ * {@link Mockito#doAnswer(Answer)}
+ * <p>
+ * {@link Mockito#doNothing()}
+ * <p>
+ * {@link Mockito#doReturn(Object)}
+ * <p>
+ *
+ * See examples in javadoc for {@link Mockito}
+ */
+@SuppressWarnings("unchecked")
+public interface Stubber {
+
+ /**
+ * Allows to choose a method when stubbing in doThrow()|doAnswer()|doNothing()|doReturn() style
+ * <p>
+ * Example:
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException())
+ * .when(mockedList).clear();
+ *
+ * //following throws RuntimeException:
+ * mockedList.clear();
+ * </code></pre>
+ *
+ * Read more about those methods:
+ * <p>
+ * {@link Mockito#doThrow(Throwable[])}
+ * <p>
+ * {@link Mockito#doAnswer(Answer)}
+ * <p>
+ * {@link Mockito#doNothing()}
+ * <p>
+ * {@link Mockito#doReturn(Object)}
+ * <p>
+ *
+ * See examples in javadoc for {@link Mockito}
+ *
+ * @param mock The mock
+ * @return select method for stubbing
+ */
+ <T> T when(T mock);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doThrow(Throwable[])} style:
+ * <pre class="code"><code class="java">
+ * doThrow(new RuntimeException("one")).
+ * doThrow(new RuntimeException("two"))
+ * .when(mock).someVoidMethod();
+ * </code></pre>
+ * See javadoc for {@link Mockito#doThrow(Throwable[])}
+ *
+ * @param toBeThrown to be thrown when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ Stubber doThrow(Throwable... toBeThrown);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doThrow(Class)} style:
+ * <pre class="code"><code class="java">
+ * doThrow(RuntimeException.class).
+ * doThrow(IllegalArgumentException.class)
+ * .when(mock).someVoidMethod();
+ * </code></pre>
+ * See javadoc for {@link Mockito#doThrow(Class)}
+ *
+ * @param toBeThrown exception class to be thrown when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ *
+ * @since 2.1.0
+ */
+ Stubber doThrow(Class<? extends Throwable> toBeThrown);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doThrow(Class)} style:
+ * <pre class="code"><code class="java">
+ * doThrow(RuntimeException.class).
+ * doThrow(IllegalArgumentException.class)
+ * .when(mock).someVoidMethod();
+ * </code></pre>
+ * See javadoc for {@link Mockito#doThrow(Class)}
+ *
+ * @param toBeThrown exception class to be thrown when the stubbed method is called
+ * @param nextToBeThrown exception class next to be thrown when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ *
+ * @since 2.1.0
+ */
+ // Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array creation
+ @SuppressWarnings ({"unchecked", "varargs"})
+ Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doAnswer(Answer)} style:
+ * <pre class="code"><code class="java">
+ * doAnswer(answerOne).
+ * doAnswer(answerTwo)
+ * .when(mock).someVoidMethod();
+ * </code></pre>
+ * See javadoc for {@link Mockito#doAnswer(Answer)}
+ *
+ * @param answer to answer when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ Stubber doAnswer(Answer answer);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doNothing()} style:
+ * <pre class="code"><code class="java">
+ * doNothing().
+ * doThrow(new RuntimeException("two"))
+ * .when(mock).someVoidMethod();
+ * </code></pre>
+ * See javadoc for {@link Mockito#doNothing()}
+ *
+ * @return stubber - to select a method for stubbing
+ */
+ Stubber doNothing();
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doReturn(Object)} style.
+ * <p>
+ * See javadoc for {@link Mockito#doReturn(Object)}
+ *
+ * @param toBeReturned to be returned when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ Stubber doReturn(Object toBeReturned);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doReturn(Object)} style.
+ * <p>
+ * See javadoc for {@link Mockito#doReturn(Object, Object...)}
+ *
+ * @param toBeReturned to be returned when the stubbed method is called
+ * @param nextToBeReturned to be returned in consecutive calls when the stubbed method is called
+ * @return stubber - to select a method for stubbing
+ */
+ @SuppressWarnings({"unchecked", "varargs"})
+ Stubber doReturn(Object toBeReturned, Object... nextToBeReturned);
+
+ /**
+ * Use it for stubbing consecutive calls in {@link Mockito#doCallRealMethod()} style.
+ * <p>
+ * See javadoc for {@link Mockito#doCallRealMethod()}
+ *
+ * @return stubber - to select a method for stubbing
+ */
+ Stubber doCallRealMethod();
+}
diff --git a/mockito-updated/src/org/mockito/stubbing/Stubbing.java b/mockito-updated/src/org/mockito/stubbing/Stubbing.java
new file mode 100644
index 0000000..795e8ed
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/Stubbing.java
@@ -0,0 +1,43 @@
+package org.mockito.stubbing;
+
+import org.mockito.MockingDetails;
+import org.mockito.invocation.Invocation;
+
+/**
+ * Stubbing declared on the mock object.
+ * See detailed description including sample code and use cases see javadoc for {@link MockingDetails#getStubbings()}.
+ *
+ * @since 2.2.3
+ */
+public interface Stubbing {
+
+ /**
+ * Returns the method invocation that is stubbed.
+ * E.g. in the example stubbing <code>when(mock.foo()).thenReturn(true)</code>
+ * the invocation is <code>mock.foo()</code>.
+ * <p>
+ * The invocation instance is mutable.
+ * It is not recommended to modify the state of invocation because it will influence mock behavior.
+ * <p>
+ * To understand how this method is useful, see the description at {@link MockingDetails#getStubbings()}.
+ *
+ * @since 2.2.3
+ */
+ Invocation getInvocation();
+
+ /**
+ * Informs if the stubbing was used
+ * <p>
+ * What does it mean 'used stubbing'?
+ * Stubbing like <code>when(mock.foo()).thenReturn(true)</code> is considered used
+ * when the method <code>mock.foo()</code> is actually invoked during the execution of code under test.
+ * <p>
+ * This method is used internally by Mockito to report and detect unused stubbings.
+ * Unused stubbings are dead code and should be deleted to increase clarity of tests (see {@link org.mockito.quality.MockitoHint}.
+ * <p>
+ * To understand how this method is useful, see the description at {@link MockingDetails#getStubbings()}.
+ *
+ * @since 2.2.3
+ */
+ boolean wasUsed();
+}
diff --git a/mockito-updated/src/org/mockito/stubbing/VoidAnswer1.java b/mockito-updated/src/org/mockito/stubbing/VoidAnswer1.java
new file mode 100644
index 0000000..8ec93f3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/VoidAnswer1.java
@@ -0,0 +1,34 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * Generic interface to be used for configuring mock's answer for a single argument invocation that returns nothing.
+ *
+ * Answer specifies an action that is executed when you interact with the mock.
+ * <p>
+ * Example of stubbing a mock with this custom answer:
+ *
+ * <pre class="code"><code class="java">
+ * 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<A0> {
+ /**
+ * @param argument0 the single argument.
+ *
+ * @throws Throwable the throwable to be thrown
+ */
+ void answer(A0 argument0) throws Throwable;
+}
diff --git a/mockito-updated/src/org/mockito/stubbing/VoidAnswer2.java b/mockito-updated/src/org/mockito/stubbing/VoidAnswer2.java
new file mode 100644
index 0000000..55d594a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/VoidAnswer2.java
@@ -0,0 +1,36 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * Generic interface to be used for configuring mock's answer for a two argument invocation that returns nothing.
+ *
+ * Answer specifies an action that is executed when you interact with the mock.
+ * <p>
+ * Example of stubbing a mock with this custom answer:
+ *
+ * <pre class="code"><code class="java">
+ * 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<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/mockito-updated/src/org/mockito/stubbing/VoidAnswer3.java b/mockito-updated/src/org/mockito/stubbing/VoidAnswer3.java
new file mode 100644
index 0000000..2cdd268
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/VoidAnswer3.java
@@ -0,0 +1,38 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * Generic interface to be used for configuring mock's answer for a three argument invocation that returns nothing.
+ *
+ * Answer specifies an action that is executed when you interact with the mock.
+ * <p>
+ * Example of stubbing a mock with this custom answer:
+ *
+ * <pre class="code"><code class="java">
+ * 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<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/mockito-updated/src/org/mockito/stubbing/VoidAnswer4.java b/mockito-updated/src/org/mockito/stubbing/VoidAnswer4.java
new file mode 100644
index 0000000..939a04a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/VoidAnswer4.java
@@ -0,0 +1,41 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * Generic interface to be used for configuring mock's answer for a four argument invocation that returns nothing.
+ *
+ * Answer specifies an action that is executed when you interact with the mock.
+ * <p>
+ * Example of stubbing a mock with this custom answer:
+ *
+ * <pre class="code"><code class="java">
+ * 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<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/mockito-updated/src/org/mockito/stubbing/VoidAnswer5.java b/mockito-updated/src/org/mockito/stubbing/VoidAnswer5.java
new file mode 100644
index 0000000..a92ab9b
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/VoidAnswer5.java
@@ -0,0 +1,43 @@
+package org.mockito.stubbing;
+
+import org.mockito.Incubating;
+
+/**
+ * Generic interface to be used for configuring mock's answer for a five argument invocation that returns nothing.
+ *
+ * Answer specifies an action that is executed when you interact with the mock.
+ * <p>
+ * Example of stubbing a mock with this custom answer:
+ *
+ * <pre class="code"><code class="java">
+ * 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<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;
+}
diff --git a/mockito-updated/src/org/mockito/stubbing/package.html b/mockito-updated/src/org/mockito/stubbing/package.html
new file mode 100644
index 0000000..55e28cc
--- /dev/null
+++ b/mockito-updated/src/org/mockito/stubbing/package.html
@@ -0,0 +1,8 @@
+<!--
+ ~ Copyright (c) 2007 Mockito contributors
+ ~ This program is made available under the terms of the MIT License.
+ -->
+
+<body>
+External stubbing related classes
+</body>
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/verification/After.java b/mockito-updated/src/org/mockito/verification/After.java
new file mode 100644
index 0000000..089324e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/verification/After.java
@@ -0,0 +1,42 @@
+package org.mockito.verification;
+
+import org.mockito.internal.verification.VerificationModeFactory;
+import org.mockito.internal.verification.VerificationOverTimeImpl;
+import org.mockito.internal.verification.VerificationWrapper;
+
+/**
+ * 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 class After extends VerificationWrapper<VerificationOverTimeImpl> implements VerificationAfterDelay {
+
+ /**
+ * 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(long delayMillis, VerificationMode verificationMode) {
+ this(10, delayMillis, verificationMode);
+ }
+
+ After(long pollingPeriod, long delayMillis, VerificationMode verificationMode) {
+ this(new VerificationOverTimeImpl(pollingPeriod, delayMillis, verificationMode, false));
+ }
+
+ After(VerificationOverTimeImpl verificationOverTime) {
+ super(verificationOverTime);
+ }
+
+ @Override
+ protected VerificationMode copySelfWithNewVerificationMode(VerificationMode verificationMode) {
+ return new After(wrappedVerification.copyWithVerificationMode(verificationMode));
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+}
diff --git a/mockito-updated/src/org/mockito/verification/Timeout.java b/mockito-updated/src/org/mockito/verification/Timeout.java
new file mode 100644
index 0000000..f49765a
--- /dev/null
+++ b/mockito-updated/src/org/mockito/verification/Timeout.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.verification;
+
+import static org.mockito.internal.exceptions.Reporter.atMostAndNeverShouldNotBeUsedWithTimeout;
+
+import org.mockito.internal.util.Timer;
+import org.mockito.internal.verification.VerificationModeFactory;
+import org.mockito.internal.verification.VerificationOverTimeImpl;
+import org.mockito.internal.verification.VerificationWrapper;
+
+/**
+ * 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 class Timeout extends VerificationWrapper<VerificationOverTimeImpl> implements VerificationWithTimeout {
+
+ /**
+ * 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(long millis, VerificationMode delegate) {
+ this(10, millis, delegate);
+ }
+
+ /**
+ * See the javadoc for {@link VerificationWithTimeout}
+ */
+ Timeout(long pollingPeriodMillis, long millis, VerificationMode delegate) {
+ this(new VerificationOverTimeImpl(pollingPeriodMillis, millis, delegate, true));
+ }
+
+ /**
+ * See the javadoc for {@link VerificationWithTimeout}
+ */
+ Timeout(long pollingPeriodMillis, VerificationMode delegate, Timer timer) {
+ this(new VerificationOverTimeImpl(pollingPeriodMillis, delegate, true, timer));
+ }
+
+ Timeout(VerificationOverTimeImpl verificationOverTime) {
+ super(verificationOverTime);
+ }
+
+ @Override
+ protected VerificationMode copySelfWithNewVerificationMode(VerificationMode newVerificationMode) {
+ return new Timeout(wrappedVerification.copyWithVerificationMode(newVerificationMode));
+ }
+
+ public VerificationMode atMost(int maxNumberOfInvocations) {
+ throw atMostAndNeverShouldNotBeUsedWithTimeout();
+ }
+
+ public VerificationMode never() {
+ throw atMostAndNeverShouldNotBeUsedWithTimeout();
+ }
+
+ @Override
+ public VerificationMode description(String description) {
+ return VerificationModeFactory.description(this, description);
+ }
+
+}
diff --git a/mockito-updated/src/org/mockito/verification/VerificationAfterDelay.java b/mockito-updated/src/org/mockito/verification/VerificationAfterDelay.java
new file mode 100644
index 0000000..3353ba3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/verification/VerificationAfterDelay.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.verification;
+
+import org.mockito.Mockito;
+
+
+/**
+ * VerificationAfterDelay is a {@link VerificationMode} that allows combining existing verification modes with an initial delay, e.g.
+ * <pre class="code"><code class="java">
+ * verify(mock, after(100).atMost(5)).foo();
+ *
+ * verify(mock, after(100).never()).bar();
+ *
+ * verify(mock, after(200).atLeastOnce()).baz();
+ * </code></pre>
+ *
+ * This is similar to {@link VerificationWithTimeout timeout()} except the assertion will not terminate until either the condition is
+ * definitively failed, or the full time has elapsed (whereas timeout() will also stop if the conditions is true at any point, as is
+ * typically the case with never() etc initially).
+ *
+ * <p>
+ * See examples in javadoc for {@link Mockito#verify(Object, VerificationMode)}
+ *
+ */
+public interface VerificationAfterDelay extends VerificationMode {
+
+ /**
+ * Verifies that there are exactly N invocations during the given period. This will wait the full period given.
+ */
+ VerificationMode times(int wantedNumberOfInvocations);
+
+ /**
+ * Allows verification that there are no invocations at any point during the given period. This will wait the
+ * full period given, unless an invocation occurs (in which case there will be immediate failure)
+ */
+ VerificationMode never();
+
+ /**
+ * Verifies that there is at least 1 invocation during the given period. This will wait the full period given.
+ */
+ VerificationMode atLeastOnce();
+
+ /**
+ * Verifies that there is are least N invocations during the given period. This will wait the full period given.
+ */
+ VerificationMode atLeast(int minNumberOfInvocations);
+
+ /**
+ * 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)
+ */
+ VerificationMode atMost(int maxNumberOfInvocations);
+
+ /**
+ * Verifies that there the given method is invoked and is the only method invoked. This will wait the full
+ * period given, unless another method is invoked (in which case there will be an immediate failure)
+ */
+ VerificationMode only();
+
+}
diff --git a/mockito-updated/src/org/mockito/verification/VerificationMode.java b/mockito-updated/src/org/mockito/verification/VerificationMode.java
new file mode 100644
index 0000000..5d8f6b3
--- /dev/null
+++ b/mockito-updated/src/org/mockito/verification/VerificationMode.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.verification;
+
+import org.mockito.Mockito;
+import org.mockito.internal.verification.api.VerificationData;
+
+/**
+ * Allows verifying that certain behavior happened at least once / exact number
+ * of times / never. E.g:
+ *
+ * <pre class="code"><code class="java">
+ * verify(mock, times(5)).someMethod("was called five times");
+ *
+ * verify(mock, never()).someMethod("was never called");
+ *
+ * verify(mock, atLeastOnce()).someMethod("was called at least once");
+ *
+ * verify(mock, atLeast(2)).someMethod("was called at least twice");
+ *
+ * verify(mock, atMost(3)).someMethod("was called at most 3 times");
+ *
+ * </code></pre>
+ *
+ * <b>times(1) is the default</b> and can be omitted
+ * <p>
+ * See examples in javadoc for {@link Mockito#verify(Object, VerificationMode)}
+ */
+public interface VerificationMode {
+
+ void verify(VerificationData data);
+
+ /**
+ * Description will be prepended to the assertion error if verification fails.
+ * @param description The custom failure message
+ * @return VerificationMode
+ * @since 2.1.0
+ */
+ VerificationMode description(String description);
+}
\ No newline at end of file
diff --git a/mockito-updated/src/org/mockito/verification/VerificationStrategy.java b/mockito-updated/src/org/mockito/verification/VerificationStrategy.java
new file mode 100644
index 0000000..4a1965e
--- /dev/null
+++ b/mockito-updated/src/org/mockito/verification/VerificationStrategy.java
@@ -0,0 +1,16 @@
+package org.mockito.verification;
+
+/**
+ * Strategy to possibly lazily perform verifications.
+ */
+public interface VerificationStrategy {
+
+ /**
+ * Possibly wrap the given VerificationMode and return a wrapping
+ * VerificationMode instead.
+ *
+ * @param mode The original mode.
+ * @return A wrapping mode that uses the original mode.
+ */
+ VerificationMode maybeVerifyLazily(VerificationMode mode);
+}
diff --git a/mockito-updated/src/org/mockito/verification/VerificationWithTimeout.java b/mockito-updated/src/org/mockito/verification/VerificationWithTimeout.java
new file mode 100644
index 0000000..13490a8
--- /dev/null
+++ b/mockito-updated/src/org/mockito/verification/VerificationWithTimeout.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+
+package org.mockito.verification;
+
+import org.mockito.Mockito;
+
+/**
+ * VerificationWithTimeout is a {@link VerificationMode} that allows combining existing verification modes with 'timeout'. E.g:
+ *
+ * <pre class="code"><code class="java">
+ * verify(mock, timeout(100).times(5)).foo();
+ *
+ * verify(mock, timeout(100).never()).bar();
+ *
+ * verify(mock, timeout(200).atLeastOnce()).baz();
+ * </code></pre>
+ *
+ * This is similar to {@link VerificationAfterDelay after()} except this assertion will immediately pass if it becomes true at any point,
+ * whereas after() will wait the full period. Assertions which are consistently expected to be initially true and potentially become false
+ * are deprecated below, and after() should be used instead.
+ *
+ * <p>
+ * See examples in javadoc for {@link Mockito#verify(Object, VerificationMode)}
+ */
+public interface VerificationWithTimeout extends VerificationMode {
+
+ /**
+ * Allows verifying exact number of invocations within given timeout
+ * <pre class="code"><code class="java">
+ * verify(mock, timeout(100).times(2)).someMethod("some arg");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param wantedNumberOfInvocations wanted number of invocations
+ *
+ * @return verification mode
+ */
+ VerificationMode times(int wantedNumberOfInvocations);
+
+ /**
+ * Allows at-least-once verification within given timeout. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, timeout(100).atLeastOnce()).someMethod("some arg");
+ * </code></pre>
+ * Alias to atLeast(1)
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return verification mode
+ */
+ VerificationMode atLeastOnce();
+
+ /**
+ * Allows at-least-x verification within given timeout. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, timeout(100).atLeast(3)).someMethod("some arg");
+ * </code></pre>
+ *
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @param minNumberOfInvocations minimum number of invocations
+ *
+ * @return verification mode
+ */
+ VerificationMode atLeast(int minNumberOfInvocations);
+
+ /**
+ * Allows checking if given method was the only one invoked. E.g:
+ * <pre class="code"><code class="java">
+ * verify(mock, only()).someMethod();
+ * //above is a shorthand for following 2 lines of code:
+ * verify(mock).someMethod();
+ * verifyNoMoreInteractions(mock);
+ * </code></pre>
+ *
+ * <p>
+ * See also {@link Mockito#verifyNoMoreInteractions(Object...)}
+ * <p>
+ * See examples in javadoc for {@link Mockito} class
+ *
+ * @return verification mode
+ */
+ VerificationMode only();
+}
\ No newline at end of file