Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use @ClassRule in Kotlin

Tags:

junit4

kotlin

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 = ...
like image 735
lujop Avatar asked Mar 05 '16 22:03

lujop


1 Answers

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

like image 124
2 revs Avatar answered Oct 21 '22 22:10

2 revs