breezymri
breezymri

Reputation: 4353

kotlin property initializer execution in JUnit tests

I have an abstract base class for testing in Kotlin:

abstract class TestBase(){
  protected var session = configure()

  private fun configure() {
    ...
    return session // a live session object
  }

  @After
  open fun tearDown() {
    ...
    session.close()
  }
}

Then in the derived test class, we have

class MyTest: TestBase() {
  ...
  @Test
  fun testScenario1() {
    ... // uses the live session object
    assertTrue(myCondition_1)
  }

  @Test
  fun testScenario2() {
    ... // uses the live session object
    assertTrue(myCondition_2)
  }
}

When I first saw this code, I thought that this will be problematic since if session is only executed once in the initialization part, it will be closed after the first test is run. And during the 2nd test, since session has been closed, it will throw exception. However, the code runs with no problem. When I traced it, I saw that the initialization block was run for each test. In other words, session was initialized for each test.

My question is why? Is this the behavior behind JUnit that for each test, it will run the whole initializer plus the constructor of the class?

If this is the case, why use the @Before annotation? Can't we just put all the @Before code in the initializer block

Upvotes: 2

Views: 2110

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

Yes, JUnit creates a new instance of the class for each test. @Before method is invoked after the constructor.

Can't we just put all the @Before code in the initializer block

Yes, you can (in the constructor for Java). It's more for symmetry with @After.

Upvotes: 2

Related Questions