Revision: a0a7441d4797
Author: szczepiq
Date: Sun Apr 8 12:18:27 2012
Log: Changed ReturnsSmartNulls so that it does not use MockMaker.
Instead i...
http://code.google.com/p/mockito/source/detail?r=a0a7441d4797
Revision: a4da064b927e
Author: szczepiq
Date: Sun Apr 8 12:23:45 2012
Log: A bucket of cold water. The MockitoInvocationHandler interface
does no...
http://code.google.com/p/mockito/source/detail?r=a4da064b927e
Revision: c570a263a6bf
Author: szczepiq
Date: Sun Apr 8 12:27:03 2012
Log: Fixed a problem that reset(null) and reset(nonMock) gave NPE
instead o...
http://code.google.com/p/mockito/source/detail?r=c570a263a6bf
Revision: 59b535dc149e
Author: szczepiq
Date: Mon Apr 9 08:58:36 2012
Log: Unfortunetly meaty checkin but things got out of hand during
Easter......
http://code.google.com/p/mockito/source/detail?r=59b535dc149e
Revision: f1689fe054d4
Author: szczepiq
Date: Mon Apr 9 09:00:26 2012
Log: Renamed MockName into MockNameImpl so that we can expose MockName
inte...
http://code.google.com/p/mockito/source/detail?r=f1689fe054d4
Revision: ca91c5d8343b
Author: szczepiq
Date: Mon Apr 9 09:02:50 2012
Log: Exposed the MockName interface. A fallout after exposing other
parts o...
http://code.google.com/p/mockito/source/detail?r=ca91c5d8343b
Revision: 3152da9ea660
Author: szczepiq
Date: Mon Apr 9 09:05:47 2012
Log: Some rename job in the MockName area. Added javadocs for the
public ty...
http://code.google.com/p/mockito/source/detail?r=3152da9ea660
Revision: 7b3ccb89b10c
Author: szczepiq
Date: Mon Apr 9 09:32:46 2012
Log: Refactored forwardTo() api into a regular answer at the
AdditionalAnsw...
http://code.google.com/p/mockito/source/detail?r=7b3ccb89b10c
==============================================================================
Revision: a0a7441d4797
Author: szczepiq
Date: Sun Apr 8 12:18:27 2012
Log: Changed ReturnsSmartNulls so that it does not use MockMaker.
Instead it uses the regular way of creating mocks. This also enables some
further refactorings in the Invocations area.
http://code.google.com/p/mockito/source/detail?r=a0a7441d4797
Modified:
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
=======================================
---
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
Sun Apr 1 08:38:19 2012
+++
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNulls.java
Sun Apr 8 12:18:27 2012
@@ -10,14 +10,9 @@
import org.mockito.Mockito;
import org.mockito.exceptions.Reporter;
import org.mockito.internal.debugging.LocationImpl;
-import org.mockito.invocation.Invocation;
import org.mockito.invocation.Location;
-import org.mockito.plugins.MockMaker;
-import org.mockito.internal.configuration.ClassPathLoader;
-import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.invocation.InvocationOnMock;
-import org.mockito.invocation.MockitoInvocationHandler;
import org.mockito.stubbing.Answer;
/**
@@ -41,26 +36,6 @@
public class ReturnsSmartNulls implements Answer<Object>, Serializable {
private static final long serialVersionUID = 7618312406617949441L;
- private static MockMaker mockMaker = ClassPathLoader.getMockMaker();
-
- private final class ThrowingInterceptor implements
MockitoInvocationHandler {
- private final InvocationOnMock invocation;
- private final Location location = new LocationImpl();
-
- private ThrowingInterceptor(InvocationOnMock invocation) {
- this.invocation = invocation;
- }
-
- public Object handle(Invocation nullDereference) throws Throwable {
- if (new
ObjectMethodsGuru().isToString(nullDereference.getMethod())) {
- return "SmartNull returned by this unstubbed method call
on a mock:\n" +
- invocation.toString();
- }
-
- new
Reporter().smartNullPointerException(invocation.toString(), location);
- return null;
- }
- }
private final Answer<Object> delegate = new ReturnsMoreEmptyValues();
@@ -71,9 +46,29 @@
}
Class<?> type = invocation.getMethod().getReturnType();
if (!type.isPrimitive() && !Modifier.isFinal(type.getModifiers()))
{
- ThrowingInterceptor handler = new
ThrowingInterceptor(invocation);
- return mockMaker.createMock(type, new Class[0], handler, new
MockSettingsImpl());
+ 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 (new
ObjectMethodsGuru().isToString(currentInvocation.getMethod())) {
+ return "SmartNull returned by this unstubbed method call
on a mock:\n" +
+ unstubbedInvocation.toString();
+ }
+
+ new
Reporter().smartNullPointerException(unstubbedInvocation.toString(),
location);
+ return null;
+ }
+ }
+}
==============================================================================
Revision: a4da064b927e
Author: szczepiq
Date: Sun Apr 8 12:23:45 2012
Log: A bucket of cold water. The MockitoInvocationHandler interface
does not make much sense yet. Internally we cast it anyway to an internal
type. This means that this API is not yet ready to be completely public. No
problem, though, I made the MockitoInvocationHandler a marker interface.
The contract of the MockMaker at the moment is that it should not create
own instances of MockitoInvocationHandler. Instead, it should keep hold on
the instance that is provided by Mockito. Documented this contract in the
MockMaker interface.
Down the road MockHandlerInterface will merge into MockitoInvocationHandler
and the invocation API will be completely open. For now what we have should
do.
http://code.google.com/p/mockito/source/detail?r=a4da064b927e
Modified:
/src/org/mockito/internal/MockHandler.java
/src/org/mockito/internal/MockHandlerInterface.java
/src/org/mockito/internal/creation/CglibMockMaker.java
/src/org/mockito/internal/creation/MethodInterceptorFilter.java
/src/org/mockito/invocation/MockitoInvocationHandler.java
/src/org/mockito/plugins/MockMaker.java
/test/org/mockito/internal/creation/MethodInterceptorFilterTest.java
=======================================
--- /src/org/mockito/internal/MockHandler.java Sun Apr 1 08:38:19 2012
+++ /src/org/mockito/internal/MockHandler.java Sun Apr 8 12:23:45 2012
@@ -26,7 +26,7 @@
* @param <T>
* type of mock object to handle
*/
-public class MockHandler<T> implements MockitoInvocationHandler,
MockHandlerInterface<T> {
+public class MockHandler<T> implements MockHandlerInterface<T> {
private static final long serialVersionUID = -2917871070982574165L;
=======================================
--- /src/org/mockito/internal/MockHandlerInterface.java Tue Oct 25 01:08:20
2011
+++ /src/org/mockito/internal/MockHandlerInterface.java Sun Apr 8 12:23:45
2012
@@ -6,13 +6,16 @@
import java.util.List;
+import org.mockito.Incubating;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.stubbing.InvocationContainer;
+import org.mockito.invocation.Invocation;
+import org.mockito.invocation.MockitoInvocationHandler;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
@SuppressWarnings("unchecked")
-public interface MockHandlerInterface<T> {
+public interface MockHandlerInterface<T> extends MockitoInvocationHandler {
MockSettingsImpl getMockSettings();
@@ -21,4 +24,18 @@
void setAnswersForStubbing(List<Answer> answers);
InvocationContainer getInvocationContainer();
-}
+
+ /**
+ * 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
+ */
+ @Incubating
+ Object handle(Invocation invocation) throws Throwable;
+}
=======================================
--- /src/org/mockito/internal/creation/CglibMockMaker.java Sun Apr 1
08:38:19 2012
+++ /src/org/mockito/internal/creation/CglibMockMaker.java Sun Apr 8
12:23:45 2012
@@ -6,6 +6,8 @@
import org.mockito.cglib.proxy.Callback;
import org.mockito.cglib.proxy.Factory;
+import org.mockito.exceptions.base.MockitoException;
+import org.mockito.internal.MockHandlerInterface;
import org.mockito.plugins.MockMaker;
import org.mockito.invocation.MockitoInvocationHandler;
import org.mockito.internal.creation.jmock.ClassImposterizer;
@@ -18,12 +20,21 @@
public <T> T createMock(Class<T> typeToMock, Class<?>[]
extraInterfaces,
MockitoInvocationHandler handler, MockSettingsInfo settings) {
+ MockHandlerInterface mockitoHandler = cast(handler);
return ClassImposterizer.INSTANCE.imposterise(
- new MethodInterceptorFilter(handler, settings),
typeToMock, extraInterfaces);
- }
-
+ new MethodInterceptorFilter(mockitoHandler, settings),
typeToMock, extraInterfaces);
+ }
+
+ private MockHandlerInterface cast(MockitoInvocationHandler handler) {
+ if (!(handler instanceof MockHandlerInterface)) {
+ throw new MockitoException("At the moment you cannot provide
own implementations of MockitoInvocationHandler." +
+ "\nPlease see the javadocs for the MockMaker
interface.");
+ }
+ return (MockHandlerInterface) handler;
+ }
+
public void resetMock(Object mock, MockitoInvocationHandler
newHandler, MockSettingsInfo settings) {
- ((Factory) mock).setCallback(0, new
MethodInterceptorFilter(newHandler, settings));
+ ((Factory) mock).setCallback(0, new
MethodInterceptorFilter(cast(newHandler), settings));
}
public MockitoInvocationHandler getHandler(Object mock) {
=======================================
--- /src/org/mockito/internal/creation/MethodInterceptorFilter.java Sun
Apr 1 08:38:19 2012
+++ /src/org/mockito/internal/creation/MethodInterceptorFilter.java Sun
Apr 8 12:23:45 2012
@@ -10,6 +10,7 @@
import org.mockito.cglib.proxy.MethodInterceptor;
import org.mockito.cglib.proxy.MethodProxy;
+import org.mockito.internal.MockHandlerInterface;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MockitoInvocationHandler;
import org.mockito.internal.creation.cglib.CGLIBHacker;
@@ -22,12 +23,12 @@
public class MethodInterceptorFilter implements MethodInterceptor,
Serializable {
private static final long serialVersionUID = 6182795666612683784L;
- private final MockitoInvocationHandler handler;
+ private final MockHandlerInterface handler;
CGLIBHacker cglibHacker = new CGLIBHacker();
ObjectMethodsGuru objectMethodsGuru = new ObjectMethodsGuru();
private final MockSettingsInfo mockSettings;
- public MethodInterceptorFilter(MockitoInvocationHandler handler,
MockSettingsInfo mockSettings) {
+ public MethodInterceptorFilter(MockHandlerInterface handler,
MockSettingsInfo mockSettings) {
this.handler = handler;
this.mockSettings = mockSettings;
}
=======================================
--- /src/org/mockito/invocation/MockitoInvocationHandler.java Tue Apr 3
10:25:30 2012
+++ /src/org/mockito/invocation/MockitoInvocationHandler.java Sun Apr 8
12:23:45 2012
@@ -10,27 +10,9 @@
/**
* Mockito handler of an invocation on a mock. This is a core part of the
API, the heart of Mockito.
- * This type might be interesting for developers wishing to extend Mockito.
* See also the {@link org.mockito.plugins.MockMaker}.
* <p>
- * Takes an invocation object and handles it.
- * The Invocation instance should be created by the {@link
org.mockito.plugins.MockMaker}.
- * <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.
+ * This api is work in progress, hence a marker interface.
*/
@Incubating
-public interface MockitoInvocationHandler extends Serializable {
-
- /**
- * Handles the invocation.
- *
- * @param invocation The invocation to handle
- * @return Result
- * @throws Throwable Throwable
- */
- @Incubating
- Object handle(Invocation invocation) throws Throwable;
-
-}
+public interface MockitoInvocationHandler extends Serializable {}
=======================================
--- /src/org/mockito/plugins/MockMaker.java Wed Apr 4 11:09:52 2012
+++ /src/org/mockito/plugins/MockMaker.java Sun Apr 8 12:23:45 2012
@@ -11,14 +11,22 @@
/**
* The facility to create mocks.
*
- * <p>By default, an internal cglib/asm based implementation is used.</p>
+ * <p>By default, an internal cglib/asm/objenesis based implementation is
used.</p>
*
- * <p>It is possible to configure your own mock maker so that dynamic
proxies are created without cglib/asm.
+ * <p>{@code MockMaker} is an extension point that makes it possible to
use custom dynamic proxies
+ * and avoid using the default cglib/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>
*
- * <p>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.</p>
+ * <h3>Implementing custom {@code MockMaker}</h3>
+ *
+ * <ul>
+ * <li>Implement {@link #createMock)}. Do not provide your own
implementation of </li>
+ * <li></li>
+ * <li></li>
+ * </ul>
+ *
+ * <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 classpath
@@ -34,20 +42,29 @@
*
* @see org.mockito.mock.MockSettingsInfo
* @see org.mockito.invocation.MockitoInvocationHandler
- * @see org.mockito.internal.configuration.ClassPathLoader
* @since 1.9.5
*/
@Incubating
public interface MockMaker {
/**
- * Returns a new instance of {@code typeToMock} that implements the
- * interfaces of {@code extraInterfaces}. Invocations to the methods
of the
- * returned instance will be delegated to {@code handler}.
+ * If you want to provide your own implementation of {@code MockMaker}
this method should:
+ * <ul>
+ * <li>Create a proxy object that implements {@code typeToMock}
and potentially also {@code extraInterfaces}.</li>
+ * <li>You may use the information from {@code settings} to
configure your proxy object.</li>
+ * <li>Your proxy object should carry the {@code hander} with it.
For example, if you generate byte code
+ * to create the proxy you could generate an extra field to keep
the {@code hanlder} with the generated object.
+ * Your implementation of {@code MockHandler} is required to
provide this instance of {@code handler} when
+ * {@link #getHandler(Object)} is called.
+ * </li>
+ * </ul>
*
- * @param typeToMock The type to imposterize, could be a
<strong>class</strong> or an <strong>interface</strong>.
- * @param extraInterfaces Interfaces the mock should implements as
well, never <code>null</code>.
- * @param handler Handler of every invocation on the mock.
+ * @param typeToMock The type of the mock, could be a
<strong>class</strong> or an <strong>interface</strong>.
+ * @param extraInterfaces Interfaces the mock should implements as
well,
+ * never <code>null</code>, interfaces only (no
classes).
+ * @param handler See {@link MockitoInvocationHandler}.
+ * <b>Do not</b> provide your own implementation at
this time. Make sure your implementation of
+ * {@link #getHandler(Object)} will return this
instance.
* @param settings Mock creation settings.
* @param <T> Type of the mock to return, actually the
<code>typeToMock</code>.
* @return The mock instance.
@@ -61,11 +78,11 @@
);
/**
- * Returns the handler for the {@code mock}, or null if {@code mock}
was not
- * a mock object created by {@link #createMock(Class, Class[],
MockitoInvocationHandler, MockSettingsInfo)}.
+ * Returns the handler for the {@code mock}. The passed mock object is
guaranteed to be a Mockito mock,
+ * created by the {@link #createMock} method.
*
* @param mock The mock instance.
- * @return The invocation handler if this object is a mock, otherwise
<code>null</code>.
+ * @return should never return null.
* @since 1.9.5
*/
MockitoInvocationHandler getHandler(Object mock);
@@ -77,9 +94,11 @@
* stubbing and verification. In order to reset the mock, we pass
* a new instance of the invocation handler.</p>
*
- * @param mock The mock instance whose invocation handler shall be
replaced.
+ * <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.
+ * @param settings The mock settings - should you need to access some
of the mock creation details.
* @since 1.9.5
*/
void resetMock(
=======================================
--- /test/org/mockito/internal/creation/MethodInterceptorFilterTest.java
Sun Apr 1 08:38:19 2012
+++ /test/org/mockito/internal/creation/MethodInterceptorFilterTest.java
Sun Apr 8 12:23:45 2012
@@ -16,8 +16,8 @@
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.cglib.proxy.MethodProxy;
+import org.mockito.internal.MockHandlerInterface;
import org.mockito.internal.invocation.InvocationImpl;
-import org.mockito.invocation.MockitoInvocationHandler;
import org.mockito.internal.creation.cglib.CGLIBHacker;
import org.mockito.internal.invocation.InvocationBuilder;
import org.mockito.internal.invocation.MockitoMethod;
@@ -27,7 +27,7 @@
public class MethodInterceptorFilterTest extends TestBase {
- MockitoInvocationHandler handler =
Mockito.mock(MockitoInvocationHandler.class);
+ MockHandlerInterface handler =
Mockito.mock(MockHandlerInterface.class);
MethodInterceptorFilter filter = new MethodInterceptorFilter(handler,
(MockSettingsImpl) withSettings());
@Before
==============================================================================
Revision: c570a263a6bf
Author: szczepiq
Date: Sun Apr 8 12:27:03 2012
Log: Fixed a problem that reset(null) and reset(nonMock) gave NPE
instead of a decent exception message.
http://code.google.com/p/mockito/source/detail?r=c570a263a6bf
Modified:
/src/org/mockito/internal/util/MockUtil.java
/test/org/mockitousage/basicapi/ResetTest.java
=======================================
--- /src/org/mockito/internal/util/MockUtil.java Wed Apr 4 08:59:45 2012
+++ /src/org/mockito/internal/util/MockUtil.java Sun Apr 8 12:27:03 2012
@@ -68,8 +68,7 @@
}
public <T> void resetMock(T mock) {
- InvocationNotifierHandler oldHandler
- = (InvocationNotifierHandler) mockMaker.getHandler(mock);
+ InvocationNotifierHandler oldHandler = (InvocationNotifierHandler)
getMockHandler(mock);
MockSettingsImpl settings = oldHandler.getMockSettings();
InvocationNotifierHandler<T> newHandler = new
InvocationNotifierHandler<T>(
new MockHandler<T>(settings), settings);
=======================================
--- /test/org/mockitousage/basicapi/ResetTest.java Tue Oct 25 01:08:20 2011
+++ /test/org/mockitousage/basicapi/ResetTest.java Sun Apr 8 12:27:03 2012
@@ -10,6 +10,7 @@
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.exceptions.misusing.MissingMethodInvocationException;
+import org.mockito.exceptions.misusing.NotAMockException;
import org.mockito.exceptions.misusing.UnfinishedVerificationException;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
@@ -30,6 +31,16 @@
} catch (MissingMethodInvocationException e) {
}
}
+
+ @Test(expected = NotAMockException.class)
+ public void resettingNonMockIsSafe() {
+ reset("");
+ }
+
+ @Test(expected = NotAMockException.class)
+ public void resettingNullIsSafe() {
+ reset(new Object[] {null});
+ }
@Test
public void shouldRemoveAllStubbing() throws Exception {
==============================================================================
Revision: 59b535dc149e
Author: szczepiq
Date: Mon Apr 9 08:58:36 2012
Log: Unfortunetly meaty checkin but things got out of hand during
Easter... Further work on exposing an MockSettingsInfo. Encountered few
obstacles and did some refactorings along the way. Stopped using the class
array in few place in favor of a Collection - MockMaker interface has
changed in due course. Fixed the javadoc a bit. There's still long way to
get the MockSettings cleaned up but I'm getting there. The purpose is to
avoid casting to our internal type (MockSettingsImpl) and use the
information provided by the interface MockSettingsInfo. MockSettingsInfo is
an interface exposed when we created MockMaker API.
http://code.google.com/p/mockito/source/detail?r=59b535dc149e
Deleted:
/test/org/mockito/internal/util/ArrayUtilsTest.java
Modified:
/src/org/mockito/MockSettings.java
/src/org/mockito/internal/InvocationNotifierHandler.java
/src/org/mockito/internal/MockHandler.java
/src/org/mockito/internal/MockHandlerInterface.java
/src/org/mockito/internal/MockitoCore.java
/src/org/mockito/internal/configuration/injection/filter/NameBasedCandidateFilter.java
/src/org/mockito/internal/configuration/injection/scanner/MockScanner.java
/src/org/mockito/internal/creation/CglibMockMaker.java
/src/org/mockito/internal/creation/MockSettingsImpl.java
/src/org/mockito/internal/creation/jmock/ClassImposterizer.java
/src/org/mockito/internal/util/MockCreationValidator.java
/src/org/mockito/internal/util/MockUtil.java
/src/org/mockito/internal/util/collections/ArrayUtils.java
/src/org/mockito/internal/util/collections/Sets.java
/src/org/mockito/mock/MockSettingsInfo.java
/src/org/mockito/plugins/MockMaker.java
/test/org/mockito/internal/MockHandlerTest.java
/test/org/mockito/internal/creation/MockSettingsImplTest.java
/test/org/mockito/internal/util/MockCreationValidatorTest.java
/test/org/mockito/internal/util/MockUtilTest.java
=======================================
--- /test/org/mockito/internal/util/ArrayUtilsTest.java Wed Apr 4 08:59:45
2012
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.util;
-
-import org.fest.assertions.Assertions;
-import org.junit.Test;
-import org.mockito.internal.util.collections.ArrayUtils;
-import org.mockitoutil.TestBase;
-
-import java.io.Serializable;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-public class ArrayUtilsTest extends TestBase {
-
- ArrayUtils utils = new ArrayUtils();
-
- @Test
- public void shouldConcatenateItemToAnEmptyArray() throws Exception {
- //when
- Class<?>[] items = utils.concat(new Class[0], List.class);
-
- //then
- Assertions.assertThat(items).containsOnly(List.class);
- }
-
- @Test
- public void shouldConcatenateItemsToFullArray() throws Exception {
- //when
- Class<?>[] items = utils.concat(new Class[] {Serializable.class,
Map.class}, List.class, Set.class);
-
- //then
- Assertions.assertThat(items).containsOnly(Serializable.class,
Map.class, List.class, Set.class);
- }
-}
=======================================
--- /src/org/mockito/MockSettings.java Wed Apr 4 11:09:52 2012
+++ /src/org/mockito/MockSettings.java Mon Apr 9 08:58:36 2012
@@ -249,5 +249,5 @@
*
* @since 1.9.5
*/
- MockSettings forwardTo(Object delegate) ;
-}
+ MockSettings forwardTo(Object delegate);
+}
=======================================
--- /src/org/mockito/internal/InvocationNotifierHandler.java Sun Apr 1
08:38:19 2012
+++ /src/org/mockito/internal/InvocationNotifierHandler.java Mon Apr 9
08:58:36 2012
@@ -5,12 +5,12 @@
package org.mockito.internal;
import org.mockito.exceptions.Reporter;
-import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.listeners.NotifiedMethodInvocationReport;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.invocation.Invocation;
import org.mockito.listeners.InvocationListener;
import org.mockito.invocation.MockitoInvocationHandler;
+import org.mockito.mock.MockSettingsInfo;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
@@ -27,7 +27,7 @@
private List<InvocationListener> invocationListeners;
private MockHandler<T> mockHandler;
- public InvocationNotifierHandler(MockHandler<T> mockHandler,
MockSettingsImpl settings) {
+ public InvocationNotifierHandler(MockHandler<T> mockHandler,
MockSettingsInfo settings) {
this.mockHandler = mockHandler;
this.invocationListeners = settings.getInvocationListeners();
}
@@ -64,7 +64,7 @@
}
}
- public MockSettingsImpl getMockSettings() {
+ public MockSettingsInfo getMockSettings() {
return mockHandler.getMockSettings();
}
=======================================
--- /src/org/mockito/internal/MockHandler.java Sun Apr 8 12:23:45 2012
+++ /src/org/mockito/internal/MockHandler.java Mon Apr 9 08:58:36 2012
@@ -4,7 +4,6 @@
*/
package org.mockito.internal;
-import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.internal.invocation.MatchersBinder;
import org.mockito.internal.progress.MockingProgress;
@@ -13,7 +12,7 @@
import org.mockito.internal.verification.MockAwareVerificationMode;
import org.mockito.internal.verification.VerificationDataImpl;
import org.mockito.invocation.Invocation;
-import org.mockito.invocation.MockitoInvocationHandler;
+import org.mockito.mock.MockSettingsInfo;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
import org.mockito.verification.VerificationMode;
@@ -34,23 +33,14 @@
MatchersBinder matchersBinder = new MatchersBinder();
MockingProgress mockingProgress = new ThreadSafeMockingProgress();
- private final MockSettingsImpl mockSettings;
-
- public MockHandler(MockSettingsImpl mockSettings) {
+ private final MockSettingsInfo mockSettings;
+
+ public MockHandler(MockSettingsInfo mockSettings) {
this.mockSettings = mockSettings;
this.mockingProgress = new ThreadSafeMockingProgress();
this.matchersBinder = new MatchersBinder();
this.invocationContainerImpl = new
InvocationContainerImpl(mockingProgress);
}
-
- // for tests
- MockHandler() {
- this(new MockSettingsImpl());
- }
-
- public MockHandler(MockHandlerInterface<T> oldMockHandler) {
- this(oldMockHandler.getMockSettings());
- }
public Object handle(Invocation invocation) throws Throwable {
if (invocationContainerImpl.hasAnswersForStubbing()) {
@@ -115,7 +105,7 @@
return new VoidMethodStubbableImpl<T>(mock,
invocationContainerImpl);
}
- public MockSettingsImpl getMockSettings() {
+ public MockSettingsInfo getMockSettings() {
return mockSettings;
}
=======================================
--- /src/org/mockito/internal/MockHandlerInterface.java Sun Apr 8 12:23:45
2012
+++ /src/org/mockito/internal/MockHandlerInterface.java Mon Apr 9 08:58:36
2012
@@ -7,17 +7,17 @@
import java.util.List;
import org.mockito.Incubating;
-import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.stubbing.InvocationContainer;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MockitoInvocationHandler;
+import org.mockito.mock.MockSettingsInfo;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.VoidMethodStubbable;
@SuppressWarnings("unchecked")
public interface MockHandlerInterface<T> extends MockitoInvocationHandler {
- MockSettingsImpl getMockSettings();
+ MockSettingsInfo getMockSettings();
VoidMethodStubbable<T> voidMethodStubbable(T mock);
=======================================
--- /src/org/mockito/internal/MockitoCore.java Sat Mar 31 15:12:10 2012
+++ /src/org/mockito/internal/MockitoCore.java Mon Apr 9 08:58:36 2012
@@ -38,7 +38,7 @@
private final MockingProgress mockingProgress = new
ThreadSafeMockingProgress();
public <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
- T mock = mockUtil.createMock(classToMock, (MockSettingsImpl)
mockSettings);
+ T mock = mockUtil.createMock(classToMock, mockSettings);
mockingProgress.mockingStarted(mock, classToMock, mockSettings);
return mock;
}
=======================================
---
/src/org/mockito/internal/configuration/injection/scanner/MockScanner.java
Sat Mar 10 17:08:10 2012
+++
/src/org/mockito/internal/configuration/injection/scanner/MockScanner.java
Mon Apr 9 08:58:36 2012
@@ -66,7 +66,7 @@
if (isAnnotatedByMockOrSpy(field)) {
return instance;
} else if (isMockOrSpy(instance)) {
- mockUtil.redefineMockNameIfSurrogate(instance,
field.getName());
+ mockUtil.maybeRedefineMockName(instance, field.getName());
return instance;
}
return null;
=======================================
--- /src/org/mockito/internal/creation/CglibMockMaker.java Sun Apr 8
12:23:45 2012
+++ /src/org/mockito/internal/creation/CglibMockMaker.java Mon Apr 9
08:58:36 2012
@@ -13,12 +13,14 @@
import org.mockito.internal.creation.jmock.ClassImposterizer;
import org.mockito.mock.MockSettingsInfo;
+import java.util.Set;
+
/**
* A MockMaker that uses cglib to generate mocks on a JVM.
*/
public final class CglibMockMaker implements MockMaker {
- public <T> T createMock(Class<T> typeToMock, Class<?>[]
extraInterfaces,
+ public <T> T createMock(Class<T> typeToMock, Set<Class>
extraInterfaces,
MockitoInvocationHandler handler, MockSettingsInfo settings) {
MockHandlerInterface mockitoHandler = cast(handler);
return ClassImposterizer.INSTANCE.imposterise(
=======================================
--- /src/org/mockito/internal/creation/MockSettingsImpl.java Sun Apr 1
08:38:19 2012
+++ /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
08:58:36 2012
@@ -13,13 +13,17 @@
import org.mockito.stubbing.Answer;
import java.util.ArrayList;
+import java.util.LinkedHashSet;
import java.util.List;
+import java.util.Set;
+
+import static org.mockito.internal.util.collections.Sets.newSet;
@SuppressWarnings("unchecked")
public class MockSettingsImpl implements MockSettings {
private static final long serialVersionUID = 4475297236197939568L;
- private Class<?>[] extraInterfaces;
+ private Set<Class> extraInterfaces = new LinkedHashSet<Class>();
private String name;
private Object spiedInstance;
private Object delegatedInstance;
@@ -33,19 +37,19 @@
return this;
}
- public MockSettings extraInterfaces(Class<?>... extraInterfaces) {
+ public MockSettings extraInterfaces(Class... extraInterfaces) {
if (extraInterfaces == null || extraInterfaces.length == 0) {
new Reporter().extraInterfacesRequiresAtLeastOneInterface();
}
- for (Class<?> i : extraInterfaces) {
+ for (Class i : extraInterfaces) {
if (i == null) {
new
Reporter().extraInterfacesDoesNotAcceptNullParameters();
} else if (!i.isInterface()) {
new Reporter().extraInterfacesAcceptsOnlyInterfaces(i);
}
}
- this.extraInterfaces = extraInterfaces;
+ this.extraInterfaces = newSet(extraInterfaces);
return this;
}
@@ -53,7 +57,11 @@
return mockName;
}
- public Class<?>[] getExtraInterfaces() {
+ public MockName mockName() {
+ return mockName;
+ }
+
+ public Set<Class> getExtraInterfaces() {
return extraInterfaces;
}
@@ -138,8 +146,8 @@
}
public MockSettings forwardTo(Object delegatedInstance) {
- this.delegatedInstance = delegatedInstance ;
- return defaultAnswer(new ForwardsInvocations(this.delegatedInstance)) ;
+ this.delegatedInstance = delegatedInstance;
+ return defaultAnswer(new ForwardsInvocations(this.delegatedInstance));
}
}
=======================================
--- /src/org/mockito/internal/creation/jmock/ClassImposterizer.java Thu Oct
27 05:49:12 2011
+++ /src/org/mockito/internal/creation/jmock/ClassImposterizer.java Mon
Apr 9 08:58:36 2012
@@ -16,6 +16,7 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.util.Collection;
import java.util.List;
import static org.mockito.internal.util.StringJoiner.join;
@@ -50,6 +51,10 @@
public boolean canImposterise(Class<?> type) {
return !type.isPrimitive()
&& !Modifier.isFinal(type.getModifiers());
}
+
+ public <T> T imposterise(final MethodInterceptor interceptor, Class<T>
mockedType, Collection<Class> ancillaryTypes) {
+ return imposterise(interceptor, mockedType,
ancillaryTypes.toArray(new Class[ancillaryTypes.size()]));
+ }
public <T> T imposterise(final MethodInterceptor interceptor, Class<T>
mockedType, Class<?>... ancillaryTypes) {
try {
=======================================
--- /src/org/mockito/internal/util/MockCreationValidator.java Fri Mar 9
14:58:23 2012
+++ /src/org/mockito/internal/util/MockCreationValidator.java Mon Apr 9
08:58:36 2012
@@ -8,6 +8,8 @@
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.creation.jmock.ClassImposterizer;
+import java.util.Collection;
+
@SuppressWarnings("unchecked")
public class MockCreationValidator {
@@ -21,7 +23,7 @@
}
}
- public void validateExtraInterfaces(Class classToMock, Class ...
extraInterfaces) {
+ public void validateExtraInterfaces(Class classToMock,
Collection<Class> extraInterfaces) {
if (extraInterfaces == null) {
return;
}
=======================================
--- /src/org/mockito/internal/util/MockUtil.java Sun Apr 8 12:27:03 2012
+++ /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 08:58:36 2012
@@ -12,9 +12,12 @@
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.util.collections.ArrayUtils;
import org.mockito.internal.util.reflection.LenientCopyTool;
+import org.mockito.mock.MockSettingsInfo;
import org.mockito.plugins.MockMaker;
import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
@SuppressWarnings("unchecked")
public class MockUtil {
@@ -30,7 +33,8 @@
this(new MockCreationValidator());
}
- public <T> T createMock(Class<T> classToMock, MockSettingsImpl
settings) {
+ public <T> T createMock(Class<T> classToMock, MockSettingsInfo
settingsInfo) {
+ MockSettingsImpl settings = (MockSettingsImpl) settingsInfo;
creationValidator.validateType(classToMock);
creationValidator.validateExtraInterfaces(classToMock,
settings.getExtraInterfaces());
creationValidator.validateMockedType(classToMock,
settings.getSpiedInstance());
@@ -41,7 +45,7 @@
InvocationNotifierHandler<T> mockHandler = new
InvocationNotifierHandler<T>(
new MockHandler<T>(settings), settings);
- Class<?>[] extraInterfaces = prepareAncillaryTypes(settings);
+ Set<Class> extraInterfaces = prepareAncillaryTypes(settings);
T mock = mockMaker.createMock(classToMock, extraInterfaces,
mockHandler, settings);
Object spiedInstance = settings.getSpiedInstance();
@@ -52,24 +56,22 @@
return mock;
}
- private Class<?>[] prepareAncillaryTypes(MockSettingsImpl settings) {
- Class<?>[] interfaces = settings.getExtraInterfaces();
-
- Class<?>[] ancillaryTypes;
- if (settings.isSerializable()) {
- ancillaryTypes = interfaces == null ? new Class<?>[]
{Serializable.class} : new ArrayUtils().concat(interfaces,
Serializable.class);
- } else {
- ancillaryTypes = interfaces == null ? new Class<?>[0] :
interfaces;
+ private Set<Class> prepareAncillaryTypes(MockSettingsImpl settings) {
+ Set<Class> interfaces = settings.getExtraInterfaces();
+
+ Set<Class> ancillaryTypes = new HashSet<Class>(interfaces);
+ if(settings.isSerializable()) {
+ ancillaryTypes.add(Serializable.class);
}
if (settings.getSpiedInstance() != null) {
- ancillaryTypes = new ArrayUtils().concat(ancillaryTypes,
MockitoSpy.class);
+ ancillaryTypes.add(MockitoSpy.class);
}
return ancillaryTypes;
}
public <T> void resetMock(T mock) {
InvocationNotifierHandler oldHandler = (InvocationNotifierHandler)
getMockHandler(mock);
- MockSettingsImpl settings = oldHandler.getMockSettings();
+ MockSettingsInfo settings = oldHandler.getMockSettings();
InvocationNotifierHandler<T> newHandler = new
InvocationNotifierHandler<T>(
new MockHandler<T>(settings), settings);
mockMaker.resetMock(mock, newHandler, settings);
@@ -103,7 +105,7 @@
return getMockHandler(mock).getMockSettings().getMockName();
}
- public void redefineMockNameIfSurrogate(Object mock, String newName) {
+ public void maybeRedefineMockName(Object mock, String newName) {
if (getMockName(mock).isSurrogate()) {
getMockHandler(mock).getMockSettings().redefineMockName(newName);
}
=======================================
--- /src/org/mockito/internal/util/collections/ArrayUtils.java Wed Apr 4
08:59:45 2012
+++ /src/org/mockito/internal/util/collections/ArrayUtils.java Mon Apr 9
08:58:36 2012
@@ -6,16 +6,6 @@
@SuppressWarnings("unchecked")
public class ArrayUtils {
-
- // TODO don't use typed arguments ?
- public Class<?>[] concat(Class<?>[] interfaces, Class<?>... clazz) {
- int interfacesCount = interfaces.length;
- int appendedCount = clazz.length;
- Class[] out = new Class[interfacesCount + appendedCount];
- System.arraycopy(interfaces, 0, out, 0, interfacesCount);
- System.arraycopy(clazz, 0, out, interfacesCount, appendedCount);
- return out;
- }
public <T> boolean isEmpty(T[] array) {
return array == null || array.length == 0;
=======================================
--- /src/org/mockito/internal/util/collections/Sets.java Sat Mar 10
17:08:10 2012
+++ /src/org/mockito/internal/util/collections/Sets.java Mon Apr 9
08:58:36 2012
@@ -1,8 +1,12 @@
package org.mockito.internal.util.collections;
+import java.util.HashSet;
+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);
@@ -15,4 +19,11 @@
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));
+ }
+}
=======================================
--- /src/org/mockito/mock/MockSettingsInfo.java Tue Apr 3 10:25:30 2012
+++ /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 08:58:36 2012
@@ -6,15 +6,46 @@
package org.mockito.mock;
import org.mockito.Incubating;
+import org.mockito.internal.util.MockName;
+import org.mockito.listeners.InvocationListener;
+import org.mockito.stubbing.Answer;
+
+import java.util.List;
+import java.util.Set;
/**
- * Informs about the mock settings
+ * Informs about the mock settings. An immutable view of {@link
org.mockito.MockSettings}.
*/
@Incubating
public interface MockSettingsInfo {
/**
- * if the mock is serializable
+ * if the mock is serializable, see {@link
org.mockito.MockSettings#serializable}.
*/
boolean isSerializable();
-}
+
+ /**
+ * the invocation listeners attached to this mock, see {@link
org.mockito.MockSettings#invocationListeners}.
+ */
+ List<InvocationListener> getInvocationListeners();
+
+ /**
+ * the default answer for this mock, see {@link
org.mockito.MockSettings#defaultAnswer}.
+ */
+ Answer getDefaultAnswer();
+
+ /**
+ * the name of this mock, as printed on verification errors; see
{@link org.mockito.MockSettings#name}.
+ */
+ MockName getMockName();
+
+ void redefineMockName(String newName);
+
+ Set<Class> getExtraInterfaces();
+
+ Object getSpiedInstance();
+
+ //TODO SF - forward needs to be consistently named with delegate
+ //also figure this thing out.
+ Object getDelegatedInstance();
+}
=======================================
--- /src/org/mockito/plugins/MockMaker.java Sun Apr 8 12:23:45 2012
+++ /src/org/mockito/plugins/MockMaker.java Mon Apr 9 08:58:36 2012
@@ -8,6 +8,8 @@
import org.mockito.invocation.MockitoInvocationHandler;
import org.mockito.mock.MockSettingsInfo;
+import java.util.Set;
+
/**
* The facility to create mocks.
*
@@ -72,17 +74,17 @@
*/
<T> T createMock(
Class<T> typeToMock,
- Class<?>[] extraInterfaces,
+ Set<Class> extraInterfaces,
MockitoInvocationHandler handler,
MockSettingsInfo settings
);
/**
- * Returns the handler for the {@code mock}. The passed mock object is
guaranteed to be a Mockito mock,
- * created by the {@link #createMock} method.
+ * Returns the handler for the {@code mock}.
*
* @param mock The mock instance.
- * @return should never return null.
+ * @return 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
*/
MockitoInvocationHandler getHandler(Object mock);
=======================================
--- /test/org/mockito/internal/MockHandlerTest.java Sat Mar 31 15:31:06 2012
+++ /test/org/mockito/internal/MockHandlerTest.java Mon Apr 9 08:58:36 2012
@@ -41,7 +41,7 @@
// given
Invocation invocation = new InvocationBuilder().toInvocation();
@SuppressWarnings("rawtypes")
- MockHandler<?> handler = new MockHandler();
+ MockHandler<?> handler = new MockHandler(new MockSettingsImpl());
handler.mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
handler.matchersBinder = new MatchersBinder() {
public InvocationMatcher bindMatchers(ArgumentMatcherStorage
argumentMatcherStorage, Invocation invocation) {
=======================================
--- /test/org/mockito/internal/creation/MockSettingsImplTest.java Fri Oct
28 07:08:52 2011
+++ /test/org/mockito/internal/creation/MockSettingsImplTest.java Mon Apr
9 08:58:36 2012
@@ -53,8 +53,9 @@
mockSettingsImpl.extraInterfaces(List.class, Set.class);
//then
- assertEquals(List.class, mockSettingsImpl.getExtraInterfaces()[0]);
- assertEquals(Set.class, mockSettingsImpl.getExtraInterfaces()[1]);
+ assertEquals(2, mockSettingsImpl.getExtraInterfaces().size());
+
assertTrue(mockSettingsImpl.getExtraInterfaces().contains(List.class));
+
assertTrue(mockSettingsImpl.getExtraInterfaces().contains(Set.class));
}
@Test
=======================================
--- /test/org/mockito/internal/util/MockCreationValidatorTest.java Tue Oct
25 01:08:20 2011
+++ /test/org/mockito/internal/util/MockCreationValidatorTest.java Mon Apr
9 08:58:36 2012
@@ -5,6 +5,7 @@
package org.mockito.internal.util;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import org.junit.Test;
@@ -12,6 +13,8 @@
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
+import static java.util.Arrays.asList;
+
@SuppressWarnings("unchecked")
public class MockCreationValidatorTest extends TestBase {
@@ -22,7 +25,7 @@
public void shouldNotAllowExtraInterfaceThatIsTheSameAsTheMockedType()
throws Exception {
try {
//when
- validator.validateExtraInterfaces(IMethods.class, new
Class<?>[] {IMethods.class});
+ validator.validateExtraInterfaces(IMethods.class, (Collection)
asList(IMethods.class));
fail();
} catch (MockitoException e) {
//then
=======================================
--- /test/org/mockito/internal/util/MockUtilTest.java Fri Oct 28 07:08:52
2011
+++ /test/org/mockito/internal/util/MockUtilTest.java Mon Apr 9 08:58:36
2012
@@ -17,7 +17,9 @@
import org.mockitoutil.TestBase;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
+import java.util.Set;
@SuppressWarnings("unchecked")
public class MockUtilTest extends TestBase {
@@ -28,7 +30,7 @@
public void validateType(Class classToMock) {
typeValidated = true;
}
- public void validateExtraInterfaces(Class classToMock, Class ...
interfaces) {
+ public void validateExtraInterfaces(Class classToMock,
Collection<Class> interfaces) {
extraInterfacesValidated = true;
}
}
@@ -91,7 +93,7 @@
@Test
public void should_redefine_MockName_if_surrogate() {
List mock = Mockito.mock(List.class);
- mockUtil.redefineMockNameIfSurrogate(mock, "newName");
+ mockUtil.maybeRedefineMockName(mock, "newName");
Assertions.assertThat(mockUtil.getMockName(mock).toString()).isEqualTo("newName");
}
@@ -99,7 +101,7 @@
@Test
public void should_not_redefine_MockName_if_surrogate() {
List mock = Mockito.mock(List.class, "original");
- mockUtil.redefineMockNameIfSurrogate(mock, "newName");
+ mockUtil.maybeRedefineMockName(mock, "newName");
Assertions.assertThat(mockUtil.getMockName(mock).toString()).isEqualTo("original");
}
==============================================================================
Revision: f1689fe054d4
Author: szczepiq
Date: Mon Apr 9 09:00:26 2012
Log: Renamed MockName into MockNameImpl so that we can expose MockName
interface.
http://code.google.com/p/mockito/source/detail?r=f1689fe054d4
Added:
/src/org/mockito/internal/util/MockNameImpl.java
/test/org/mockito/internal/util/MockNameImplTest.java
Deleted:
/src/org/mockito/internal/util/MockName.java
/test/org/mockito/internal/util/MockNameTest.java
Modified:
/src/org/mockito/internal/creation/MockSettingsImpl.java
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
/src/org/mockito/internal/util/MockUtil.java
/src/org/mockito/mock/MockSettingsInfo.java
=======================================
--- /dev/null
+++ /src/org/mockito/internal/util/MockNameImpl.java Mon Apr 9 09:00:26
2012
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2007 Mockito contributors
+ * This program is made available under the terms of the MIT License.
+ */
+package org.mockito.internal.util;
+
+import java.io.Serializable;
+
+public class MockNameImpl implements Serializable {
+
+ private static final long serialVersionUID = 8014974700844306925L;
+ private final String mockName;
+ private boolean surrogate;
+
+ @SuppressWarnings("unchecked")
+ public MockNameImpl(String mockName, Class classToMock) {
+ if (mockName == null) {
+ this.mockName = toInstanceName(classToMock);
+ this.surrogate = 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 isSurrogate() {
+ return surrogate;
+ }
+
+ @Override
+ public String toString() {
+ return mockName;
+ }
+}
=======================================
--- /dev/null
+++ /test/org/mockito/internal/util/MockNameImplTest.java Mon Apr 9
09:00:26 2012
@@ -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.util;
+
+import org.junit.Test;
+import org.mockitoutil.TestBase;
+
+public class MockNameImplTest extends TestBase {
+
+ @Test
+ public void shouldProvideTheNameForClass() throws Exception {
+ //when
+ String name = new MockNameImpl(null, SomeClass.class).toString();
+ //then
+ assertEquals("someClass", name);
+ }
+
+ @Test
+ public void shouldProvideTheNameForAnonymousClass() throws Exception {
+ //given
+ SomeInterface anonymousInstance = new SomeInterface() {};
+ //when
+ String name = new MockNameImpl(null,
anonymousInstance.getClass()).toString();
+ //then
+ assertEquals("someInterface", name);
+ }
+
+ @Test
+ public void shouldProvideTheGivenName() throws Exception {
+ //when
+ String name = new MockNameImpl("The Hulk",
SomeClass.class).toString();
+ //then
+ assertEquals("The Hulk", name);
+ }
+
+ private class SomeClass {}
+ private class SomeInterface {}
+}
=======================================
--- /src/org/mockito/internal/util/MockName.java Fri Oct 28 07:08:52 2011
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.util;
-
-import java.io.Serializable;
-
-public class MockName implements Serializable {
-
- private static final long serialVersionUID = 8014974700844306925L;
- private final String mockName;
- private boolean surrogate;
-
- @SuppressWarnings("unchecked")
- public MockName(String mockName, Class classToMock) {
- if (mockName == null) {
- this.mockName = toInstanceName(classToMock);
- this.surrogate = true;
- } else {
- this.mockName = mockName;
- }
- }
-
- public MockName(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 isSurrogate() {
- return surrogate;
- }
-
- @Override
- public String toString() {
- return mockName;
- }
-}
=======================================
--- /test/org/mockito/internal/util/MockNameTest.java Tue Oct 25 01:08:20
2011
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2007 Mockito contributors
- * This program is made available under the terms of the MIT License.
- */
-package org.mockito.internal.util;
-
-import org.junit.Test;
-import org.mockitoutil.TestBase;
-
-public class MockNameTest extends TestBase {
-
- @Test
- public void shouldProvideTheNameForClass() throws Exception {
- //when
- String name = new MockName(null, SomeClass.class).toString();
- //then
- assertEquals("someClass", name);
- }
-
- @Test
- public void shouldProvideTheNameForAnonymousClass() throws Exception {
- //given
- SomeInterface anonymousInstance = new SomeInterface() {};
- //when
- String name = new MockName(null,
anonymousInstance.getClass()).toString();
- //then
- assertEquals("someInterface", name);
- }
-
- @Test
- public void shouldProvideTheGivenName() throws Exception {
- //when
- String name = new MockName("The Hulk", SomeClass.class).toString();
- //then
- assertEquals("The Hulk", name);
- }
-
- private class SomeClass {}
- private class SomeInterface {}
-}
=======================================
--- /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
08:58:36 2012
+++ /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
09:00:26 2012
@@ -8,7 +8,7 @@
import org.mockito.exceptions.Reporter;
import org.mockito.internal.debugging.VerboseMockInvocationLogger;
import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;
-import org.mockito.internal.util.MockName;
+import org.mockito.internal.util.MockNameImpl;
import org.mockito.listeners.InvocationListener;
import org.mockito.stubbing.Answer;
@@ -28,7 +28,7 @@
private Object spiedInstance;
private Object delegatedInstance;
private Answer<Object> defaultAnswer;
- private MockName mockName;
+ private MockNameImpl mockName;
private boolean serializable;
private List<InvocationListener> invocationListeners = new
ArrayList<InvocationListener>();
@@ -53,11 +53,11 @@
return this;
}
- public MockName getMockName() {
+ public MockNameImpl getMockName() {
return mockName;
}
- public MockName mockName() {
+ public MockNameImpl mockName() {
return mockName;
}
@@ -97,7 +97,7 @@
}
public void initiateMockName(Class classToMock) {
- mockName = new MockName(name, classToMock);
+ mockName = new MockNameImpl(name, classToMock);
}
public MockSettings verboseLogging() {
@@ -142,7 +142,7 @@
}
public void redefineMockName(String newName) {
- mockName = new MockName(newName);
+ mockName = new MockNameImpl(newName);
}
public MockSettings forwardTo(Object delegatedInstance) {
=======================================
---
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Sat Mar 31 15:10:06 2012
+++
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Mon Apr 9 09:00:26 2012
@@ -22,7 +22,7 @@
import java.util.TreeSet;
import org.mockito.internal.creation.ClassNameFinder;
-import org.mockito.internal.util.MockName;
+import org.mockito.internal.util.MockNameImpl;
import org.mockito.internal.util.MockUtil;
import org.mockito.internal.util.ObjectMethodsGuru;
import org.mockito.internal.util.Primitives;
@@ -63,7 +63,7 @@
public Object answer(InvocationOnMock invocation) {
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
- MockName name = new MockUtil().getMockName(mock);
+ MockNameImpl name = new MockUtil().getMockName(mock);
if (name.isSurrogate()) {
return "Mock for " +
ClassNameFinder.classNameForMock(mock) + ", hashCode: " + mock.hashCode();
} else {
=======================================
--- /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 08:58:36 2012
+++ /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:00:26 2012
@@ -10,7 +10,6 @@
import org.mockito.internal.MockHandlerInterface;
import org.mockito.internal.configuration.ClassPathLoader;
import org.mockito.internal.creation.MockSettingsImpl;
-import org.mockito.internal.util.collections.ArrayUtils;
import org.mockito.internal.util.reflection.LenientCopyTool;
import org.mockito.mock.MockSettingsInfo;
import org.mockito.plugins.MockMaker;
@@ -101,7 +100,7 @@
return mockMaker.getHandler(mock) != null;
}
- public MockName getMockName(Object mock) {
+ public MockNameImpl getMockName(Object mock) {
return getMockHandler(mock).getMockSettings().getMockName();
}
=======================================
--- /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 08:58:36 2012
+++ /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 09:00:26 2012
@@ -6,7 +6,7 @@
package org.mockito.mock;
import org.mockito.Incubating;
-import org.mockito.internal.util.MockName;
+import org.mockito.internal.util.MockNameImpl;
import org.mockito.listeners.InvocationListener;
import org.mockito.stubbing.Answer;
@@ -37,7 +37,7 @@
/**
* the name of this mock, as printed on verification errors; see
{@link org.mockito.MockSettings#name}.
*/
- MockName getMockName();
+ MockNameImpl getMockName();
void redefineMockName(String newName);
==============================================================================
Revision: ca91c5d8343b
Author: szczepiq
Date: Mon Apr 9 09:02:50 2012
Log: Exposed the MockName interface. A fallout after exposing other
parts of the API. Now behind a proper interface.
http://code.google.com/p/mockito/source/detail?r=ca91c5d8343b
Added:
/src/org/mockito/mock/MockName.java
Modified:
/src/org/mockito/internal/creation/MockSettingsImpl.java
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
/src/org/mockito/internal/util/MockNameImpl.java
/src/org/mockito/internal/util/MockUtil.java
/src/org/mockito/mock/MockSettingsInfo.java
=======================================
--- /dev/null
+++ /src/org/mockito/mock/MockName.java Mon Apr 9 09:02:50 2012
@@ -0,0 +1,11 @@
+package org.mockito.mock;
+
+/**
+ * by Szczepan Faber, created at: 4/9/12
+ */
+public interface MockName {
+
+ boolean isSurrogate();
+
+ String toString();
+}
=======================================
--- /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
09:00:26 2012
+++ /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
09:02:50 2012
@@ -10,6 +10,7 @@
import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;
import org.mockito.internal.util.MockNameImpl;
import org.mockito.listeners.InvocationListener;
+import org.mockito.mock.MockName;
import org.mockito.stubbing.Answer;
import java.util.ArrayList;
@@ -28,7 +29,7 @@
private Object spiedInstance;
private Object delegatedInstance;
private Answer<Object> defaultAnswer;
- private MockNameImpl mockName;
+ private MockName mockName;
private boolean serializable;
private List<InvocationListener> invocationListeners = new
ArrayList<InvocationListener>();
@@ -53,11 +54,11 @@
return this;
}
- public MockNameImpl getMockName() {
+ public MockName getMockName() {
return mockName;
}
- public MockNameImpl mockName() {
+ public MockName mockName() {
return mockName;
}
=======================================
---
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Mon Apr 9 09:00:26 2012
+++
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Mon Apr 9 09:02:50 2012
@@ -22,11 +22,11 @@
import java.util.TreeSet;
import org.mockito.internal.creation.ClassNameFinder;
-import org.mockito.internal.util.MockNameImpl;
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;
/**
@@ -63,7 +63,7 @@
public Object answer(InvocationOnMock invocation) {
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
- MockNameImpl name = new MockUtil().getMockName(mock);
+ MockName name = new MockUtil().getMockName(mock);
if (name.isSurrogate()) {
return "Mock for " +
ClassNameFinder.classNameForMock(mock) + ", hashCode: " + mock.hashCode();
} else {
=======================================
--- /src/org/mockito/internal/util/MockNameImpl.java Mon Apr 9 09:00:26
2012
+++ /src/org/mockito/internal/util/MockNameImpl.java Mon Apr 9 09:02:50
2012
@@ -4,9 +4,11 @@
*/
package org.mockito.internal.util;
+import org.mockito.mock.MockName;
+
import java.io.Serializable;
-public class MockNameImpl implements Serializable {
+public class MockNameImpl implements MockName, Serializable {
private static final long serialVersionUID = 8014974700844306925L;
private final String mockName;
=======================================
--- /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:00:26 2012
+++ /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:02:50 2012
@@ -11,6 +11,7 @@
import org.mockito.internal.configuration.ClassPathLoader;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.util.reflection.LenientCopyTool;
+import org.mockito.mock.MockName;
import org.mockito.mock.MockSettingsInfo;
import org.mockito.plugins.MockMaker;
@@ -100,7 +101,7 @@
return mockMaker.getHandler(mock) != null;
}
- public MockNameImpl getMockName(Object mock) {
+ public MockName getMockName(Object mock) {
return getMockHandler(mock).getMockSettings().getMockName();
}
=======================================
--- /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 09:00:26 2012
+++ /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 09:02:50 2012
@@ -37,7 +37,7 @@
/**
* the name of this mock, as printed on verification errors; see
{@link org.mockito.MockSettings#name}.
*/
- MockNameImpl getMockName();
+ MockName getMockName();
void redefineMockName(String newName);
==============================================================================
Revision: 3152da9ea660
Author: szczepiq
Date: Mon Apr 9 09:05:47 2012
Log: Some rename job in the MockName area. Added javadocs for the
public type.
http://code.google.com/p/mockito/source/detail?r=3152da9ea660
Modified:
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
/src/org/mockito/internal/util/MockNameImpl.java
/src/org/mockito/internal/util/MockUtil.java
/src/org/mockito/mock/MockName.java
/test/org/mockito/internal/util/MockUtilTest.java
=======================================
---
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Mon Apr 9 09:02:50 2012
+++
/src/org/mockito/internal/stubbing/defaultanswers/ReturnsEmptyValues.java
Mon Apr 9 09:05:47 2012
@@ -64,7 +64,7 @@
if (methodsGuru.isToString(invocation.getMethod())) {
Object mock = invocation.getMock();
MockName name = new MockUtil().getMockName(mock);
- if (name.isSurrogate()) {
+ if (name.isDefault()) {
return "Mock for " +
ClassNameFinder.classNameForMock(mock) + ", hashCode: " + mock.hashCode();
} else {
return name.toString();
=======================================
--- /src/org/mockito/internal/util/MockNameImpl.java Mon Apr 9 09:02:50
2012
+++ /src/org/mockito/internal/util/MockNameImpl.java Mon Apr 9 09:05:47
2012
@@ -12,13 +12,13 @@
private static final long serialVersionUID = 8014974700844306925L;
private final String mockName;
- private boolean surrogate;
+ private boolean defaultName;
@SuppressWarnings("unchecked")
public MockNameImpl(String mockName, Class classToMock) {
if (mockName == null) {
this.mockName = toInstanceName(classToMock);
- this.surrogate = true;
+ this.defaultName = true;
} else {
this.mockName = mockName;
}
@@ -38,8 +38,8 @@
return className.substring(0, 1).toLowerCase() +
className.substring(1);
}
- public boolean isSurrogate() {
- return surrogate;
+ public boolean isDefault() {
+ return defaultName;
}
@Override
=======================================
--- /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:02:50 2012
+++ /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:05:47 2012
@@ -106,7 +106,7 @@
}
public void maybeRedefineMockName(Object mock, String newName) {
- if (getMockName(mock).isSurrogate()) {
+ if (getMockName(mock).isDefault()) {
getMockHandler(mock).getMockSettings().redefineMockName(newName);
}
}
=======================================
--- /src/org/mockito/mock/MockName.java Mon Apr 9 09:02:50 2012
+++ /src/org/mockito/mock/MockName.java Mon Apr 9 09:05:47 2012
@@ -1,11 +1,17 @@
package org.mockito.mock;
/**
- * by Szczepan Faber, created at: 4/9/12
+ * Represents the name of the mock as shown in the verification failure
reports, etc.
*/
public interface MockName {
- boolean isSurrogate();
-
+ /**
+ * the name
+ */
String toString();
-}
+
+ /**
+ * default name means generated by Mockito. non-default means the user
has named the mock at creation.
+ */
+ boolean isDefault();
+}
=======================================
--- /test/org/mockito/internal/util/MockUtilTest.java Mon Apr 9 08:58:36
2012
+++ /test/org/mockito/internal/util/MockUtilTest.java Mon Apr 9 09:05:47
2012
@@ -91,7 +91,7 @@
}
@Test
- public void should_redefine_MockName_if_surrogate() {
+ public void should_redefine_MockName_if_default() {
List mock = Mockito.mock(List.class);
mockUtil.maybeRedefineMockName(mock, "newName");
@@ -99,7 +99,7 @@
}
@Test
- public void should_not_redefine_MockName_if_surrogate() {
+ public void should_not_redefine_MockName_if_default() {
List mock = Mockito.mock(List.class, "original");
mockUtil.maybeRedefineMockName(mock, "newName");
==============================================================================
Revision: 7b3ccb89b10c
Author: szczepiq
Date: Mon Apr 9 09:32:46 2012
Log: Refactored forwardTo() api into a regular answer at the
AdditionalAnswers. Brice - stay happy - I decided to change forwardTo into
delegatesTo() because we've already talked in the javadocs
about 'delegating' in few places. So I wanted to use a consistent language.
We haven't yet released so you can still convince me why should we stop
talking about 'delegate' in favor of 'forward'. Tweaked some javadocs.
http://code.google.com/p/mockito/source/detail?r=7b3ccb89b10c
Modified:
/src/org/mockito/AdditionalAnswers.java
/src/org/mockito/MockSettings.java
/src/org/mockito/Mockito.java
/src/org/mockito/internal/creation/MockSettingsImpl.java
/src/org/mockito/internal/util/MockCreationValidator.java
/src/org/mockito/internal/util/MockUtil.java
/src/org/mockito/mock/MockSettingsInfo.java
/test/org/mockitousage/stubbing/StubbingWithDelegate.java
=======================================
--- /src/org/mockito/AdditionalAnswers.java Sun Apr 8 05:28:08 2012
+++ /src/org/mockito/AdditionalAnswers.java Mon Apr 9 09:32:46 2012
@@ -1,5 +1,6 @@
package org.mockito;
+import org.mockito.internal.stubbing.defaultanswers.ForwardsInvocations;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.answers.ReturnsArgumentAt;
@@ -99,4 +100,49 @@
return (Answer<T>) new ReturnsArgumentAt(position);
}
-}
+ /**
+ * An answer that directly forwards the calls to the delegate.
+ *
+ * Makes sense only 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>
+ * <li>...</li>
+ * </ul>
+ * Sets the real implementation to be called when the method is called
on a mock object.
+ * <p>
+ * <pre class="code"><code class="java">
+ * final class DontMessTheCodeOfThisList implements list { ... }
+ *
+ * DontMessTheCodeOfThisList awesomeList = new
DontMessTheCodeOfThisList();
+ *
+ * List listWithDelegate = mock(List.class,
delegatesTo(awesomeList));
+ * </code></pre>
+ *
+ * <p>
+ * This features suffer 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.
+ * @return the answer
+ *
+ * @since 1.9.5
+ */
+ public static <T> Answer<T> delegatesTo(Object delegate) {
+ return (Answer<T>) new ForwardsInvocations(delegate);
+ }
+}
=======================================
--- /src/org/mockito/MockSettings.java Mon Apr 9 08:58:36 2012
+++ /src/org/mockito/MockSettings.java Mon Apr 9 09:32:46 2012
@@ -197,57 +197,4 @@
* @return settings instance so that you can fluently specify other
settings
*/
MockSettings invocationListeners(InvocationListener... listeners);
-
- /**
- * Specifies the delegated instance on which a mock should forward
calls.
- *
- * Makes sense only 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>
- * <li>...</li>
- * </ul>
- * 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 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">
- * final class DontMessTheCodeOfThisList implements list { ... }
- *
- * DontMessTheCodeOfThisList awesomeList = new
DontMessTheCodeOfThisList();
- *
- * List listWithDelegate = mock(List.class,
withSettings().forwardTo(awesomeList));
- * </code></pre>
- *
- * <p>
- * This features suffer from the same drawback as the spy. The mock
will always call the delegate.
- * This mean that you have to use the doReturn|Throw|Answer|
CallRealMethod stubbing style. Example:
- *
- * <pre class="code"><code class="java">
- * List listWithDelegate = mock(List.class,
withSettings().forwardTo(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.
- * @return settings instance so that you can fluently specify other
settings
- *
- * @since 1.9.5
- */
- MockSettings forwardTo(Object delegate);
-}
+}
=======================================
--- /src/org/mockito/Mockito.java Wed Apr 4 12:13:48 2012
+++ /src/org/mockito/Mockito.java Mon Apr 9 09:32:46 2012
@@ -882,13 +882,13 @@
*
*
*
- * <h3 id="27">27. (**New**) <a class="meaningful_link"
href="#forwarding_call_to_real_instance">Forward calls to real instance</a>
(Since 1.9.5)</h3>
- * <p>Now mockito offer a specific way to forward calls to a concrete
instance. This is different than than a
- * spy because the spy creation syntax discard the to be spied instance.
+ * <h3 id="27">27. (**New**) <a class="meaningful_link"
href="#delegating_call_to_real_instance">Delegate calls to real
instance</a> (Since 1.9.5)</h3>
+ * <p>Now mockito offer a specific way to delegate calls to a concrete
instance. This is different than the
+ * spy because the regular spy contains all the state of the spied
instance. TODO SF - add more information.
*
* <p>Note that this feature only makes sense only for spies or partial
mocks of objects <strong>that are difficult to
* mock or spy</strong> using the usual spy API.
- * Possible use cases :
+ * Possible use cases:
* <ul>
* <li>Final classes but with an interface</li>
* <li>Already custom proxied object</li>
@@ -896,28 +896,29 @@
* <li>...</li>
* </ul>
*
- * Possible example with an object interacting with native objects and spy
that would not work :
+ * Possible example with an object interacting with native objects and spy
that would not work:
* <pre class="code"><code class="java">
* InteractingWithNativeStuff theSpy = spy(interactingWithNativeStuff);
*
* // Some time after the GC collect interactingWithNativeStuff as it
not anymore used,
* // the finalizer is executed, for example to call a C++ destructor.
*
- * // Later on, it's finally the psy to be garbage collected, finalize
method is called again,
+ * // Later on, it's finally the spy to be garbage collected, finalize
method is called again,
* // unfortunately the second interaction with the native objects will
crash the JVM.
* </code></pre>
* Now with the forwarding feature in place :
* <pre class="code"><code class="java">
- * InteractingWithNativeStuff native =
mock(InteractingWithNativeStuff.class,
withSettings().forwardTo(interactingWithNativeStuff));
+ * InteractingWithNativeStuff native =
mock(InteractingWithNativeStuff.class,
AdditionalAnswers.delegateTo(interactingWithNativeStuff));
*
- * // OK, the mock keeps a reference to the interactingWithNativeStuff,
so the finalize method never kick-in.
+ * //TODO SF - I don't quite follow this example... spied instance is
also something we hold in the MockSettings...
+ * // OK, the mock keeps a reference to the interactingWithNativeStuff,
so the finalize method never kicks in.
* </code></pre>
*
* <p>Friendly reminder that final Methods cannot be mocked, so if
<code>finalize</code> is <code>final</code> the
* real code will still be executed.
*
* <p>
- * See more information there {@link MockSettings#forwardTo}.
+ * See more information there {@link
AdditionalAnswers#delegatesTo(Object)}.
*
*
*
=======================================
--- /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
09:02:50 2012
+++ /src/org/mockito/internal/creation/MockSettingsImpl.java Mon Apr 9
09:32:46 2012
@@ -27,7 +27,6 @@
private Set<Class> extraInterfaces = new LinkedHashSet<Class>();
private String name;
private Object spiedInstance;
- private Object delegatedInstance;
private Answer<Object> defaultAnswer;
private MockName mockName;
private boolean serializable;
@@ -69,10 +68,6 @@
public Object getSpiedInstance() {
return spiedInstance;
}
-
- public Object getDelegatedInstance() {
- return this.delegatedInstance ;
- }
public MockSettings name(String name) {
this.name = name;
@@ -145,10 +140,5 @@
public void redefineMockName(String newName) {
mockName = new MockNameImpl(newName);
}
-
- public MockSettings forwardTo(Object delegatedInstance) {
- this.delegatedInstance = delegatedInstance;
- return defaultAnswer(new ForwardsInvocations(this.delegatedInstance));
- }
}
=======================================
--- /src/org/mockito/internal/util/MockCreationValidator.java Mon Apr 9
08:58:36 2012
+++ /src/org/mockito/internal/util/MockCreationValidator.java Mon Apr 9
09:32:46 2012
@@ -52,11 +52,4 @@
new
Reporter().mockedTypeIsInconsistentWithDelegatedInstanceType(classToMock,
delegatedInstance);
}
}
-
- public void validateMutualExclusionForSpyOrDelegate(MockSettingsImpl
settings) {
- if (settings.getDelegatedInstance() != null &&
settings.getSpiedInstance() != null) {
- new Reporter().spyAndDelegateAreMutuallyExclusive() ;
- }
-
- }
-}
+}
=======================================
--- /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:05:47 2012
+++ /src/org/mockito/internal/util/MockUtil.java Mon Apr 9 09:32:46 2012
@@ -38,8 +38,8 @@
creationValidator.validateType(classToMock);
creationValidator.validateExtraInterfaces(classToMock,
settings.getExtraInterfaces());
creationValidator.validateMockedType(classToMock,
settings.getSpiedInstance());
- creationValidator.validateDelegatedInstance(classToMock,
settings.getDelegatedInstance()) ;
-
creationValidator.validateMutualExclusionForSpyOrDelegate(settings) ;
+ //TODO SF - add this validation and also add missing coverage
+// creationValidator.validateDelegatedInstance(classToMock,
settings.getDelegatedInstance()) ;
settings.initiateMockName(classToMock);
=======================================
--- /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 09:02:50 2012
+++ /src/org/mockito/mock/MockSettingsInfo.java Mon Apr 9 09:32:46 2012
@@ -6,7 +6,6 @@
package org.mockito.mock;
import org.mockito.Incubating;
-import org.mockito.internal.util.MockNameImpl;
import org.mockito.listeners.InvocationListener;
import org.mockito.stubbing.Answer;
@@ -44,8 +43,4 @@
Set<Class> getExtraInterfaces();
Object getSpiedInstance();
-
- //TODO SF - forward needs to be consistently named with delegate
- //also figure this thing out.
- Object getDelegatedInstance();
-}
+}
=======================================
--- /test/org/mockitousage/stubbing/StubbingWithDelegate.java Sun Mar 11
15:15:51 2012
+++ /test/org/mockitousage/stubbing/StubbingWithDelegate.java Mon Apr 9
09:32:46 2012
@@ -11,6 +11,7 @@
import static junit.framework.Assert.assertEquals;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;
+import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.withSettings;
@@ -23,7 +24,7 @@
List<String> delegatedList = new ArrayList<String>();
delegatedList.add("un") ;
- List<String> mock = mock(List.class,
withSettings().forwardTo(delegatedList)) ;
+ List<String> mock = mock(List.class, delegatesTo(delegatedList)) ;
mock.add("two") ;
@@ -34,7 +35,7 @@
public void when_stubbed_the_delegate_should_not_be_called() {
List<String> delegatedList = new ArrayList<String>();
delegatedList.add("un") ;
- List<String> mock = mock(List.class,
withSettings().forwardTo(delegatedList)) ;
+ List<String> mock = mock(List.class, delegatesTo(delegatedList)) ;
doReturn(10).when(mock).size();
@@ -48,7 +49,7 @@
public void delegate_should_not_be_called_when_stubbed2() {
List<String> delegatedList = new ArrayList<String>();
delegatedList.add("un") ;
- List<String> mockedList = mock(List.class,
withSettings().forwardTo(delegatedList)) ;
+ List<String> mockedList = mock(List.class, delegatesTo(delegatedList)) ;
doReturn(false).when(mockedList).add(Mockito.anyString()) ;
@@ -60,7 +61,7 @@
@Test
public void
null_wrapper_dont_throw_exception_from_org_mockito_package() throws
Exception {
- IMethods methods = mock(IMethods.class,
withSettings().forwardTo(new MethodsImpl()));
+ IMethods methods = mock(IMethods.class, delegatesTo(new
MethodsImpl()));
try {
byte b = methods.byteObjectReturningMethod(); // real method
returns null