Trying to setup a super simple junit4 test in kotl...
# getting-started
c
Trying to setup a super simple junit4 test in kotlin and after 3 hours of messing with it... im defeated... What's wrong with this code? Why does BeforeClass and Before never print?
Copy code
class Test1 {
    companion object {
        @BeforeClass
        @JvmStatic
        fun setup() {
            println("This runs once before all tests in the class")
        }
    }

    @Before
    fun setUp() {
        println("This runs before each test")
    }

    @Test
    fun testExample1() = runTest {
        println("TEST ONE")
    }
}
Full code with imports
Copy code
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test

class Test1 {
    companion object {
        @BeforeClass
        @JvmStatic
        fun setup() {
            println("This runs once before all tests in the class")
        }
    }

    @Before
    fun setUp() {
        println("This runs before each test")
    }

    @Test
    fun testExample1() = runTest {
        println("TEST ONE")
    }
}
My full build.gradle file (this is a plain ol java project). super simple. no android or anything
Copy code
plugins {
    kotlin("jvm") version "2.0.20"
}

group = "app.rollertoaster"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(kotlin("test"))
    testImplementation("junit:junit:4.13.2")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
}

tasks.test {
    useJUnitPlatform()
}
kotlin {
    jvmToolchain(17)
}
The only output I get is "TEST ONE" The two other prints never happen. I initially caught this because I had a lateinit var that was supposed to be setup in BeforeClass but it never was getting set, so I simplified my problem down to this and I indeed do not see the two other printlns.
y
I think there's some gradle option you need to use junit as your test runner
c
😭
Switched from default of tasks.test { useJUnitPlatform() } to tasks.test { useJUnit() }
and now it works
WUT
y
Oh yeah that's something to do with JUnit 4 vs 5
I think the platform one is 5, and hence you need the right imports
☝️ 1
c
jeez. TIL. thank you though Youssef
e
JUnit Platform (5) can run JUnit4 tests through the vintage engine, but only if you include it
but I'd stick either entirely to JUnit 5 (and
useJUnitPlatform()
) or JUnit 4 (and
useJUnit()
) only, to avoid confusion
c
gotcha. i think maybe intellij project wizard could do a better job explaining that. i created a new test. intellij asked me what i wanted to use and i chose junit4. so to my surprise when this wasn't working. Currently I only stick with junit 4... but that's because jake wharton said that junit5 was bad. /shruggie