JUnit

JUnit

JUnit is a test automation framework for the Java programming language.

When Erich and I were flying to Atlanta from Zürich, JUnit got started on the airplane. At that time our perceptions of what we had done were, we’d written a little program, it was pretty cool, but it was so small and seemingly insignificant that of course the only thing we could do with it was give it away for free.

 — Kent Beck

A test class is written to test a class or group of classes that form a module. Each test method in the test class is annotated with the @Test annotation and describes a test case. Test cases often follow the Arrange Act Assert or Given When Then structure.

The following code is taken from a resolution of the Poker Hands kata.

 1import org.junit.jupiter.api.Test;
 2
 3import java.util.List;
 4
 5import static org.junit.jupiter.api.Assertions.*;
 6
 7class HandTest {
 8
 9    @Test
10    void thisCardRanksHigherThanThatCard() {
11        assertTrue(new Card(5, Suit.CLUB).compareTo(new Card(4, Suit.CLUB)) > 0);
12    }
13
14    @Test
15    void thisCardIsEqualToThatCard() {
16        assertEquals(new Card(3, Suit.CLUB), (new Card(3, Suit.CLUB)));
17    }
18
19    @Test
20    void whenHandDoesNotFitHigherCategoryItIsHighCard() {
21        assertEquals(Hand.of(List.of(
22                new Card(2, Suit.CLUB),
23                new Card(5, Suit.HEART))), Hand.HIGH_CARD);
24    }
25
26    @Test
27    void whenTwoCardsHaveTheSameValueItIsPair() {
28        assertEquals(Hand.of(List.of(
29                new Card(2, Suit.CLUB),
30                new Card(3, Suit.CLUB),
31                new Card(2, Suit.CLUB))), Hand.PAIR);
32    }
33
34}

AssertJ

AssertJ is a Java library that provides a rich set of assertions. It improves test code readability.

Here is the above example rewritten with AssertJ:

 1import org.junit.jupiter.api.Test;
 2
 3import java.util.List;
 4
 5import static org.assertj.core.api.Assertions.assertThat;
 6
 7class HandTest {
 8
 9    @Test
10    void thisCardRanksHigherThanThatCard() {
11        assertThat(new Card(5, Suit.CLUB).compareTo(new Card(4, Suit.CLUB)))
12                .isPositive();
13    }
14
15    @Test
16    void thisCardIsEqualToThatCard() {
17        assertThat(new Card(3, Suit.CLUB).equals(new Card(3, Suit.CLUB)))
18                .isTrue();
19    }
20
21    @Test
22    void whenHandDoesNotFitHigherCategoryItIsHighCard() {
23        assertThat(Hand.of(List.of(
24                new Card(2, Suit.CLUB),
25                new Card(5, Suit.HEART))))
26                .isEqualTo(Hand.HIGH_CARD);
27    }
28
29    @Test
30    void whenTwoCardsHaveTheSameValueItIsPair() {
31        assertThat(Hand.of(List.of(
32                new Card(2, Suit.CLUB),
33                new Card(3, Suit.CLUB),
34                new Card(2, Suit.CLUB))))
35                .isEqualTo(Hand.PAIR);
36    }
37
38}