chapter two

2 Exploring Core JUnit

 

This chapter covers

  • Understanding the JUnit lifecycle
  • Applying in practice the work with the core JUnit classes, methods and annotations
  • Demonstrating the JUnit mechanisms

Mistakes are the portals of discovery.

—James Joyce

In chapter 1, we decided that we need a reliable and repeatable way to test our program. Our solution is to write or reuse a framework to drive test code that exercises our program API. As our program grows with new classes and new methods added to the existing classes, we need to grow our test code as well. Experience has taught us that sometimes classes interact in unexpected ways, we need to make sure that we can run all of our tests at any time, no matter what code changes took place. The question becomes, how do we run multiple test classes? How do we find out which tests passed and which ones failed?

In this chapter, we will look at how JUnit provides the functionality to answer those questions. We will begin with an overview of the core JUnit concepts – the test class, methods and annotations. We will take a detailed look at the many testing mechanisms that JUnit 5 has provided and, also, we will understand the JUnit lifecycle.

2.1   Core annotations

2.1.1   The @DisplayName annotation

2.1.2   The @Disabled annotation

2.2   Nested tests

2.3   Tagged tests

2.4   Assertions

2.5   Assumptions

2.6   Dependency injection in JUnit 5

2.7   Repeated tests

2.8   Parameterized tests

2.9   Dynamic tests

2.10   Using Hamcrest matchers

2.11   Summary