DEV Community

Vijay Hiremath
Vijay Hiremath

Posted on

Kotlin

๐Ÿงช JUnit Test Isolation โ€” One Small Detail That Changed Everything

Today I learned that JUnit creates a brand-new instance of your test class for every "@test" method by default.

"@TestInstance(TestInstance.Lifecycle.PER_METHOD)"

What happens?

  • "test1()" runs โ†’ counter becomes "1"
  • JUnit destroys that object
  • "test2()" gets a fresh instance โ†’ counter starts at "0" again and becomes "2"

This prevents tests from accidentally sharing state and affecting each other.

๐Ÿ“ Bonus Gradle Gotcha:

If your tests are inside "src/main/kotlin", Gradle ignores them and shows:

"Task :test NO-SOURCE"

Move them to:

"src/test/kotlin"

and your tests run correctly. Use:

"./gradlew test -i"

to see "println()" output in the terminal.

Small detail, big debugging lesson. ๐Ÿš€

JUnit #Kotlin #Testing #Gradle #Java #AndroidDev

Top comments (0)