Skip to content

Commit

Permalink
Merge pull request #1536 from li-wjohnson/release/2.x
Browse files Browse the repository at this point in the history
Allow delegating to non-public methods for AdditionalAnswers#delegatesTo

[ci maven-central-release]
  • Loading branch information
mockitoguy committed Nov 20, 2018
2 parents 5a0269c + 2a68497 commit af2036b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
}

Object[] rawArguments = ((Invocation) invocation).getRawArguments();
try {
delegateMethod.setAccessible(true);
} catch (SecurityException ignore) {
// try to invoke anyway
}
return delegateMethod.invoke(delegatedObject, rawArguments);
} catch (NoSuchMethodException e) {
throw delegatedMethodDoesNotExistOnDelegate(mockMethod, invocation.getMock(), delegatedObject);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package org.mockitousage.stubbing;

import org.junit.Test;
import org.mockito.AdditionalAnswers;
import org.mockito.Mockito;
import org.mockito.exceptions.base.MockitoException;
import org.mockitousage.IMethods;
Expand All @@ -14,12 +15,13 @@
import java.util.Collection;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@SuppressWarnings("unchecked")
public class StubbingWithDelegateTest {
Expand Down Expand Up @@ -175,4 +177,25 @@ public String simpleMethod() {
assertThat(e).isEqualTo(failure);
}
}

interface Foo {
int bar();
}

@Test
public void should_call_anonymous_class_method() throws Throwable {
Foo foo = new Foo() {
public int bar() {
return 0;
}
};

Foo mock = mock(Foo.class);
when(mock.bar()).thenAnswer(AdditionalAnswers.delegatesTo(foo));

//when
mock.bar();

//then no exception is thrown
}
}

0 comments on commit af2036b

Please sign in to comment.