问题描述
在JUnit中,您可以使用@ClassRule注释静态字段.如何在Kotlin中做到这一点?
In JUnit you can use @ClassRule to annotate an static field.How can I do this in Kotlin?
我尝试过:
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 = ...
推荐答案
您没有使用伴侣对象正确.您在声明一个名为companion
的对象(类的单个实例),而不是在类内部创建companion object
.因此,不能正确创建静态字段.
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.
这是使用@ClassRule
的正确工作示例,已在Kotlin 1.0.0中进行了测试:
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...")
}
}
这将输出:
这篇关于在Kotlin中使用@ClassRule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!