0
0
JUnittesting~5 mins

Why assertions verify expected outcomes in JUnit

Choose your learning style9 modes available
Introduction

Assertions check if the test results match what we expect. They help us find mistakes early.

When you want to confirm a function returns the right value.
When checking if a feature works as planned after changes.
When making sure error messages appear for wrong inputs.
When verifying that data saved in a database is correct.
When testing if a user interface shows the expected text.
Syntax
JUnit
assertEquals(expected, actual);
assertTrue(condition);
assertFalse(condition);
assertNotNull(object);

assertEquals compares expected and actual values.

assertTrue checks if a condition is true.

assertFalse checks if a condition is false.

assertNotNull checks if an object is not null.

Examples
Checks if adding 2 and 3 gives 5.
JUnit
assertEquals(5, calculator.add(2, 3));
Verifies the user is logged in.
JUnit
assertTrue(user.isLoggedIn());
Confirms the list is not empty.
JUnit
assertFalse(list.isEmpty());
Ensures the response object is not null.
JUnit
assertNotNull(response);
Sample Program

This test checks if the add method returns the correct sum of 2 and 3. The assertion verifies the expected outcome is 5.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @Test
    void testAdd() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result);
    }
}

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
}
OutputSuccess
Important Notes

Assertions stop the test immediately if they fail, helping you find errors fast.

Use clear expected values to avoid confusion in tests.

Summary

Assertions confirm your code works as expected.

They help catch bugs early by comparing actual results to expected ones.

Using assertions makes tests reliable and meaningful.