Skip to content

Commit 5486617

Browse files
authored
Correct visibility check to respect nestmates (#2948)
For subclasses which can invoke private constructors if they are nested classes Fixes #2947
1 parent 568c829 commit 5486617

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/main/java/org/mockito/internal/creation/bytebuddy/MockMethodAdvice.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
*/
55
package org.mockito.internal.creation.bytebuddy;
66

7+
import static net.bytebuddy.matcher.ElementMatchers.isAccessibleTo;
78
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
8-
import static net.bytebuddy.matcher.ElementMatchers.isPrivate;
99
import static net.bytebuddy.matcher.ElementMatchers.isStatic;
1010
import static net.bytebuddy.matcher.ElementMatchers.not;
1111

@@ -398,7 +398,7 @@ public MethodVisitor wrap(
398398
.getSuperClass()
399399
.asErasure()
400400
.getDeclaredMethods()
401-
.filter(isConstructor().and(not(isPrivate())));
401+
.filter(isConstructor().and(isAccessibleTo(instrumentedType)));
402402
int arguments = Integer.MAX_VALUE;
403403
boolean packagePrivate = true;
404404
MethodDescription.InDefinedShape current = null;

src/test/java/org/mockito/internal/creation/bytebuddy/InlineDelegateByteBuddyMockMakerTest.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,22 @@ public void should_create_mock_from_final_spy() throws Exception {
8080
});
8181
}
8282

83+
@Test
84+
public void should_create_mock_from_accessible_inner_spy() throws Exception {
85+
MockCreationSettings<Outer.Inner> settings = settingsFor(Outer.Inner.class);
86+
Optional<Outer.Inner> proxy =
87+
mockMaker.createSpy(
88+
settings,
89+
new MockHandlerImpl<>(settings),
90+
new Outer.Inner(new Object(), new Object()));
91+
assertThat(proxy)
92+
.hasValueSatisfying(
93+
spy -> {
94+
assertThat(spy.p1).isNotNull();
95+
assertThat(spy.p2).isNotNull();
96+
});
97+
}
98+
8399
@Test
84100
public void should_create_mock_from_non_constructable_class() throws Exception {
85101
MockCreationSettings<NonConstructableClass> settings =
@@ -646,4 +662,23 @@ void internalThrowException(int test) throws IOException {
646662
}
647663
}
648664
}
665+
666+
static class Outer {
667+
668+
final Object p1;
669+
670+
private Outer(final Object p1) {
671+
this.p1 = p1;
672+
}
673+
674+
private static class Inner extends Outer {
675+
676+
final Object p2;
677+
678+
Inner(final Object p1, final Object p2) {
679+
super(p1);
680+
this.p2 = p2;
681+
}
682+
}
683+
}
649684
}

0 commit comments

Comments
 (0)