Skip to content

Java: Clarify JUnit test method naming exception #851

@mches

Description

@mches

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions