Java转Kotlin后,如何在单元测试中断言Kotlin内部类的构造器非公开?
How to Assert That a Kotlin Internal Class Constructor Is Not Public in Unit Tests
First, let's break down why your original Java test fails after porting to Kotlin:
Kotlin's internal visibility gets compiled to public access in JVM bytecode, but the compiler adds a @kotlin.jvm.JvmInternal annotation to enforce module-level visibility rules. That's why Modifier.isPublic(constructor.getModifiers()) returns true, causing your assertFalse assertion to fail.
Solution: Check for the @JvmInternal Annotation
To correctly verify the constructor is Kotlin's internal (i.e., not accessible outside your module), you need to target the annotation that Kotlin uses to mark internal elements. Here's how to adjust your test:
If your test is written in Java:
@Test public void verify_Constructor() throws NoSuchMethodException { Constructor<NotificationManager> constructor = NotificationManager.class.getDeclaredConstructor(Context.class); // Verify the constructor has Kotlin's internal marker annotation boolean isInternalConstructor = constructor.isAnnotationPresent(JvmInternal.class); assertTrue(isInternalConstructor); // Note: Modifier.isPublic will return true here (due to JVM bytecode rules), so we no longer use that assertion }
If your test is written in Kotlin:
@Test fun verify_Constructor() { val constructor = NotificationManager::class.java.getDeclaredConstructor(Context::class.java) val isInternalConstructor = constructor.isAnnotationPresent(JvmInternal::class.java) assert(isInternalConstructor) }
Quick Notes
- When you declare an
internal classin Kotlin, its primary constructor is implicitlyinternal—you don't need to explicitly add theinternalmodifier to the constructor (though doing so is fine for clarity). - The
@JvmInternalannotation is automatically added by the Kotlin compiler to allinternalelements exposed to the JVM. It acts as a signal to tools (IDEs, linters) that the element shouldn't be accessed outside its module.
内容的提问来源于stack exchange,提问作者lannyf
相关产品推荐
相关产品推荐

