0
0
JunitDebug / FixBeginner · 4 min read

How to Fix Assertion Error in JUnit Tests Quickly

An AssertionError in JUnit means your test expected a different result than what actually happened. To fix it, check your expected value and actual value carefully, then update your assertEquals or other assertions to match the correct expected outcome.
🔍

Why This Happens

An AssertionError occurs when the actual result from your code does not match the expected result defined in your test. This usually means either the code under test has a bug or the test has incorrect expected values.

java
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(6, result); // Incorrect expected value causes AssertionError
    }
}

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
Output
org.opentest4j.AssertionFailedError: Expected :6 Actual :5 <Click to see difference>
🔧

The Fix

Update the expected value in your assertion to match the correct result from your code. Here, the sum of 2 and 3 is 5, so the expected value should be 5, not 6.

java
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result); // Correct expected value
    }
}

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
Output
Test passed successfully
🛡️

Prevention

To avoid assertion errors in the future:

  • Double-check expected values before writing assertions.
  • Use descriptive assertion messages to clarify intent.
  • Run tests frequently to catch mismatches early.
  • Consider using parameterized tests for multiple inputs.
  • Keep your test data simple and clear.
⚠️

Related Errors

Other common errors similar to AssertionError include:

  • NullPointerException: Happens when your test or code tries to use a null object.
  • TimeoutException: When a test takes too long to complete.
  • IllegalArgumentException: When invalid arguments are passed to methods.

Fix these by checking nulls, optimizing code, and validating inputs.

Key Takeaways

AssertionError means expected and actual values differ in your test.
Always verify your expected values match the real output from your code.
Use clear assertion messages to help identify failures quickly.
Run tests often to catch errors early and keep tests simple.
Understand related errors to improve overall test reliability.