Kotlin
Assertions
Learn assertions with assertEquals and assertTrue.
Assertions: assertEquals, assertTrue
Assertions are functions that compare the expected value with the actual value in a test. assertEquals(expected, actual) verifies two values are equal, assertTrue(condition) verifies a condition is true. If the verification fails an exception is thrown and the test fails.
assertEquals(5, c.add(2, 3))
assertTrue(c.add(2, 3) > 0)
Here the first line verifies that add(2, 3) is 5, the second verifies the result is positive. Assertions produce clearer error messages than check; they show the expected and actual values. JUnit's Assertions object provides these functions; the kotlin.test package also offers compatible versions.
Assertion error messages
When an assertion fails JUnit produces a detailed error message. assertEquals includes the expected and actual values in the message; so you understand what went wrong. assertTrue states that the condition was false. To add extra context a third string argument can be given.
assertEquals(5, result, "add(2,3) should be 5")
assertTrue(list.isEmpty(), "list should be empty")
Here each assertion carries a message; it explains what went wrong when the test fails. Good messages let you quickly grasp why a test failed. When many assertions pile up in one test, splitting the test is a good habit.
Exercise Verify a test with assertEquals
Define class Calculator; inside it add fun add(a: Int, b: Int): Int = a + b. Then define a helper fun assertEquals(expected: Int, actual: Int) whose body throws AssertionError when the values are not equal. In main create an instance with val c = Calculator(); verify with assertEquals(5, c.add(2, 3)); print println("all passed").
Show example solution
fun main() {
val c = Calculator()
assertEquals(5, c.add(2, 3))
println("all passed")
}
Test yourself
-
What does assertEquals(4, calc.add(2, 2)) verify?
- That add returns 2
- That add returns 0
- That add returns 4
- That add returns 22
Show answer
That add returns 4 — assertEquals(4, ...) expects the actual value to be 4.
-
Verify equality
____(5, c.add(2, 3))
Show answer
assertEquals(5, c.add(2, 3))
-
Match the assertion types
- assertEquals(a, b)
- Equality
- assertTrue(cond)
- Truth
- assertNull(x)
- Nullness
- assertFalse(cond)
- Falsity
Next lesson: @BeforeEach