docs icon indicating copy to clipboard operation
docs copied to clipboard

Recipe: parametrized tests in JUnit 5

Open hobovsky opened this issue 3 years ago • 3 comments
trafficstars

import java.util.*;
import java.util.stream.*;
import java.util.function.*;

import org.junit.jupiter.api.*;
import org.junit.jupiter.params.*;
import org.junit.jupiter.params.provider.*;
import static org.junit.jupiter.api.Assertions.*;

// Values source
@ParameterizedTest
@ValueSource(strings = {"", "  "})
void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input) {
    assertTrue(Strings.isBlank(input));
}

// CSV source
@ParameterizedTest
@CsvSource({"test,TEST", "tEst,TEST", "Java,JAVA"})
void toUpperCase_ShouldGenerateTheExpectedUppercaseValue(String input, String expected) {
    String actualValue = input.toUpperCase();
    assertEquals(expected, actualValue);
}

// Generator method
@ParameterizedTest
@MethodSource("provideStringsForIsBlank")
void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input, boolean expected) {
    assertEquals(expected, Strings.isBlank(input));
}

private static Stream<Arguments> provideStringsForIsBlank() {
    return Stream.of(
      Arguments.of(null, true),
      Arguments.of("", true),
      Arguments.of("  ", true),
      Arguments.of("not blank", false)
    );
}

hobovsky avatar Feb 07 '22 12:02 hobovsky

I would suggest to add also display names:

import org.junit.jupiter.api.DisplayName;

@DisplayName("Tests with JUnit 5")
class SampleTests {

    @ParameterizedTest(name = "input: '{0}' and I expect you to return >>{1}<<")
    @DisplayName("We test some fixed Strings")
    @CsvSource({"test,TEST", "tEst,TEST"})
    void toUpperCase_ShouldGenerateTheExpectedUppercaseValue(String input, String expected) {
        String actualValue = input.toUpperCase();
        assertEquals(expected, actualValue);
    }
}

This will lead to the following output: image

Madjosz avatar Feb 07 '22 13:02 Madjosz

Finally readable parametrized tests in java...? XD

What about the order of the test methods?

Blind4Basics avatar Feb 07 '22 16:02 Blind4Basics

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SampleTests {
    @Test
    @Order(2)
    void secondTest() { ... }

    @Test
    @Order(1)
    void firstTest() { ... }
}

Other built-in possibilities are

  • ~~MethodOrderer.Alphanumeric~~ (deprecated since JUnit 5.7, but will only be removed in JUnit 6)
  • MethodOrderer.DisplayName (since 5.7, still experimental in latest 5.8.2)
  • MethodOrderer.MethodName (since 5.7, still experimental in latest 5.8.2)
  • MethodOrderer.Random

CW currently uses JUnit 5.4.0

Madjosz avatar Feb 16 '22 10:02 Madjosz