Skip to content

Commit

Permalink
Correct visibility check to respect nestmates (#2948)
Browse files Browse the repository at this point in the history
For subclasses which can invoke private constructors if they are nested classes

Fixes #2947
  • Loading branch information
raphw committed Mar 25, 2023
1 parent 568c829 commit 5486617
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
*/
package org.mockito.internal.creation.bytebuddy;

import static net.bytebuddy.matcher.ElementMatchers.isAccessibleTo;
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;

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
Original file line number Diff line number Diff line change
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 5486617

Please sign in to comment.