CodeBlanks Logo Icon CodeBlanks

JUnit

Learn the JUnit 5 test framework.

JUnit: Test framework

JUnit is the most common test framework for the JVM. Kotlin tests use JUnit 5 (Jupiter). The framework is added in build.gradle.kts with the testImplementation("org.jetbrains.kotlin:kotlin-test") dependency. Test classes go in the src/test/kotlin directory.

class CalculatorTest {
    @Test
    fun adds() {
        // assert
    }
}

Here CalculatorTest is a test class; each test method is marked with @Test. JUnit finds these methods and runs them in turn. A method that completes without throwing counts as a passing test. Tests are run from the IDE or with ./gradlew test.

The test class structure

A test class is a normal Kotlin class; its name usually ends with Test. Inside it each test is written as a method, marked with the @Test annotation. Methods return Unit and take no parameters.

class CalculatorTest {
    @Test
    fun adds() { }

    @Test
    fun subtracts() { }
}

Here there are two test methods. JUnit runs each separately. Ending the class name with Test is a convention, not a rule; it helps separate test code from production code. Test method names usually reflect the behavior being tested.

Practice Define a Calculator class

Define class Calculator; inside it add fun add(a: Int, b: Int): Int = a + b. In main create an instance with val c = Calculator(); print the result with println(c.add(2, 3)). This class will be tested in later lessons.

Starter code

Main.kt
// Define a Calculator class: add(a: Int, b: Int): Int = a + b
// main: create a Calculator instance, println the result of add(2, 3)
fun main() {
    // write here
}

Sample solution

Main.kt
class Calculator {
    fun add(a: Int, b: Int): Int = a + b
}

fun main() {
    val c = Calculator()
    println(c.add(2, 3))
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What kind of framework is JUnit?

  • A test framework Correct answer
  • A build tool
  • A database
  • A UI library

Explanation: JUnit is a test framework for the JVM.

2 Complete the test class name

Question
class Calculator____ {
    @Test
    fun adds() { }
}
Answer
class CalculatorTest {
    @Test
    fun adds() { }
}

Explanation: CalculatorTest follows the test class naming convention.

3 Match the JUnit concepts

Term Meaning
JUnit Test framework
@Test Test method annotation
CalculatorTest Test class
src/test/kotlin Test directory

All lessons in Intermediate