Exercise: Write a Custom Assertion

After you have finished this exercise, you understand how you can enforce business rules with custom assertions. Let’s start by taking a look at the system under test.

If a todo item was closed because it was finished, the closed todo item must fulfill these conditions:

  • The value of the closerId property must identify the person who closed the todo item.
  • Its resolution must be: TodoItemResolution.DONE.
  • Its status must be: TodoItemStatus.CLOSED.

The closeAsDone() method of the TodoItem class makes sure that these business rules are followed when you close a todo item because it was finished. Its source code looks as follows:

public class TodoItem {

    private Long closerId;
    private TodoItemResolution resolution;
    private String title;
    private TodoItemStatus status;

    //Getters and setters are omitted
    public void closeAsDone(Long closerId) {
        this.closerId = closerId;
        this.resolution = TodoItemResolution.DONE;
        this.status = TodoItemStatus.CLOSED;

During this exercise you will write an unit test for the closeAsDone() method of the TodoItem class. You can finish this exercise by following these steps:

1. Clone the Git repository that contains the sample applications of this course. If you have already cloned that repository, you can ignore this step.

2. Open the project found from the introduction-to-junit5/writing-assertions-with-junit5/exercises/write-assertions-for-business-rules-exercise directory with your favorite IDE.

3. Write a custom assertion with AssertJ. This assertion must verify that the closed todo item was closed because it was finished. When you implement your custom assertion, you must use soft assertions.

4. Open the TodoItemTest class that’s found from the com.cleantestautomation.junit5intro package.

5. Write the assertion which verifies that the closed todo item was closed because it was finished. You can find the relevant test method from this nested test class: CloseAsDone. Use your new custom assertion.

6. Run the tests found from the TodoItemTest class and make sure that they pass.

Remember to revert you changes after you have finished this exercise!