Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #2915 Forbid spy on mocked interface #2989

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/java/org/mockito/Mockito.java
Expand Up @@ -10,6 +10,7 @@
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
import org.mockito.internal.session.DefaultMockitoSessionBuilder;
import org.mockito.internal.util.MockUtil;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationFactory;
Expand Down Expand Up @@ -2167,6 +2168,10 @@ public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {
* @return a spy of the real object
*/
public static <T> T spy(T object) {
if (MockUtil.isMock(object)) {
throw new IllegalArgumentException(
"Please don't pass mock here. Spy is not allowed on mock.");
}
return MOCKITO_CORE.mock(
(Class<T>) object.getClass(),
withSettings().spiedInstance(object).defaultAnswer(CALLS_REAL_METHODS));
Expand Down
Expand Up @@ -409,6 +409,18 @@ public void handles_bridge_methods_correctly() {
assertEquals("value", testBug.getValue(0));
}

@Test
public void forbid_spy_on_mock() {
try {
spy(mock(List.class));
fail();
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageContaining(
"Please don't pass mock here. Spy is not allowed on mock.");
}
}

public abstract class SomeAbstractClass<T> {

protected abstract String getRealValue(T value);
Expand Down