codewars / docs

The Codewars Docs :construction: WIP
https://docs.codewars.com
MIT License
56 stars 201 forks source link

Recipe: parametrized tests in JUnit 5 #375

Open hobovsky opened 2 years ago

hobovsky commented 2 years ago
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)
    );
}
Madjosz commented 2 years ago

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

Blind4Basics commented 2 years ago

Finally readable parametrized tests in java...? XD

What about the order of the test methods?

Madjosz commented 2 years ago
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

CW currently uses JUnit 5.4.0