Assertion: Cara Check Hasil

Assertion adalah pernyataan “nilai ini harus sama dengan itu”. Jika assertion gagal, test gagal.

3 Assertion Paling Sering

1. assertEquals() — Check nilai sama

@Test
public void testAddition() {
    int hasil = 2 + 2;
    assertEquals(4, hasil);  // "hasil harus sama dengan 4"
}

Jika hasil tidak sama dengan 4, test FAIL.

2. assertTrue() — Check boolean true

@Test
public void testIsPositive() {
    int number = 10;
    assertTrue(number > 0);  // "10 > 0 harus true"
}

3. assertThrows() — Expect exception

Kadang kita ingin method melempar exception (error). Kita check apakah exception itu dilempar:

@Test
public void testDivideByZero() {
    assertThrows(ArithmeticException.class, () -> {
        int hasil = 10 / 0;  // Ini akan throw ArithmeticException
    });
}

“Ini code harus throw ArithmeticException. Jika gak throw, test FAIL.”