Master the most popular testing framework for Java, through the Learn JUnit course:
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:
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:
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:
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:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
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:
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:
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.
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:
- Writing tests β define requirements in the form of tests
- Implementing features β make the tests pass without focusing too much on the elegance of the code
- 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.
