testing – Companion object в Kotlin

Question:

Just switching from Java to Kotlin. A question arose, the answer to which, unfortunately, I could not find. There is a certain abstract class with several abstract variables, on which dozens of tests will later fall. I am testing with JUnit. Methods annotated with @BeforeClass and @AfterClass must be static, and I see only one way to resolve whitespace: stuff the methods inside the companion object , where you can use @JvmStatic , but at the same time, an abstract variable set by each implementation is called in the @BeforeClass method. Accordingly, how can you refer to a variable from an outer class? Or maybe there is another way to solve such a problem? The code:

abstract class TemplateConfig {

    abstract val template : String?


    companion object {
        lateinit var h: Handle

        @BeforeClass
        @JvmStatic
        fun setUp() {
            h = dbi.value.open()
            //Здесь используется абстрактная переменная
            //
            //if (template != null) {
            //    h.createStatement(template).execute()
            //}
        }

        @AfterClass
        @JvmStatic
        fun tearDown() {
            h.close()
        }

        //{...Объявление и инициализация других переменных...}
    }
}

Answer:

If I understand correctly, you are trying in a static method to refer to a non-static variable / method that is set in the descendant class. It won't work that way. The only solution I see is to define the field as static and set a value to it when initializing the descendant class.

object Demo {
   protected var value:String
   @BeforeClass
   fun setUp() {
      println(value)
   }
   @AfterClass
   fun destroy() {
   }
}
internal class SubClass:Demo() {
   companion object {
     init {
        Demo.value = "this is value"
     }
   }
}
Scroll to Top