Exercise 1: Write Assertions for an Object or an Exception

After you have finished this exercise, you understand how you can write assertions for the properties of an object that’s returned by the system under test and you know how you can ensure that the system under throws the correct exception. Let’s start by taking a look at the system under test.

The TodoItemRepository interface declares one method (findById()) that returns an Optional object that contains the found todo item. If no todo item is found from the database, this method returns an empty Optional object.

The source code of the TodoItemRepository interface looks as follows:

import java.util.Optional;

interface TodoItemRepository {

    Optional<TodoItem> findById(Long id);
}

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

public class TodoItem {

    private Long id;
    private String title;
    private String description;

    //Getters and setters are omitted
}

The TodoItemService class has one method called findById() which queries the information of the specified todo item from the database. This method is implemented by following these steps:

  1. Find the requested todo item from the database.
  2. Return the found todo item. If no todo item is found from the database, throw a TodoItemNotFoundException.

The source code of the TodoItemService class looks as follows:

public class TodoItemService {

    private final TodoItemRepository repository;

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

    public TodoItem findById(Long id) {
        return repository.findById(id)
                .orElseThrow(
                        () -> new TodoItemNotFoundException(
                                "No todo item found with id: #" + id
                        )
                );
    }
}

During this exercise you will write unit tests for the findById() 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 assertions which verify that the system under test is working as expected when the requested todo item isn’t found. You can find the relevant test methods from a nested test class called: WhenTodoItemIsNotFound. Remember to use AssertJ.

3. Write the assertions which verify that the system under test is working as expected when the requested todo item is found. You can find the relevant test methods from a nested test test class called: WhenTodoItemIsFound. Remember to use AssertJ.

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