Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java: Clarify JUnit test method naming exception #851

Open
mches opened this issue Aug 31, 2024 · 0 comments
Open

Java: Clarify JUnit test method naming exception #851

mches opened this issue Aug 31, 2024 · 0 comments
Labels
lang:java The Java language

Comments

@mches
Copy link

mches commented Aug 31, 2024

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.

@vapier vapier added the lang:java The Java language label Dec 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lang:java The Java language
Projects
None yet
Development

No branches or pull requests

2 participants