Learn Java · 14/15

Testing Your Java Code

12 min read

Welcome, brave coder! You've written some Java code. It looks magnificent. It compiles without a single error. But does it work? And more importantly, will it still work after you or your teammate "quickly" adds a "tiny" feature next week?

This is where testing comes in. It’s the safety net that lets you code with confidence, the friendly robot that double-checks your work, and the reason you can sleep at night without worrying that your code will spontaneously combust.

1. JUnit 5 Basics: Writing Your First Unit Test

The Problem: How Do I Know My Code Really Works? 🤔

Imagine you've built a beautiful, high-tech coffee machine. You press the "Espresso" button, and it gives you... hot water. You try again, and it dispenses coffee beans into your cup. Manually checking every button and every combination of settings after every small change would be a nightmare.

In software, this "machine" is your code, and the smallest testable parts (a single method, a class) are called units. Manually testing them every time you make a change is slow, boring, and easy to mess up.

The Solution: Automated Unit Tests with JUnit 5 ✅

Unit Testing is the practice of testing these small, isolated units of your code to ensure they behave as expected.

JUnit 5 is the most popular testing framework for Java that helps us automate this process. It's like having a dedicated robot that presses all the buttons on your coffee machine in a precise sequence and checks that it produces a perfect espresso every time.

Getting Started: Setting up JUnit 5

First things first, you need to add JUnit 5 to your project. How you do this depends on your build tool (Maven or Gradle).

For Maven Users (pom.xml):

Add this dependency to your pom.xml. The junit-jupiter artifact handily pulls in the necessary components like the API and the engine.

xml
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>5.10.2</version> <!-- Check for the latest version! -->
        <scope>test</scope>
    </dependency>
</dependencies>

For Gradle Users (build.gradle):

Ensure your build.gradle file includes the following. Gradle needs to know to use the JUnit Platform for its tests.

groovy
plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2' // Check for the latest version!
}

test {
    useJUnitPlatform()
}

Writing Your First Test: The Calculator 🤖

Let's create a simple Calculator class that we want to test.

src/main/java/com/example/Calculator.java

java
package com.example;

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

Now, let's write a test for it. By convention, test classes are kept in src/test/java and have the same package structure and a Test suffix in their name.

src/test/java/com/example/CalculatorTest.java

java
package com.example;

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

class CalculatorTest {

    @Test
    void testAdd() {
        // 1. Arrange: Set up the test objects
        Calculator calculator = new Calculator();
        int a = 5;
        int b = 10;

        // 2. Act: Call the method being tested
        int result = calculator.add(a, b);

        // 3. Assert: Check if the result is what you expect
        assertEquals(15, result, "5 + 10 should equal 15");
    }
}

Breakdown of the Test:

  • import org.junit.jupiter.api.Test;: This imports the annotation that tells JUnit, "Hey! This is a test method. Run it!"
  • @Test: This annotation marks the testAdd method as a test case. Any method with this tag will be executed by the testing framework.
  • Arrange-Act-Assert (AAA): This is a common pattern for structuring tests.
    • Arrange: You create and configure the objects you need for the test. Here, we create a Calculator instance.
    • Act: You execute the actual method you want to test. We call calculator.add(5, 10).
    • Assert: You verify that the outcome of the action was correct. assertEquals(15, result) checks if the result is equal to the expected value of 15. If it isn't, the test fails! The optional third argument is a message that will be displayed if the test fails, which is super helpful for debugging.

You can now run this test from your IDE (like IntelliJ or Eclipse) or via your build tool (mvn test or gradle test). You should see a comforting green checkmark indicating that your test passed! 🎉


2. Assertions and Test Lifecycle Annotations

The Problem: My Tests Need More Complex Checks and Setup 🛠️

Just checking for equality (assertEquals) is a good start, but what if you need to verify other things? Is a value true? Is an object null? Did a method throw the specific exception you were expecting?

Also, imagine you need to create a new Calculator object for every single test method. Or maybe you need to connect to a test database once before all tests run. Repeating this setup and teardown code in every test is inefficient and error-prone.

The Solution: JUnit's Rich Assertions and Lifecycle Hooks 🪝

JUnit Jupiter provides a whole toolbox of assertion methods and special annotations to manage the lifecycle of your tests.

A Deep Dive into Assertions

All standard assertion methods are static methods in the org.junit.jupiter.api.Assertions class. Here are the most common ones you'll use:

  • assertTrue(boolean condition): Fails if the condition is false.
  • assertFalse(boolean condition): Fails if the condition is true.
  • assertNull(Object obj): Fails if the object is not null.
  • assertNotNull(Object obj): Fails if the object is null.
  • assertNotEquals(Object unexpected, Object actual): Fails if the two objects are equal.
  • assertThrows(Class<T> expectedType, Executable executable): Fails if the executable code block does not throw an exception of the expected type.

Example Test Class with Various Assertions:

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

class AssertionsShowcaseTest {

    @Test
    void testStandardAssertions() {
        assertTrue(5 > 4, "5 should be greater than 4");
        assertFalse(5 < 4, "5 should not be less than 4");
        assertNull(null, "This object should be null");

        String name = "freeCodeCamp";
        assertNotNull(name, "The name variable should not be null");
    }

    @Test
    void testExceptionThrowing() {
        // This test checks if dividing by zero throws an ArithmeticException
        Exception exception = assertThrows(ArithmeticException.class, () -> {
            int result = 10 / 0;
        });

        // You can even assert things about the exception itself!
        assertEquals("/ by zero", exception.getMessage());
    }
}

Managing the Test Lifecycle

Think of these annotations as your stage crew. They set up the scene before the play starts and clean up after it's over.

  • @BeforeAll: Runs once before any tests in the class. Must be a static method. Perfect for expensive, one-time setups like starting a database connection.
  • @AfterAll: Runs once after all tests in the class have finished. Also must be static. Used for global cleanup.
  • @BeforeEach: Runs before each individual @Test method. Ideal for creating clean object instances for every test, ensuring tests don't interfere with each other.
  • @AfterEach: Runs after each individual @Test method. Used for cleaning up resources used by a single test.

Example of Lifecycle Annotations in Action:

java
import org.junit.jupiter.api.*;

class LifecycleDemoTest {

    @BeforeAll
    static void setupAll() {
        System.out.println("Connecting to the test database...");
    }

    @BeforeEach
    void setupEach() {
        System.out.println("  Creating a new calculator object.");
    }

    @Test
    void testOne() {
        System.out.println("    Executing test one...");
        assertTrue(true);
    }

    @Test
    void testTwo() {
        System.out.println("    Executing test two...");
        assertTrue(true);
    }

    @AfterEach
    void tearDownEach() {
        System.out.println("  Test finished. Cleaning up.");
    }

    @AfterAll
    static void tearDownAll() {
        System.out.println("Disconnecting from the test database.");
    }
}

If you run this, you'll see the print statements appear in a very specific, predictable order, demonstrating the lifecycle in action.


3. Mocking Dependencies with Mockito

The Problem: My Code Doesn't Live in a Vacuum isolé

Your Calculator class was simple. But what if you have a ReportService that depends on a DatabaseConnector to work?

java
public class ReportService {
    private DatabaseConnector dbConnector;

    public ReportService(DatabaseConnector dbConnector) {
        this.dbConnector = dbConnector;
    }

    public String generateWeeklyReport() {
        String data = dbConnector.fetchData();
        // ... complex logic to generate report from data
        return "Weekly Report: " + data;
    }
}

To test generateWeeklyReport(), you would need a real database running. This is bad for unit tests because:

  • It's slow: Network and database operations are thousands of times slower than in-memory operations.
  • It's unreliable: What if the network is down? Or the database has bad data? Your test could fail for reasons that have nothing to do with your ReportService code.
  • It's not a unit test: You'd be testing both the service and the database connection. We want to test the service in isolation.

The Solution: Create Fake Objects with Mockito 🎭

Mocking is the process of creating controllable, fake objects (or "mocks") that simulate the behavior of real dependencies. Mockito is the most popular mocking framework for Java. It lets you create these "stunt doubles" for your dependencies.

Getting Started: Setting up Mockito

Add the mockito-core dependency to your project. It's best practice to also include mockito-junit-jupiter which helps integrate Mockito with JUnit 5.

For Maven Users (pom.xml):

xml
<dependencies>
    <!-- ... your JUnit dependency ... -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>5.11.0</version> <!-- Check for the latest version! -->
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>5.11.0</version> <!-- Check for the latest version! -->
        <scope>test</scope>
    </dependency>
</dependencies>

For Gradle Users (build.gradle):

groovy
dependencies {
    // ... your JUnit dependency ...
    testImplementation 'org.mockito:mockito-core:5.11.0' // Check for the latest version!
    testImplementation 'org.mockito:mockito-junit-jupiter:5.11.0'
}

Mocking in Action

Let's test our ReportService without a real database.

java
package com.example;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;

// This tells JUnit 5 to activate the Mockito extension
@ExtendWith(MockitoExtension.class)
class ReportServiceTest {

    // Creates a mock (a fake) DatabaseConnector
    @Mock
    private DatabaseConnector mockDbConnector;

    // Creates an instance of ReportService and injects the mocks (mockDbConnector) into it
    @InjectMocks
    private ReportService reportService;

    @Test
    void testGenerateWeeklyReport() {
        // Arrange: Tell our mock what to do
        // WHEN the fetchData() method is called on our mock...
        when(mockDbConnector.fetchData()).thenReturn("Sample Data"); // ...THEN return "Sample Data"

        // Act: Call the method we are testing
        String report = reportService.generateWeeklyReport();

        // Assert: Check the result
        assertEquals("Weekly Report: Sample Data", report);

        // (Optional) Verify: Check that the fetchData method was actually called
        verify(mockDbConnector).fetchData();
    }
}

Breakdown of the Mocking Test:

  • @ExtendWith(MockitoExtension.class): This enables Mockito's annotation-based features for this test class.
  • @Mock: This annotation creates a mock object of the DatabaseConnector class. This object looks like a DatabaseConnector, but all its methods do nothing by default.
  • @InjectMocks: This creates a real instance of ReportService and tries to inject any fields annotated with @Mock into it.
  • when(...).thenReturn(...): This is the core of mocking. It's called "stubbing." You are telling your mock object: "When this specific method is called on you, return this specific value."
  • verify(...): This lets you check if a certain method on your mock object was called during the test. It's useful for ensuring your code is interacting with its dependencies as you expect.

With this test, we have verified the logic of ReportService completely on its own, without ever touching a real database. It's fast, reliable, and a true unit test.


4. Test-Driven Development (TDD) Concepts

The Problem: My Tests Feel Like an Afterthought afterthought

Usually, the workflow is:

  1. Write a bunch of production code.
  2. Write tests for it (if you have time).
  3. Run the tests and hope they pass.
  4. Fix the code and the tests.

This can lead to code that's hard to test, and you might miss testing crucial edge cases because you're biased by the code you already wrote.

The Solution: Write the Test First with TDD 🔄

Test-Driven Development (TDD) is a software development process that flips the traditional model on its head. It follows a very short, repeating cycle:

  1. RED: Write a small, automated test for a new piece of functionality. Run the test and watch it fail. This is crucial. It fails because you haven't written the code yet.
  2. GREEN: Write the absolute minimum amount of production code required to make the failing test pass. Don't add extra features. Just make the bar green.
  3. REFACTOR: Now that you have a working, tested piece of code, you can clean it up. Improve the names, remove duplication, and enhance the structure of both the production code and the test code, all while making sure the tests stay green.

Then you repeat the cycle for the next small piece of functionality.

A TDD Cycle in Practice

Let's add a subtract method to our Calculator class using TDD.

Cycle 1: The subtract Method

1. RED: Write a failing test.

In CalculatorTest.java, add a new test method. The subtract method doesn't even exist yet, so this won't even compile, which is a form of failing!

java
// Inside CalculatorTest.java
@Test
void testSubtract() {
    Calculator calculator = new Calculator();
    int result = calculator.subtract(10, 4);
    assertEquals(6, result, "10 - 4 should equal 6");
}

2. GREEN: Make the test pass.

Go to Calculator.java and write the simplest possible code to make the test compile and pass.

java
// Inside Calculator.java
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    // Add the new method
    public int subtract(int a, int b) {
        return a - b;
    }
}

Now run your tests. The testSubtract test should pass. You are now in the green!

3. REFACTOR: Clean up the code.

In this simple case, the code is already very clean. There's no duplication to remove or complex logic to simplify. So, we can move on.

Benefits of TDD:

  • Guarantees Test Coverage: You literally cannot write code without a test for it.
  • Drives Better Design: Writing the test first forces you to think about how your code will be used, often leading to cleaner, more decoupled designs.
  • Acts as a Safety Net: The comprehensive test suite gives you immense confidence to refactor and add new features without breaking existing ones.

TDD can feel strange at first, but it's a powerful discipline that builds quality and confidence directly into your development process.


📚 Extra Reading & References

  • JUnit 5: Official User Guide
  • Mockito: Official Documentation
  • TDD: A great article by Martin Fowler on the topic. (A general search for "Martin Fowler TDD" will yield excellent resources.)
  • Baeldung: An amazing resource for all things Java, with many articles on JUnit 5 and Mockito.

Challenge

Challenge: Test the User Service

You are given a UserService class that handles user registration and depends on a UserRepository interface. Your task is to write a complete JUnit 5 test class named UserServiceTest to verify the functionality of the registerUser method.

Requirements:

  1. Setup: Use Mockito to create a mock of the UserRepository and inject it into an instance of UserService.
  2. Success Scenario: Create a test method named testRegisterUser_Success.
    • This test should simulate the case where the username is not yet taken.
    • Assert that the registerUser method returns a non-null User object with the correct username.
    • Verify that the saveUser method of the userRepository mock is called exactly once.
  3. Failure Scenario: Create a test method named testRegisterUser_UserAlreadyExists.
    • This test should simulate the case where the username already exists.
    • Assert that an IllegalArgumentException is thrown when registerUser is called.
    • Verify that the saveUser method of the userRepository mock is never called.

Expected result

Your solution should be a single Java class named UserServiceTest.

java
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    void testRegisterUser_Success() {
        // Arrange
        when(userRepository.findUserByUsername("newUser")).thenReturn(null);

        // Act
        User result = userService.registerUser("newUser", "password123");

        // Assert
        assertNotNull(result);
        assertEquals("newUser", result.getUsername());
        verify(userRepository, times(1)).saveUser(any(User.class));
    }

    @Test
    void testRegisterUser_UserAlreadyExists() {
        // Arrange
        when(userRepository.findUserByUsername("existingUser")).thenReturn(new User("existingUser", "password"));

        // Act & Assert
        assertThrows(IllegalArgumentException.class, () -> {
            userService.registerUser("existingUser", "newPassword");
        });

        verify(userRepository, never()).saveUser(any(User.class));
    }
}
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.