google / styleguide

Style guides for Google-originated open-source projects
https://google.github.io/styleguide/
Apache License 2.0
37.55k stars 13.3k forks source link

Java: Clarify JUnit test method naming exception #851

Open mches opened 2 months ago

mches commented 2 months ago

Section 5.2.3 of the Java Style Guide states

Underscores may appear in JUnit test method names to separate logical components of the name, with each component written in lowerCamelCase, for example transferMoney_deductsFromSource. There is no One Correct Way to name test methods.

Could you clarify whether this exception applies strictly to the methods annotated with a JUnit test annotation such as @Test, @RepeatedTest, or @ParameteriezedTest? Could it not also apply a conventionally-named method corresponding to a test annotated @ParameterizedTest @MethodSource, with no value specified for @MethodSource? In such a case, JUnit looks for a static method with the same name to provide the parameters. The IDE may even report an error if the method does not exist and offer to create a stub. Take this source for example.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.params.provider.Arguments.arguments;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class StringTest {
  static Stream<Arguments> substring_int() {
    return Stream.of(
        arguments("foo", 0, "foo"),
        arguments("foo", 1, "oo"),
        arguments("foo", 2, "o"),
        arguments("foo", 3, ""));
  }

  @ParameterizedTest
  @MethodSource
  void substring_int(String s, int beginIndex, String expected) {
    assertEquals(expected, s.substring(beginIndex));
  }

  static Stream<Arguments> substring_int_throws() {
    return Stream.of(arguments("foo", -1), arguments("foo", 4));
  }

  @ParameterizedTest
  @MethodSource
  void substring_int_throws(String s, int beginIndex) {
    assertThrows(IndexOutOfBoundsException.class, () -> s.substring(beginIndex));
  }
}

See also checkstyle/checkstyle#15429, checkstyle/checkstyle#15556, checkstyle/checkstyle#15599.