You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 class in Kotlin, its primary constructor is implicitly internal—you don't need to explicitly add the internal modifier to the constructor (though doing so is fine for clarity).
  • The @JvmInternal annotation is automatically added by the Kotlin compiler to all internal elements 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 22:17:33