What Is Unit Testing in Java and How Does JUnit Work?

Learn What Is Unit Testing in Java and How Does JUnit Work? with practical examples, explanations, best practices, and real-world coding techniques.

Unit testing in Java is the practice of testing small, focused pieces of application logic independently. Instead of manually checking a feature every time code changes, developers create automated tests that verify expected behavior repeatedly. A good unit test gives fast feedback when a method or class no longer behaves according to its intended contract.

Unit tests are especially valuable in applications that evolve over time. When developers refactor existing code, fix bugs, or add new features, a reliable test suite helps identify regressions early. The goal is not simply to increase the number of tests, but to create tests that are clear, deterministic, isolated, and useful when something fails.

What a Good Unit Test Should Do

Focused

Tests one behavior or a small logical unit.

Repeatable

Produces the same result when run under the same conditions.

Fast

Can be executed frequently during development.

Meaningful

Clearly communicates the behavior being protected.

What Is Unit Testing?

A unit test verifies a small piece of code, commonly a method or a class, without depending on unrelated external systems. For example, a price calculator can be tested by supplying different inputs and checking whether the returned result is correct.

A unit test should normally avoid dependencies such as real databases, remote APIs, file systems, message brokers, or external services. Those systems are important to test too, but they usually belong to integration or end-to-end testing rather than a small isolated unit test.

Unit Test vs Integration Test

Unit Test Integration Test
Focuses on a small unit of logic. Checks interaction between multiple components or systems.
Usually avoids external infrastructure. May use databases, HTTP services, queues, or other infrastructure.
Usually very fast. Usually slower and more environment-dependent.

Why Use Unit Tests in Java?

Catch Regressions

A previously working behavior can be automatically checked after future changes.

Safer Refactoring

A test suite gives developers feedback while internal implementation is changed.

Executable Documentation

Well-written tests show how a method is expected to behave for important inputs and edge cases.

Faster Feedback

Developers can run focused tests frequently instead of repeatedly checking behavior manually.

JUnit 5 for Java Testing

JUnit is one of the most widely used testing frameworks in the Java ecosystem. JUnit 5 introduced the JUnit Jupiter programming model, which provides annotations and APIs for writing modern Java tests.

A basic JUnit test usually contains a method annotated with @Test. The test executes application code and uses assertions to compare the actual result with the expected result.

Basic Test Structure

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

class CalculatorTest {

    @Test
    void addShouldReturnSum() {

        Calculator calculator =
            new Calculator();

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

        assertEquals(5, result);
    }
}

The test follows a simple sequence: prepare the input, execute the behavior, and verify the result. This pattern is often described as Arrange, Act, Assert.

Arrange, Act, Assert

Arrange

Create the objects and input data required by the test.

Act

Execute the method or behavior being tested.

Assert

Verify that the observed result matches the expected behavior.

Keeping these phases easy to recognize makes tests easier to read and maintain.

JUnit Assertions

JUnit provides several assertions for checking different kinds of behavior.

Assertion Purpose
assertEquals() Checks that expected and actual values are equal.
assertNotEquals() Checks that values are different.
assertTrue() Checks that a condition is true.
assertFalse() Checks that a condition is false.
assertNull() Checks that a value is null.
assertNotNull() Checks that a value is not null.

Example with Multiple Assertions

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

class UserTest {

    @Test
    void userShouldContainExpectedData() {

        User user =
            new User(
                "Ananya",
                "ananya@example.com"
            );

        assertNotNull(user);
        assertEquals(
            "Ananya",
            user.getName()
        );

        assertEquals(
            "ananya@example.com",
            user.getEmail()
        );

        assertTrue(
            user.getEmail().contains("@")
        );
    }
}

Testing Exceptions

A method may be expected to reject invalid input by throwing an exception. JUnit provides assertThrows() for this scenario.

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

class AccountTest {

    @Test
    void withdrawShouldRejectNegativeAmount() {

        Account account =
            new Account(1000);

        assertThrows(
            IllegalArgumentException.class,
            () -> account.withdraw(-100)
        );
    }
}

Testing the expected exception type is usually more useful than simply verifying that "something failed". When the exception contains important information, the test can also inspect the returned exception object.

IllegalArgumentException exception =
    assertThrows(
        IllegalArgumentException.class,
        () -> account.withdraw(-100)
    );

assertEquals(
    "Amount must be positive",
    exception.getMessage()
);

JUnit Test Lifecycle

Tests often require common setup before each test or cleanup after a test. JUnit provides lifecycle annotations for this purpose.

Annotation Purpose
@BeforeEach Runs before each test method.
@AfterEach Runs after each test method.
@BeforeAll Runs once before all test methods in the test class.
@AfterAll Runs once after all test methods in the test class.
import org.junit.jupiter.api.*;

class CalculatorTest {

    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @AfterEach
    void tearDown() {
        calculator = null;
    }

    @Test
    void addShouldReturnCorrectValue() {

        assertEquals(
            10,
            calculator.add(4, 6)
        );
    }
}

Keep lifecycle setup small. Large setup methods can hide what a test actually depends on and make individual tests harder to understand.

Parameterized Tests

Sometimes the same behavior needs to be tested with many inputs. Instead of creating multiple almost-identical test methods, JUnit supports parameterized tests. A parameterized test can execute the same test logic with different arguments.

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

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class CalculatorTest {

    @ParameterizedTest
    @CsvSource({
        "2, 3, 5",
        "10, 5, 15",
        "-2, 4, 2",
        "0, 7, 7"
    })
    void addShouldReturnExpectedResult(
            int first,
            int second,
            int expected) {

        Calculator calculator =
            new Calculator();

        assertEquals(
            expected,
            calculator.add(
                first,
                second
            )
        );
    }
}

Parameterized tests are useful for boundary values, valid input combinations, invalid values, and other data-driven scenarios where the behavior stays the same but the inputs change.

Testing Collections and Objects

Unit tests are not limited to primitive return values. Applications frequently return objects and collections, so tests should verify the observable behavior that matters to the caller.

import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;

class UserServiceTest {

    @Test
    void shouldReturnActiveUsers() {

        UserService service =
            new UserService();

        List<User> users =
            service.getActiveUsers();

        assertEquals(
            2,
            users.size()
        );

        assertEquals(
            "Ananya",
            users.get(0).getName()
        );

        assertTrue(
            users.stream()
                .allMatch(User::isActive)
        );
    }
}

Avoid checking implementation details that are irrelevant to the behavior being tested. The test should communicate what the consumer of the class can rely on.

Test Isolation

A useful unit test should not depend on another test running before it. Shared mutable state can create tests that pass or fail depending on execution order.

A Common Problem

Test A changes a shared static list, Test B assumes that list is empty, and suddenly the result depends on whether Test A ran first. This is a sign that the tests are not properly isolated.

Each test should create or reset the state it needs. Mutable global state, static caches, environment-dependent values, and real external services should be treated carefully.

Test Instance Lifecycle

JUnit Jupiter uses a per-method test instance lifecycle by default, meaning a new test class instance is created for each test method. This helps prevent mutable state from leaking between tests.

A test class can explicitly use a per-class lifecycle when there is a reason to share the same test instance across methods. Shared state must then be managed deliberately so one test does not affect another.

Testing Private Methods

In most cases, private methods should not be tested directly. Private implementation details are internal to the class. Tests should generally exercise the public behavior that uses those methods.

Prefer Behavior Over Implementation

When a private method changes internally but the externally visible behavior remains correct, the tests should normally continue to pass. This makes the test suite more resistant to harmless refactoring.

Unit Tests and Dependencies

Real applications often depend on repositories, HTTP clients, message publishers, payment providers, or other services. Directly connecting to those systems from a small unit test makes the test slower and more dependent on external state.

A better design is to depend on abstractions and provide a controlled test implementation, fake, stub, or mock where appropriate. Frameworks such as Mockito are commonly used in Java projects for mocking dependencies, but mocking should support good design rather than hide complex or poorly structured code.

interface PaymentGateway {

    boolean charge(
        double amount
    );
}

class OrderService {

    private final PaymentGateway gateway;

    OrderService(
            PaymentGateway gateway) {

        this.gateway = gateway;
    }

    boolean placeOrder(
            double amount) {

        return gateway.charge(amount);
    }
}

Because OrderService depends on an interface, a test can supply a controlled implementation without contacting a real payment provider. This is one reason dependency injection and testable design often work well together.

Testing Time, Randomness and External State

Tests become difficult to reproduce when their result depends on the current time, random values, network responses, environment variables, or machine-specific configuration.

A useful design is to move such dependencies behind abstractions. For example, instead of calling the system clock directly from business logic, the application can depend on a clock abstraction that can be controlled during testing.

Testing Edge Cases

A strong test suite does more than verify the normal path. Important edge cases often reveal defects that ordinary examples do not cover.

Input Boundaries

Test minimum values, maximum values, zero, empty values, and invalid ranges where relevant.

Null Values

Verify the intended behavior when null is valid or invalid for the API.

Empty Collections

Confirm that empty lists, sets, or maps are handled correctly.

Failure Scenarios

Verify expected exceptions and failure behavior instead of testing only successful execution.

Test Naming

Test names should explain the behavior being protected. Names such as test1() or checkMethod() provide very little information when a test fails.

Weak

testDiscount()

Better

shouldApplyTwentyPercentDiscountForPremiumCustomer()

Good test names describe the scenario and expected outcome without forcing the reader to open the implementation to understand what the test means.

Keep Tests Small

A test that performs ten unrelated operations is difficult to debug when it fails. Smaller tests make failures easier to understand and usually make the intended behavior clearer.

Prefer

  • One scenario per test.
  • Minimal setup.
  • Clear inputs.
  • Clear expected result.
  • Minimal unrelated assertions.

Avoid Over-Testing Implementation Details

A test can become fragile when it checks internal details rather than externally observable behavior. For example, verifying the exact order of internal helper calls may make a test fail after a harmless refactoring.

Tests should protect behavior that matters to users or other components. Implementation-level verification is sometimes necessary for infrastructure code, but it should not become the default approach for every class.

Code Coverage Is Not the Same as Test Quality

Code coverage can show which parts of a codebase are executed by tests, but a high coverage percentage does not automatically mean that the tests are useful. A poorly designed test can execute many lines while asserting very little.

Good testing focuses on important behavior, boundaries, failure cases, and business rules. Coverage is useful as a signal, but it should not become the only measure of testing quality.

Running Unit Tests in a Build

Unit tests should normally run as part of the project build so that failures are detected automatically. Maven and Gradle both support Java testing workflows and can integrate test execution into CI pipelines.

Typical Development Flow

Write / Change Code
↓
Run Unit Tests
↓
Investigate Failures
↓
Commit Changes
↓
CI Runs Tests Again

Common Java Unit Testing Mistakes

Testing Only the Happy Path

A test suite that checks only valid input can miss important boundary and failure conditions.

Using a Real Database for Every Unit Test

This makes tests slower and couples them to external infrastructure. Database behavior is usually better covered separately with integration tests.

Sharing Mutable State

Shared state can cause tests to influence one another and create order-dependent failures.

Overusing Mocks

Excessive mocking can make tests describe implementation details instead of actual behavior and can hide design problems.

Meaningless Test Names

Poor names make failures difficult to understand and reduce the documentation value of the test suite.

Asserting Too Much

A test containing many unrelated assertions can become difficult to diagnose and maintain.

Java Unit Testing Best Practices

  • Write tests around observable behavior rather than implementation details.
  • Keep individual tests focused and easy to understand.
  • Use Arrange, Act, Assert to organize test logic.
  • Give tests descriptive names.
  • Include boundary and failure scenarios.
  • Keep unit tests independent from external infrastructure.
  • Use dependency injection to make external dependencies replaceable during testing.
  • Use parameterized tests when the same behavior needs to be verified with multiple inputs.
  • Keep test setup small and explicit.
  • Run tests automatically in the build and CI pipeline.
  • Treat coverage as a supporting metric rather than the sole definition of test quality.
  • Remove unnecessary duplication while keeping each test readable.

Practical Testing Strategy

1

Identify the behavior.

2

Choose normal and edge-case inputs.

3

Write focused assertions.

4

Run tests continuously during development.

Key Takeaways

Java unit testing verifies small and focused pieces of application behavior automatically.

JUnit 5 provides annotations, assertions, lifecycle support, and parameterized testing for writing maintainable Java tests.

A good unit test should be focused, repeatable, isolated, fast, and clear.

Arrange, Act, Assert provides a simple structure for organizing test logic.

assertEquals(), assertTrue(), assertFalse(), assertNull(), and assertThrows() are useful for verifying different behaviors.

Parameterized tests reduce duplication when the same behavior needs to be checked against multiple inputs.

Unit tests should normally avoid real external infrastructure such as databases and remote services. Those interactions can be covered with integration tests.

The strongest test suites focus on meaningful behavior and edge cases rather than simply maximizing the number of executed lines.

Code Examples

java
// Calculator.java
public class Calculator {

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

    public int subtract(int a, int b) {
        return a - b;
    }
}

// CalculatorTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class CalculatorTest {

    @Test
    void addShouldReturnSum() {

        Calculator calculator =
            new Calculator();

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

        assertEquals(
            5,
            result
        );
    }

    @Test
    void subtractShouldReturnDifference() {

        Calculator calculator =
            new Calculator();

        int result =
            calculator.subtract(5, 3);

        assertEquals(
            2,
            result
        );
    }
}
    
java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

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

class CalculatorTest {

    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @Test
    void addShouldReturnCorrectResult() {

        int result =
            calculator.add(10, 20);

        assertEquals(
            30,
            result
        );
    }

    @Test
    void resultShouldBePositive() {

        int result =
            calculator.add(10, 5);

        assertTrue(
            result > 0
        );
    }
}
    
java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

class BankAccount {

    private double balance;

    BankAccount(double balance) {

        if (balance < 0) {
            throw new IllegalArgumentException(
                "Initial balance cannot be negative"
            );
        }

        this.balance = balance;
    }

    void withdraw(double amount) {

        if (amount <= 0) {
            throw new IllegalArgumentException(
                "Amount must be positive"
            );
        }

        if (amount > balance) {
            throw new IllegalStateException(
                "Insufficient balance"
            );
        }

        balance -= amount;
    }

    double getBalance() {
        return balance;
    }
}

class BankAccountTest {

    @Test
    void withdrawShouldReduceBalance() {

        BankAccount account =
            new BankAccount(1000);

        account.withdraw(250);

        assertEquals(
            750,
            account.getBalance()
        );
    }

    @Test
    void withdrawShouldRejectNegativeAmount() {

        BankAccount account =
            new BankAccount(1000);

        IllegalArgumentException exception =
            assertThrows(
                IllegalArgumentException.class,
                () -> account.withdraw(-100)
            );

        assertEquals(
            "Amount must be positive",
            exception.getMessage()
        );
    }

    @Test
    void withdrawShouldRejectInsufficientBalance() {

        BankAccount account =
            new BankAccount(500);

        assertThrows(
            IllegalStateException.class,
            () -> account.withdraw(600)
        );
    }
}
    
java
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class Calculator {

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

class CalculatorParameterizedTest {

    @ParameterizedTest
    @CsvSource({
        "2, 3, 5",
        "10, 20, 30",
        "-2, 5, 3",
        "0, 10, 10",
        "-5, -5, -10"
    })
    void addShouldReturnExpectedResult(
            int first,
            int second,
            int expected) {

        Calculator calculator =
            new Calculator();

        assertEquals(
            expected,
            calculator.add(
                first,
                second
            )
        );
    }
}
    
java
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class StringValidator {

    boolean isValidUsername(
            String username) {

        return username != null
            && !username.isBlank()
            && username.length() >= 3;
    }
}

class StringValidatorTest {

    private final StringValidator validator =
        new StringValidator();

    @Test
    void validUsernameShouldReturnTrue() {

        assertTrue(
            validator.isValidUsername(
                "ananya"
            )
        );
    }

    @Test
    void shortUsernameShouldReturnFalse() {

        assertFalse(
            validator.isValidUsername(
                "ab"
            )
        );
    }

    @Test
    void blankUsernameShouldReturnFalse() {

        assertFalse(
            validator.isValidUsername(
                "   "
            )
        );
    }

    @Test
    void nullUsernameShouldReturnFalse() {

        assertFalse(
            validator.isValidUsername(
                null
            )
        );
    }
}
    

Pro Tip

Write unit tests around behavior that should remain true even when the implementation changes. Keep tests isolated from databases, networks, clocks, and other external systems where practical, use parameterized tests for repeated input scenarios, and make failures easy to understand through descriptive test names and precise assertions.

More Advanced Java lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.