Skip to content

Commit

Permalink
Fixes 2947: correct visibility check to respect nestmates where subcl…
Browse files Browse the repository at this point in the history
…asses can invoke private constructors if they are nested classes.
  • Loading branch information
raphw committed Mar 25, 2023
1 parent 568c829 commit 50457b3
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
Expand Up @@ -4,11 +4,6 @@
*/
package org.mockito.internal.creation.bytebuddy;

import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.isPrivate;
import static net.bytebuddy.matcher.ElementMatchers.isStatic;
import static net.bytebuddy.matcher.ElementMatchers.not;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
Expand Down Expand Up @@ -61,6 +56,11 @@
import org.mockito.internal.util.concurrent.WeakConcurrentMap;
import org.mockito.plugins.MemberAccessor;

import static net.bytebuddy.matcher.ElementMatchers.isAccessibleTo;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.isStatic;
import static net.bytebuddy.matcher.ElementMatchers.not;

public class MockMethodAdvice extends MockMethodDispatcher {

private final WeakConcurrentMap<Object, MockMethodInterceptor> interceptors;
Expand Down Expand Up @@ -398,7 +398,7 @@ public MethodVisitor wrap(
.getSuperClass()
.asErasure()
.getDeclaredMethods()
.filter(isConstructor().and(not(isPrivate())));
.filter(isConstructor().and(isAccessibleTo(instrumentedType)));
int arguments = Integer.MAX_VALUE;
boolean packagePrivate = true;
MethodDescription.InDefinedShape current = null;
Expand Down
Expand Up @@ -80,6 +80,22 @@ public void should_create_mock_from_final_spy() throws Exception {
});
}

@Test
public void should_create_mock_from_accessible_inner_spy() throws Exception {
MockCreationSettings<Outer.Inner> settings = settingsFor(Outer.Inner.class);
Optional<Outer.Inner> proxy =
mockMaker.createSpy(
settings,
new MockHandlerImpl<>(settings),
new Outer.Inner(new Object(), new Object()));
assertThat(proxy)
.hasValueSatisfying(
spy -> {
assertThat(spy.p1).isNotNull();
assertThat(spy.p2).isNotNull();
});
}

@Test
public void should_create_mock_from_non_constructable_class() throws Exception {
MockCreationSettings<NonConstructableClass> settings =
Expand Down Expand Up @@ -646,4 +662,23 @@ void internalThrowException(int test) throws IOException {
}
}
}

static class Outer {

final Object p1;

private Outer(final Object p1) {
this.p1 = p1;
}

private static class Inner extends Outer {

final Object p2;

Inner(final Object p1, final Object p2) {
super(p1);
this.p2 = p2;
}
}
}
}

0 comments on commit 50457b3

Please sign in to comment.