Use @ClassRule in Kotlin

早过忘川 提交于 2019-12-08 14:35:48

问题


In JUnit you can use @ClassRule to annotate an static field. How can I do this in Kotlin?

I tried:

object companion {
    @ClassRule @JvmStatic
    val managedMongoDb = ...    
}

and 

object companion {
    @ClassRule @JvmField
    val managedMongoDb = ...    
}

but none of the last works because rule isn't executed.

I double checked that exactly same rule works fine without static context:

@Rule @JvmField
val managedMongoDb = ...

回答1:


You are not using companion objects correctly. You are declaring an object (single instance of a class) called companion instead of creating a companion object inside of a class. And therefore the static fields are not created correctly.

class TestClass {
    companion object { ... }
}

Is very different than:

class TestClass { 
    object companion { ... } // this is an object declaration, not a companion object
}

Although both are valid code.

Here is a correct working example of using @ClassRule, tested in Kotlin 1.0.0:

class TestWithRule {
    companion object {
        @ClassRule @JvmField
        val resource: ExternalResource = object : ExternalResource() {
            override fun before() {
                println("ClassRule Before")
            }

            override fun after() {
                println("ClassRule After")
            }
        }
    }

    @Test fun testSomething() {
        println("Testing...")
    }
}

This outputs:

ClassRule Before
Testing...
ClassRule After



来源:https://stackoverflow.com/questions/35820936/use-classrule-in-kotlin

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