Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 851
Leonardo Goes Avatar asked Oct 29 '25 01:10

Leonardo Goes


1 Answers

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
  }
like image 174
Marcin Bak Avatar answered Oct 30 '25 13:10

Marcin Bak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!