Exercise 2: Write Assertions for an Optional Object

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

The PersonRepository interface declares one method (findById()) which returns a Person object that contains the information of the found person. If the requested person isn’t found from the database, this method returns null.

The source code of the PersonRepository interface looks as follows:

interface PersonRepository {

    Person findById(Long id);
}

The Person class contains the information of one person. Its source code looks as follows:

public class Person {

    private Long id;
    private String name;

    //Getters and setters are omitted
}

The PersonFinder class has one method called findBy() which queries the information of the specified person from the database. This method is implemented by following these steps:

  1. Find the specified person from the database.
  2. If the specified person isn’t found from the database, return an empty Optional object.
  3. If the specified person is found from the database, return an Optional object which contains the found Person object.

The source code of the PersonFinder class looks as follows:

public class PersonFinder {

    private final PersonRepository repository;

    public PersonFinder(PersonRepository repository) {
        this.repository = repository;
    }

    public Optional<Person> findById(Long id) {
        var person = repository.findById(id);

        if (person == null) {
            return Optional.empty();
        }

        return Optional.of(person);
    }
}

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

1. Open the PersonFinderTest class that’s found from the com.cleantestautomation.junit5intro.person package.

2. Write the assertion which verifies that the system under test is working as expected when the requested person isn’t found. You can find the relevant test method from a nested test class called: WhenPersonIsNotFound. Use the JUnit 5 assertion API.

3. Write the assertions which ensure that the system under test is working as expected when the requested person is found. You can find the relevant test methods from a nested test class called: WhenPersonIsFound. Use the JUnit 5 assertion API.

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