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



  • I have an InstrumentedTest class like this:

    @RunWith(AndroidJUnit4::class)
    class MyInstrumentedTest {
        @Inject
        private lateinit var myVar:MyType
    
        @BeforeClass
        fun method(){
            with(myVar){
            ...
    

    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 {
      @BeforeClass
      @JvmStatic
      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.

    @Before
    fun setup() {
      // your setup logic here
    }
    

Log in to reply
 

Suggested Topics

  • 4
  • 2
  • 4
  • 2
  • 2