I'm using JUnit 5.7.0, IntellijIDEA 2021.1.2 CE, MacOS Catalina 10.15. and don't understand the difference between
ParameterizedTest.ARGUMENTS_PLACEHOLDER
and ParameterizedTest.ARGUMENTS_WITH_NAMES_PLACEHOLDER
.
According to the javadoc ARGUMENTS_WITH_NAMES_PLACEHOLDER
deals with named arguments whereas ARGUMENTS_PLACEHOLDER
with just arguments.
The test result in IDEA for both tests looks the same:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@ParameterizedTest(name = ARGUMENTS_WITH_NAMES_PLACEHOLDER)
@CsvSource({"apple, 1", "banana, 2", "'lemon, lime', 3" })
void testWithArguments(String fruit, int rank) {
}
@ParameterizedTest(name = ARGUMENTS_PLACEHOLDER)
@CsvSource({"apple, 1", "banana, 2", "'lemon, lime', 3" })
void testWithNamedArguments(String fruit, int rank) {
}
Can anyone provide an example where these two placeholders behave differently?
For ARGUMENTS_WITH_NAMES_PLACEHOLDER
to work as expected, tests must be compiled with
-parameters
flag. Then, argument names will be 1) stored, and 2) be able to be subsequently retrieved by JUnit via reflection.
For Java projects built with Gradle, the following would enable this flag specifically for tests:
tasks.named('compileTestJava') {
options.compilerArgs += '-parameters'
}
From Java 8 documentation on javac
:
-parameters
Stores formal parameter names of constructors and methods in the generated class file so that the methodjava.lang.reflect.Executable.getParameters
from the Reflection API can retrieve them.
Naturally, JUnit is using reflection to get parameter names. For instance, check out ParameterizedTestMethodContext#getParameterName
(example from v5.7.1).