我怎样才能只开班考试呢? [英] How can I open class only to test class?

查看:109
本文介绍了我怎样才能只开班考试呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要是Java开发人员,在用Kotlin编写单元测试时想知道结构,

I'm mainly a Java developer and wonder about structure when writing unit test in kotlin,

假设科特林没有 package-private

private限制文件的可见性

private to restrict visibility to the file

internal限制对模块的可见性

我怎样才能只开放班来测试课程?

How can I open class only to test class ?

我必须在kotlin类或开放类中为所有模块(内部)编写测试吗?

Must I write test inside kotlin class or open class to all module (internal)?

kotlin仅用于单元测试的开放方法是什么?

What's the kotlin way to open method for unit test only?

编辑

:

Found similar question/request in kotlin discuss by @bentolor:

我应该如何正确进行单元/白盒测试?我想编写测试代码来测试类内部功能,而除了我的测试类之外,我根本不想将其公开给其他类.

How am I supposed to do unit / whitebox testing properly? I want to write test code which tests class-internal functionality which I do not want to expose to other classes except my test class at all.

受包装保护的可见性是实现此目标的绝佳方法.而Kotlin现在要求我有效地公开这些方法,并在整个项目中乱扔我组件的可见API以便对其进行测试.

The package protected visibility is an excellent way to achieve this. Whereas Kotlin now requires me to make these methods effectively public and litter the visible API of my component all-over the project be able to test them.

在我看来,内部公司或多或少是公开的,因为它的范围要大得多.大多数项目都有…….在Kotlin的意义上大约有1-5个模块".

In my view internal is more or less public as it has a much larger scope. Most projects have sth. around 1 - 5 "modules" in the Kotlin sense.

在此强烈要求/提倡在程序包本地可见性.

Really strongly asking/advocating for package-local visibility here.

推荐答案

在形式上,不可能在JVM上诚实地做到这一点,因为无法为可能的干预者的子集打开类.

Formally it is not possible to do this honestly on JVM, because class couldn't be open for subset of possible interiters.

但是,可以通过以下技巧部分完成它:

However it can be partially done by the following trick:

open class SomeClass internal constructor(val configurableParameter: Int) {
    companion object {
        private const val defaultInput = 123

        fun create() = SomeClass(defaultInput)
    }
}

只能从同一模块(或从测试)调用此类的构造函数.而且班级是公开的,所以任何人都可以使用它.但是,从外部模块中,只有两种构建类的方法:伴随对象或反射.

The constructor of this class can be called only from the same module (or from tests). And class is public, so anyone can use it. However from external modules you have only two ways of the class construction: companion object or reflection.

最后,由于构造函数是内部的,因此您无法在任何其他模块上继承此类.

And finally you couldn't inherit from this class at any other modules, because constructor is internal.

这篇关于我怎样才能只开班考试呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆