google / google/styleguide

Java: Clarify JUnit test method naming exception

Open
#851 0 comments 0 reactions 0 assignees View on GitHub
lang:java
Dominant language
HTML
Stars
39.6k
Forks
12.9k
Avg merge
42m
Merged PRs (30d)
15

Description

[Section 5.2.3](https://google.github.io/styleguide/javaguide.html#s5.2.3-method-names) of the [Java Style Guide](https://google.github.io/styleguide/javaguide.html) states

> Underscores may appear in JUnit test method names to separate logical components of the name, with each component written in [lowerCamelCase](https://google.github.io/styleguide/javaguide.html#s5.3-camel-case), 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.

```java
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 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 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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.