CodeBlanks Logo Icon CodeBlanks

@Test

Learn to write tests with the @Test annotation.

@Test: Test method annotation

The @Test annotation states that a method is a test to be run by JUnit. The annotation is added by writing @Test above the method. JUnit finds methods with @Test and runs each in a separate instance.

import org.junit.jupiter.api.Test

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

The annotation adds metadata to the method; JUnit reads this metadata to recognize the method as a test. If a test method fails (throws an exception) JUnit marks it as failing. Annotations in Kotlin start with @ and are written above a class or method.

The test method body

A test method calls the code under test and verifies the result. Verification is usually done with an assertion: the expected value is compared to the actual value. If they do not match an exception is thrown and the test fails.

@Test
fun adds() {
    val c = Calculator()
    val result = c.add(2, 3)
    check(result == 5) { "expected 5 but got: $result" }
}

Here the check function verifies the condition; if false it throws IllegalStateException. This is Kotlin's built-in verification function; JUnit's assertEquals will be covered in the next lesson. If the test succeeds nothing is thrown and the test passes.

Practice Verify a test with check

Define class Calculator; inside it add fun add(a: Int, b: Int): Int = a + b. In main create an instance with val c = Calculator(); get the result with val result = c.add(2, 3); verify with check(result == 5); then print println("passed").

Starter code

Main.kt
// Calculator class: add(a: Int, b: Int): Int = a + b
// main: get add(2, 3) result, check it equals 5
// print "passed"
fun main() {
    // write here
}

Sample solution

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

fun main() {
    val c = Calculator()
    val result = c.add(2, 3)
    check(result == 5)
    println("passed")
}

Expected output

passed

Questions and answers

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

1 Add the test annotation

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

Explanation: @Test marks the method as a test.

2 Match the @Test concepts

Term Meaning
@Test Test annotation
JUnit Runner
check(cond) Verification
exception Failing test

3 When does a test method count as passing?

  • When it completes quickly
  • When it completes without throwing Correct answer
  • When it produces screen output
  • When it writes to a file

Explanation: A test passes when it completes without throwing an exception.

All lessons in Intermediate