Unleash The True Potential Of JUnit5 And B.D.D.

Emanuel Trandafir
Javarevisited
Published in
7 min readDec 5, 2022

--

Let’s write some JUnit5 tests in a B.D.D. (Behaviour-Driven Development) style. Hands-on, beginner-friendly article.

image generated on https://imgflip.com/

1. Overview

In this article, we’ll discuss some interesting features of JUnit5 that allow us to write tests in a BDD (Behaviour-Driven Development) style.

For the code examples in this article, we’ll implement a very simple BMI calculator. After that, we’ll see how to leverage JUnit5’s @ParameterizedTest, @CsvSource, and ArgumentConverter to test many scenarios in a very declarative way.

2. BMI Calculator Implementation

Firstly, let’s look at the implementation. We’ll have a BmiCalculator class with a static method for calculating the BMI:

public class BmiCalculator {
public static BmiHealthCategory calculate(Weight weight, Height height) {
// ...
}
}

As we can see from the function’s signature, it accepts as parameters a Weight and a Height object. They are small, immutable, objects that can expose factory methods for various units of measurement:

record Height(BigDecimal valueInMeters) {
private static final BigDecimal INCH_TO_METER = BigDecimal.valueOf(0.025d);

public static Height ofMeters(double valueInMeters) {…

--

--

Emanuel Trandafir
Javarevisited

Hi, I'm Emanuel Trandafir, a Java developer from Romania. I have a strong passion for clean code, software design, and unit testing.