eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

Course – LJU – NPI (tag = JUnit)
announcement - icon

Master the most popular testing framework for Java, through the Learn JUnit course:

>> LEARN JUNIT

Partner – Diagrid – NPI (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

 

1. Overview

In this tutorial, we’ll walk through a custom List implementation using the Test-Driven Development (TDD) process.

This is not an intro to TDD, so we’re assuming you already have some basic idea of what it means and the sustained interest to get better at it.

Simply put, TDD is a design tool, enabling us to drive our implementation with the help of tests.

A quick disclaimer – we’re not focusing on creating efficient implementation here – just using it as an excuse to display TDD practices.

2. Getting Started

First, let’s define the skeleton for our class:

public class CustomList<E> implements List<E> {
    private Object[] internal = {};
    // empty implementation methods
}

The CustomList class implements the List interface, hence it must contain implementations for all the methods declared in that interface.

To get started, we can just provide empty bodies for those methods. If a method has a return type, we can return an arbitrary value of that type, such as null for Object or false for boolean.

For the sake of brevity, we’ll omit optional methods, together with some obligatory methods that aren’t often used.

3. TDD Cycles

Developing our implementation with TDD means that we need to create test cases first, thereby defining requirements for our implementation. Only then we’ll create or fix the implementation code to make those tests pass.

In a very simplified manner, the three main steps in each cycle are:

  1. Writing tests – define requirements in the form of tests
  2. Implementing features – make the tests pass without focusing too much on the elegance of the code
  3. Refactoring – improve the code to make it easier to read and maintain while still passing the tests

We’ll go through these TDD cycles for some methods of the List interface, starting with the simplest ones.

4. The isEmpty Method

The isEmpty method is probably the most straightforward method defined in the List interface. Here’s our starting implementation:

@Override
public boolean isEmpty() {
    return false;
}

This initial method definition is enough to compile. The body of this method will be “forced” to improve when more and more tests are added.

4.1. The First Cycle

Let’s write the first test case which makes sure that the isEmpty method returns true when the list doesn’t contain any element:

@Test
public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
    List<Object> list = new CustomList<>();

    assertTrue(list.isEmpty());
}

The given test fails since the isEmpty method always returns false. We can make it pass just by flipping the return value:

@Override
public boolean isEmpty() {
    return true;
}

4.2. The Second Cycle

To confirm that the isEmpty method returns false when the list isn’t empty, we need to add at least one element:

@Test
public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() {
    List<Object> list = new CustomList<>();
    list.add(null);

    assertFalse(list.isEmpty());
}

An implementation of the add method is now required. Here’s the add method we start with:

@Override
public boolean add(E element) {
    return false;
}

This method implementation doesn’t work as no changes to the internal data structure of the list are made. Let’s update it to store the added element:

@Override
public boolean add(E element) {
    internal = new Object[] { element };
    return false;
}

Our test still fails since the isEmpty method hasn’t been enhanced. Let’s do that:

@Override
public boolean isEmpty() {
    if (internal.length != 0) {
        return false;
    } else {
        return true;
    }
}

The non-empty test passes at this point.

4.3. Refactoring

Both test cases we’ve seen so far pass, but the code of the isEmpty method could be more elegant.

Let’s refactor it:

@Override
public boolean isEmpty() {
    return internal.length == 0;
}

We can see that tests pass, so the implementation of the isEmpty method is complete now.

5. The size Method

This is our starting implementation of the size method enabling the CustomList class to compile:

@Override
public int size() {
    return 0;
}

5.1. The First Cycle

Using the existing add method, we can create the first test for the size method, verifying that the size of a list with a single element is 1:

@Test
public void givenListWithAnElement_whenSize_thenOneIsReturned() {
    List<Object> list = new CustomList<>();
    list.add(null);

    assertEquals(1, list.size());
}

The test fails as the size method is returning 0. Let’s make it pass with a new implementation:

@Override
public int size() {
    if (isEmpty()) {
        return 0;
    } else {
        return internal.length;
    }
}

5.2. Refactoring

We can refactor the size method to make it more elegant:

@Override
public int size() {
    return internal.length;
}

The implementation of this method is now complete.

6. The get Method

Here’s the starting implementation of get:

@Override
public E get(int index) {
    return null;
}

6.1. The First Cycle

Let’s take a look at the first test for this method, which verifies the value of the single element in the list:

@Test
public void givenListWithAnElement_whenGet_thenThatElementIsReturned() {
    List<Object> list = new CustomList<>();
    list.add("baeldung");
    Object element = list.get(0);

    assertEquals("baeldung", element);
}

The test will pass with this implementation of the get method:

@Override
public E get(int index) {
    return (E) internal[0];
}

6.2. Improvement

Usually, we’d add more tests before making additional improvements to the get method. Those tests would need other methods of the List interface to implement proper assertions.

However, these other methods aren’t mature enough, yet, so we break the TDD cycle and create a complete implementation of the get method, which is, in fact, not very hard.

It’s easy to imagine that get must extract an element from the internal array at the specified location using the index parameter:

@Override
public E get(int index) {
    return (E) internal[index];
}

7. The add Method

This is the add method we created in section 4:

@Override
public boolean add(E element) {
    internal = new Object[] { element };
    return false;
}

7.1. The First Cycle

The following is a simple test that verifies the return value of add:

@Test
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
    List<Object> list = new CustomList<>();
    boolean succeeded = list.add(null);

    assertTrue(succeeded);
}

We must modify the add method to return true for the test to pass:

@Override
public boolean add(E element) {
    internal = new Object[] { element };
    return true;
}

Although the test passes, the add method doesn’t cover all cases yet. If we add a second element to the list, the existing element will be lost.

7.2. The Second Cycle

Here’s another test adding the requirement that the list can contain more than one element:

@Test
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
    List<Object> list = new CustomList<>();
    list.add("baeldung");
    list.add(".com");
    Object element1 = list.get(0);
    Object element2 = list.get(1);

    assertEquals("baeldung", element1);
    assertEquals(".com", element2);
}

The test will fail since the add method in its current form doesn’t allow more than one element to be added.

Let’s change the implementation code:

@Override
public boolean add(E element) {
    Object[] temp = Arrays.copyOf(internal, internal.length + 1);
    temp[internal.length] = element;
    internal = temp;
    return true;
}

The implementation is elegant enough, hence we don’t need to refactor it.

8. Conclusion

This tutorial went through a test-driven development process to create part of a custom List implementation. Using TDD, we can implement requirements step by step, while keeping the test coverage at a very high level. Also, the implementation is guaranteed to be testable, since it was created to make the tests pass.

Note that the custom class created in this article is just used for demonstration purposes and should not be adopted in a real-world project.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)