Kotlin
@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.
Exercise 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").
Show example solution
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")
}
Test yourself
-
Add the test annotation
class CalculatorTest {
____
fun adds() { }
}
Show answer
class CalculatorTest {
@Test
fun adds() { }
}
-
Match the @Test concepts
- @Test
- Test annotation
- JUnit
- Runner
- check(cond)
- Verification
- exception
- Failing test
-
When does a test method count as passing?
- When it completes quickly
- When it completes without throwing
- When it produces screen output
- When it writes to a file
Show answer
When it completes without throwing — A test passes when it completes without throwing an exception.
Next lesson: Assertions