【问题标题】:kotlin, unit test how to assert a class constructor is not publickotlin,单元测试如何断言类构造函数不公开
【发布时间】:2021-09-27 05:35:54
【问题描述】:

将java转换为kotlin,它有一个java包级别的可见性类

class NotificationManager extends Base {

    NotificationManager(Context context) {
        super(context);
        ... ...
    }

断言此构造函数的单元测试不公开

    @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()));
    }

转换kotlin后变成内部可见性

internal class NotificationManager internal constructor(context: Context) : Base(context) {...}

但测试在 assertFalse(Modifier.isPublic(constructor.getModifiers())); 失败。

在单元测试中如何断言 kotlin 内部类的构造函数不公开?

【问题讨论】:

    标签: unit-testing kotlin constructor


    【解决方案1】:

    您可以使用 Kotlin 反射来获取构造函数的 KVisibility 并进行检查。

    @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);
    }
    

    【讨论】:

    • 得到错误KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime.,并出现testImplementation "org.jetbrains.kotlin:kotlin-reflect:1.5.21"
    • 工作,谢谢!即使没有 testImplementation "org.jetbrains.kotlin:kotlin-reflect:1.5.21" 依赖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多