CodeBlanks Logo Icon CodeBlanks

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.

Practice 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").

Starter code

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

fun assertEquals(expected: Int, actual: Int) {
    if (expected != actual) throw AssertionError("expected $expected but was $actual")
}

// main: get add(2, 3) result, verify with assertEquals expecting 5
// print "all passed"
fun main() {
    // write here
}

Sample solution

Main.kt
fun main() {
    val c = Calculator()
    assertEquals(5, c.add(2, 3))
    println("all passed")
}

Expected output

all passed

Questions and answers

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

1 What does assertEquals(4, calc.add(2, 2)) verify?

  • That add returns 2
  • That add returns 0
  • That add returns 4 Correct answer
  • That add returns 22

Explanation: assertEquals(4, ...) expects the actual value to be 4.

2 Verify equality

Question
____(5, c.add(2, 3))
Answer
assertEquals(5, c.add(2, 3))

Explanation: assertEquals(5, ...) expects the value to be 5.

3 Match the assertion types

Term Meaning
assertEquals(a, b) Equality
assertTrue(cond) Truth
assertNull(x) Nullness
assertFalse(cond) Falsity

All lessons in Intermediate