How do I test expected values with assertEquals()?

In JUnit, you use assertEquals() to test whether an actual value matches an expected value.

The basic syntax is:

assertEquals(expectedValue, actualValue);

The first argument is what you expect.
The second argument is what your code actually produced.

Basic Example

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void shouldAddTwoNumbers() {
        int result = 2 + 3;

        assertEquals(5, result);
    }
}

In this example:

assertEquals(5, result);

means:

I expect the result to be 5.

If result is 5, the test passes.
If result is anything else, the test fails.

Example with Strings

import org.junit.jupiter.api.Test;

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

class GreetingTest {

    @Test
    void shouldReturnGreetingMessage() {
        String message = "Hello, Java";

        assertEquals("Hello, Java", message);
    }
}

Using a Failure Message

You can add a custom message that appears when the test fails:

assertEquals(10, result, "The result should be 10");

Example:

import org.junit.jupiter.api.Test;

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

class MathTest {

    @Test
    void shouldMultiplyNumbers() {
        int result = 4 * 3;

        assertEquals(12, result, "4 multiplied by 3 should be 12");
    }
}

Common Mistake

Be careful with the order:

assertEquals(expected, actual);

Good:

assertEquals(100, total);

Less clear:

assertEquals(total, 100);

JUnit will still compare the values, but failure messages are easier to understand when the expected value comes first.

Example with a Method

Suppose you have this class:

class Calculator {

    int add(int a, int b) {
        return a + b;
    }
}

You can test it like this:

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void addShouldReturnSum() {
        Calculator calculator = new Calculator();

        int actual = calculator.add(2, 3);

        assertEquals(5, actual);
    }
}

Summary

Use assertEquals() like this:

assertEquals(expected, actual);

For example:

assertEquals(5, result);
assertEquals("Alice", name);
assertEquals(100.0, price);

assertEquals() is one of the most common JUnit assertions because it clearly checks whether your code returned the value you expected.

How do I use assertions in JUnit?

In JUnit, assertions are used to verify that your code produces the expected result. If an assertion fails, the test fails.

JUnit 5 assertions are provided by the org.junit.jupiter.api.Assertions class.

Basic Example

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void testAddition() {
        int result = 2 + 3;

        assertEquals(5, result);
    }
}

In this example, the test passes because 2 + 3 equals 5.

Common JUnit Assertions

assertEquals()

Use assertEquals() to check whether two values are equal.

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

assertEquals(10, 5 + 5);
assertEquals("Hello", "He" + "llo");

You can also provide a failure message:

assertEquals(10, 5 + 4, "The result should be 10");

assertNotEquals()

Use assertNotEquals() to check that two values are not equal.

import static org.junit.jupiter.api.Assertions.assertNotEquals;

assertNotEquals(10, 5 + 4);

assertTrue() and assertFalse()

Use assertTrue() when a condition should be true.

import static org.junit.jupiter.api.Assertions.assertTrue;

assertTrue(10 > 5);

Use assertFalse() when a condition should be false.

import static org.junit.jupiter.api.Assertions.assertFalse;

assertFalse(10 < 5);

assertNull() and assertNotNull()

Use assertNull() to check that a value is null.

import static org.junit.jupiter.api.Assertions.assertNull;

String name = null;

assertNull(name);

Use assertNotNull() to check that a value is not null.

import static org.junit.jupiter.api.Assertions.assertNotNull;

String name = "Kode Java";

assertNotNull(name);

assertSame() and assertNotSame()

Use assertSame() to check whether two references point to the same object.

import static org.junit.jupiter.api.Assertions.assertSame;

String text = "Java";
String sameText = text;

assertSame(text, sameText);

Use assertNotSame() when two references should not point to the same object.

import static org.junit.jupiter.api.Assertions.assertNotSame;

String first = new String("Java");
String second = new String("Java");

assertNotSame(first, second);

Note that assertEquals() checks object equality, while assertSame() checks object identity.

assertArrayEquals()

Use assertArrayEquals() to compare arrays.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

int[] expected = {1, 2, 3};
int[] actual = {1, 2, 3};

assertArrayEquals(expected, actual);

assertThrows()

Use assertThrows() to verify that a block of code throws an expected exception.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertThrows;

class NumberParserTest {

    @Test
    void testInvalidNumber() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("abc");
        });
    }
}

You can also inspect the thrown exception:

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

NumberFormatException exception = assertThrows(
        NumberFormatException.class,
        () -> Integer.parseInt("abc")
);

assertEquals("For input string: \"abc\"", exception.getMessage());

assertAll()

Use assertAll() to group multiple assertions together. JUnit will run all assertions and report all failures.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class UserTest {

    @Test
    void testUserDetails() {
        String name = "Alice";
        int age = 25;

        assertAll(
                () -> assertEquals("Alice", name),
                () -> assertEquals(25, age),
                () -> assertTrue(age >= 18)
        );
    }
}

Without assertAll(), the test stops at the first failed assertion.

fail()

Use fail() when a test should fail explicitly.

import static org.junit.jupiter.api.Assertions.fail;

fail("This test should not reach this point");

This is often useful inside conditional logic or exception handling.

Complete Example

import org.junit.jupiter.api.Test;

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

class StringUtilsTest {

    @Test
    void testStringAssertions() {
        String text = "JUnit";

        assertEquals("JUnit", text);
        assertNotEquals("TestNG", text);
        assertTrue(text.startsWith("J"));
        assertFalse(text.isEmpty());
        assertNotNull(text);
    }

    @Test
    void testArrayAssertions() {
        int[] numbers = {1, 2, 3};

        assertArrayEquals(new int[]{1, 2, 3}, numbers);
    }

    @Test
    void testExceptionAssertion() {
        assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("not-a-number");
        });
    }
}

Using Static Imports

Most JUnit tests use static imports so assertions can be written directly:

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

Then you can write:

assertEquals(5, result);
assertTrue(result > 0);
assertThrows(Exception.class, () -> someMethod());

Instead of:

Assertions.assertEquals(5, result);
Assertions.assertTrue(result > 0);
Assertions.assertThrows(Exception.class, () -> someMethod());

Summary

Common JUnit assertion methods include:

Assertion Purpose
assertEquals(expected, actual) Checks that two values are equal
assertNotEquals(unexpected, actual) Checks that two values are not equal
assertTrue(condition) Checks that a condition is true
assertFalse(condition) Checks that a condition is false
assertNull(value) Checks that a value is null
assertNotNull(value) Checks that a value is not null
assertSame(expected, actual) Checks that two references point to the same object
assertNotSame(unexpected, actual) Checks that two references do not point to the same object
assertArrayEquals(expected, actual) Checks that two arrays are equal
assertThrows(type, executable) Checks that an exception is thrown
assertAll(executables) Groups multiple assertions
fail(message) Fails the test explicitly

In short, assertions are the main way to express what your code is expected to do in a JUnit test.

How do I use @Test in JUnit?

Using @Test in JUnit

In JUnit, @Test is an annotation that marks a method as a test method. When you run your tests, JUnit looks for methods annotated with @Test and executes them automatically.


1. Add the Correct Import

For JUnit 5, use:

import org.junit.jupiter.api.Test;

You will usually also import assertions such as:

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

2. Basic Example

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void addTwoNumbers() {
        int result = 10 + 15;

        assertEquals(25, result);
    }
}

Here:

  • @Test tells JUnit this method should be run as a test.
  • assertEquals(25, result) checks that the actual result is 25.
  • If the assertion passes, the test passes.
  • If the assertion fails, the test fails.

3. Common JUnit 5 Assertions

import org.junit.jupiter.api.Test;

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

class ExampleTest {

    @Test
    void assertionsExample() {
        String message = "Hello JUnit";

        assertNotNull(message);
        assertTrue(message.contains("JUnit"));
        assertEquals("Hello JUnit", message);
    }
}

Common assertions include:

Assertion Purpose
assertEquals(expected, actual) Checks that two values are equal
assertTrue(condition) Checks that a condition is true
assertFalse(condition) Checks that a condition is false
assertNotNull(value) Checks that a value is not null
assertThrows(...) Checks that code throws an expected exception

4. Testing Exceptions

Use assertThrows() when you expect code to throw an exception:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertThrows;

class DivisionTest {

    @Test
    void divideByZeroThrowsException() {
        assertThrows(ArithmeticException.class, () -> {
            int result = 10 / 0;
        });
    }
}

5. JUnit 5 Test Method Rules

In JUnit 5, test methods usually:

  • Are annotated with @Test
  • Return void
  • Do not need to be public
  • Should contain assertions
  • Should have descriptive names

Example:

@Test
void shouldReturnSumWhenAddingTwoNumbers() {
    assertEquals(5, 2 + 3);
}

6. JUnit 4 vs. JUnit 5 Import

Be careful: JUnit 4 and JUnit 5 use different @Test imports.

JUnit 5

import org.junit.jupiter.api.Test;

JUnit 4

import org.junit.Test;

For new projects, JUnit 5 is generally recommended.


7. Running the Test

You can run JUnit tests from:

  • Your IDE, such as IntelliJ IDEA or Eclipse
  • Maven
  • Gradle

With Maven:

mvn test

With Gradle:

gradle test

or:

./gradlew test

Summary

Use @Test above a method to tell JUnit, “this is a test.”

import org.junit.jupiter.api.Test;

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

class MyTest {

    @Test
    void simpleTest() {
        assertEquals(4, 2 + 2);
    }
}

That method will be discovered and run by JUnit as part of your test suite.

How do I understand the basic structure of a JUnit test class?

A basic JUnit test class is just a Java class that contains one or more test methods. Each test method checks whether a small piece of code behaves the way you expect.

Here is a simple JUnit 5 example:

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void shouldAddTwoNumbers() {
        int result = 2 + 3;

        assertEquals(5, result);
    }
}

1. The Test Class

class CalculatorTest {
    // test methods go here
}

A JUnit test class is usually named after the class being tested, followed by Test.

For example:

Class Being Tested Test Class
Calculator CalculatorTest
UserService UserServiceTest
OrderRepository OrderRepositoryTest

The test class does not need a main() method. JUnit runs the tests for you.

2. The @Test Annotation

@Test
void shouldAddTwoNumbers() {
    // test code
}

The @Test annotation tells JUnit:

This method is a test method. Run it as part of the test suite.

In JUnit 5, the annotation comes from:

import org.junit.jupiter.api.Test;

3. The Test Method

A test method usually:

  1. Creates some input or test data.
  2. Runs the code being tested.
  3. Checks the result.

Example:

@Test
void shouldAddTwoNumbers() {
    int result = 2 + 3;

    assertEquals(5, result);
}

The method name should describe the expected behavior. Common naming styles include:

void shouldAddTwoNumbers()
void returnsTrueWhenPasswordIsValid()
void throwsExceptionWhenEmailIsMissing()

4. Assertions

Assertions are checks that decide whether the test passes or fails.

Common JUnit 5 assertions include:

assertEquals(expected, actual);
assertTrue(condition);
assertFalse(condition);
assertNotNull(value);
assertNull(value);
assertThrows(Exception.class, () -> {
    // code expected to throw exception
});

Example:

@Test
void shouldCheckUserName() {
    String name = "Alice";

    assertNotNull(name);
    assertEquals("Alice", name);
    assertTrue(name.startsWith("A"));
}

If all assertions pass, the test passes. If any assertion fails, the test fails.

Assertions are usually imported like this:

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

5. Basic Arrange-Act-Assert Pattern

Many test methods follow this structure:

@Test
void shouldCalculateTotalPrice() {
    // Arrange
    int price = 100;
    int quantity = 3;

    // Act
    int total = price * quantity;

    // Assert
    assertEquals(300, total);
}

Arrange

Prepare the data or objects needed for the test.

int price = 100;
int quantity = 3;

Act

Run the code you want to test.

int total = price * quantity;

Assert

Check that the result is correct.

assertEquals(300, total);

6. A Complete Basic JUnit 5 Test Class

import org.junit.jupiter.api.Test;

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

class StringUtilsTest {

    @Test
    void shouldConvertTextToUpperCase() {
        // Arrange
        String text = "hello";

        // Act
        String result = text.toUpperCase();

        // Assert
        assertEquals("HELLO", result);
    }

    @Test
    void shouldCheckIfTextContainsWord() {
        // Arrange
        String text = "Learning JUnit is useful";

        // Act
        boolean containsJUnit = text.contains("JUnit");

        // Assert
        assertTrue(containsJUnit);
    }
}

7. Optional Setup Method

If several tests need the same object or data, you can use @BeforeEach.

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    private int baseNumber;

    @BeforeEach
    void setUp() {
        baseNumber = 10;
    }

    @Test
    void shouldAddNumber() {
        int result = baseNumber + 5;

        assertEquals(15, result);
    }

    @Test
    void shouldMultiplyNumber() {
        int result = baseNumber * 2;

        assertEquals(20, result);
    }
}

@BeforeEach runs before every test method.

8. JUnit 4 vs. JUnit 5 Structure

Older JUnit 3 or JUnit 4 tests may look different.

JUnit 5 style

import org.junit.jupiter.api.Test;

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

class AppTest {

    @Test
    void shouldWork() {
        assertTrue(true);
    }
}

Older JUnit 3 style

import junit.framework.TestCase;

public class AppTest extends TestCase {

    public void testApp() {
        assertTrue(true);
    }
}

In modern Java projects, you will usually prefer JUnit 5 unless you are maintaining older code.

9. Typical Folder Location

In a Maven or Gradle Java project, test classes usually go under:

src/test/java

Application code usually goes under:

src/main/java

Example:

src
├── main
│   └── java
│       └── org.kodejava
│           └── Calculator.java
└── test
    └── java
        └── org.kodejava
            └── CalculatorTest.java

Summary

A basic JUnit test class usually has:

  1. A class name ending in Test.
  2. One or more methods annotated with @Test.
  3. Assertions such as assertEquals() or assertTrue().
  4. A clear structure: Arrange, Act, Assert.
  5. Optional setup methods such as @BeforeEach.

In short:

import org.junit.jupiter.api.Test;

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

class ExampleTest {

    @Test
    void shouldDoSomething() {
        // Arrange
        String value = "JUnit";

        // Act
        boolean result = value.contains("Unit");

        // Assert
        assertTrue(result);
    }
}

How do I add JUnit to a Gradle project?

To add JUnit to a Gradle project, add the JUnit dependency to your build.gradle or build.gradle.kts file and configure Gradle to use the JUnit Platform.

If you use Groovy Gradle: build.gradle

For JUnit 5, add:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
}

test {
    useJUnitPlatform()
}

If you use Kotlin Gradle: build.gradle.kts

plugins {
    java
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
}

tasks.test {
    useJUnitPlatform()
}

Example JUnit 5 Test

import org.junit.jupiter.api.Test;

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

class CalculatorTest {

    @Test
    void addsNumbers() {
        assertEquals(4, 2 + 2);
    }
}

Place test files under:

src/test/java

For example:

src/test/java/org/kodejava/CalculatorTest.java

Run Tests

From the command line:

./gradlew test

On Windows:

gradlew test

If You Need JUnit 4 Instead

Use this dependency:

dependencies {
    testImplementation 'junit:junit:4.13.2'
}

For most new Gradle projects, prefer JUnit 5 with junit-jupiter.