Exercise 2: Write Assertions for a Stream

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

The TagRepository interface declares one method (findUniqueTagNames()) which queries unique tag names from the database and returns a Stream that contains the found tag names. If no tags is found from the database, this method returns an empty Stream.

The source code of the TodoItemRepository interface looks as follows:

import java.util.stream.Stream;

interface TagRepository {

    Stream<String> findUniqueTagNames();
}

The TagService class has one method called findUniqueTagNames() which simply invokes the findUniqueTagNames() method of the TagRepository interface and returns the Stream that’s returned by the invoked method.

The source code of the TagService class looks as follows:

import java.util.stream.Stream;

public class TagService {

    private final TagRepository repository;

    public TagService(TagRepository repository) {
        this.repository = repository;
    }

    public Stream<String> findUniqueTagNames() {
        return repository.findUniqueTagNames();
    }
}

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

1. Open the TagServiceTest class that’s found from the com.cleantestautomation.junit5intro.tag package.

2. Write the assertion which verifies that the system under test is working as expected when no tags is found from the database. You can find the relevant test method from this nested test class: FindUniqueTagNames -> WhenNoTagsIsFound. 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 unique tags are found from the database. You can find the relevant test methods from this nested test class: FindUniqueTagNames -> WhenTwoUniqueTagsAreFound. Remember to use the JUnit 5 assertion API.

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