What is the proper way to declare @BeforeClass on a test in Android with Kotlin

  • I have an InstrumentedTest class like this:

    class MyInstrumentedTest {
        private lateinit var myVar:MyType
        fun method(){

    This gives an error because method must be static. If I put the @BeforeClass method inside a companion object and annotate with @JvmStatic, the injected myVar can't be used. Is there a more proper way to use the @BeforeClass using kotlin, in gereral and in this situation?

  • Usage of companion object is the proper way:

    companion object {
      fun setupClass() {
        // your class level setup logic here

    Remember that @BeforeClass is static and is executed before you have test object instance. There's no other way. If you want to have access to the injected variable you should do your logic in @Before method which is executed before each @Test method.

    fun setup() {
      // your setup logic here

Log in to reply

Suggested Topics

  • 4
  • 2
  • 2
  • 2
  • 2