Just moving from Java to Kotlin. There was a question, 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 go on. I'm testing with JUnit. The annotated methods @BeforeClass and @AfterClass are required to be static, and I see only one way to resolve the gap: push methods inside the companion object , where you can use @JvmStatic , but at the same time, an abstract variable is called in the @BeforeClass method @BeforeClass is defined by each implementation separately. Correspondingly, how can I access a variable from an external class? Or maybe there is another way to solve this problem? 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() } //{...Объявление и инициализация других переменных...} } } 
  • @rjhdby Thank you, of course, but I myself found this, and this does not answer my question at all. - Janislav Kornev
  • In general, the answers converge to "Don't put the BeforeClass on the abstract class. Call it from each subclass." - rjhdby
  • @rjhdby seems so. There is no alternative? For writing the same thing in two dozen test classes is not very convenient. - Janislav Kornev
  • one
    Why abstract template? - rjhdby

1 answer 1

If I understand correctly, you are trying in a static method to refer to a non-static variable / method that is specified in the descendant class. That will not work. The only solution I see is to define the field as static and set the 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" } } }