Reputation: 11035
converting java to kotlin, it has a java package level visibility class
class NotificationManager extends Base {
NotificationManager(Context context) {
super(context);
... ...
}
the unit test to assert this constructor is not public
@Test
public void verify_Constructor() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<NotificationManager> constructor = NotificationManager.class.getDeclaredConstructor(Context.class);
constructor.newInstance(application);
assertFalse(Modifier.isPublic(constructor.getModifiers()));
}
after convert kotlin, it is turned into internal visibility
internal class NotificationManager internal constructor(context: Context) : Base(context) {...}
but the test failed at assertFalse(Modifier.isPublic(constructor.getModifiers()));
.
In unit test how to assert a kotlin internal class constructor is not public?
Upvotes: 1
Views: 1062
Reputation: 93834
You can use Kotlin reflection to get the KVisibility of the constructor and check that.
@Test
public void verify_Constructor() {
KClass<?> kClass = JvmClassMappingKt.getKotlinClass(NotificationManager.class);
boolean hasPublicConstructor = kClass.getConstructors().stream()
.map(KFunction::getVisibility)
.filter(Objects::nonNull) // package-private and java-protected are null
.anyMatch(kVisibility -> kVisibility.equals(KVisibility.PUBLIC));
assertFalse(hasPublicConstructor);
}
Upvotes: 1