Two notable features in JUnit5

java

@DisplayName / @ParameterizedTest

I got a chance to use JUnit5. During the journey, I came across two impressive features:

  1. @DisplayName Annotation:

    This annotation allows you to assign descriptive and meaningful names to your tests. In JUnit 4, such custom naming was not readily available, making it harder to understand the purpose of each test case.

  2. @ParameterizedTest Annotation:

    This annotation serves as a replacement for the traditional @Test annotation. It facilitates parameterized testing, enabling you to supply a stream of arguments to your test method. This, in combination with other annotations like @MethodSource, @ValueSource, and more, offers flexible ways to provide input data to your test cases.

    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    import java.util.stream.Stream;
    import org.junit.jupiter.api.DisplayName;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.params.ParameterizedTest;
    import org.junit.jupiter.params.provider.Arguments;
    import org.junit.jupiter.params.provider.MethodSource;
    
    public class AddTest {
    
      public static int add(int a, int b) {
        return a + b;
      }
    
      @Test
      @DisplayName("test add two integers")
      void testAdd() {
        assertEquals(5, add(2, 3));
      }
    
      @ParameterizedTest
      @MethodSource("supplyInts")
      @DisplayName("test add with zero")
      void testAddZero(int a, int b) {
        assertEquals(2, add(a, b));
      }
    
      private static Stream<Arguments> supplyInts() {
        return Stream.of(Arguments.of(2, 0), Arguments.of(0, 2));
      }
    }