26

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 = ...
2
  • what the difference between first two versions? Commented Mar 6, 2016 at 6:13
  • One uses @JvmStatic and other JvmField. To my understand as I want to reproduce a static field the first is the one to use, but I tried also with the second. Commented Mar 6, 2016 at 14:15

1 Answer 1

33

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

Sign up to request clarification or add additional context in comments.

1 Comment

object companion { ... } is not an object expression but an object declaration as per kotlinlang.org/docs/reference/object-declarations.html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.