Exercise 1: Write Assertions for a List

After you have finished this exercise, you understand how you can write assertions for lists by using the JUnit 5 assertion API. Let’s start by taking a look at the system under test.

The TodoItemRepository interface declares one method (findAll()) which returns a list that contains all todo items which are found from the database. If the database has no todo items, this method returns an empty list.

The source code of the TodoItemRepository interface looks as follows:

import java.util.List;

interface TodoItemRepository {

    List<TodoItemListItem> findAll();
}

The TodoItemListItem class contains the information of one todo item. Its source code looks as follows:

public class TodoItemListItem {

    private Long id;
    private String title;

    //Getters and setters are omitted
}

The TodoItemService class has one method called findAll() which simply invokes the findAll() method of the TodoItemRepository interface and returns the list that’s returned by the invoked method.

The source code of the TodoItemService class looks as follows:

import java.util.List;

public class TodoItemService {

    private final TodoItemRepository repository;

    public TodoItemService(TodoItemRepository repository) {
        this.repository = repository;
    }

    public List<TodoItemListItem> findAll() {
        return repository.findAll();
    }
}

During this exercise you will write unit tests for the findAll() method of the TodoItemService class. You can finish this exercise by following these steps:

1. Open the TodoItemServiceTest class that’s found from the com.cleantestautomation.junit5intro.todoitem package.

2. Write the assertion which verifies that the system under test is working as expected when the database has no todo items. You can find the relevant test method from a nested test class called: WhenNoTodoItemsIsFound. Remember to use the JUnit 5 assertion API.

3. Write the assertions which ensure that the system under test is working as expected when two todo items are found from the database. You can find the relevant test methods from a nested test class called: WhenTwoTodoItemsAreFound. Remember to use the JUnit 5 assertion API.

4. Run the tests found from the TodoItemServiceTest class and make sure that they pass.