How can I open class only to test class?

限于喜欢 提交于 2020-01-23 09:26:24

问题


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

Assuming there's no package-private in kotlin

private to restrict visibility to the file

internal to restrict visibility to the module

How can I open class only to test class ?

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

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

EDIT

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.

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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/59158369/how-can-i-open-class-only-to-test-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!