I would like to be able to pass a class name in to a parameterized test along with a set of other data points and use these parameterized values to drive/validate a test. I typically use this in a circumstance where I want to drive a test wherein a number of possible exceptions could be thrown that should result in a similar result, with that result having a number of other parameterized input parameters.
@ParameterizedTest
@CsvSource({"OneException.class,someName,someNumber", "TwoException.class,anotherName,anotherNumber"})
void anExampleTest(Class<Throwable> clazz, String name, String number) {
when(collaborator.doTheOtherThing(name, number)).thenThrow(class);
try {
unitUnderTest.doTheThing(name, number);
}
catch (Exception ignored) {
}
assertThat(standardOutput).contains(name + " " + number);
}
As a note; my current work-around is to use a @MethodSource with a method that returns a data structure containing all of the items I need. This makes for one-off methods lying around as test fixtures, often to support a single test, with a nasty interface inside the test requiring that I perform a #get on a list or some such.
@Jitsusama Take a look at argument converters - with them you can easily map such strings to a Class instance.
Mmh, I just checked why String ~> Class does not work automatically with object factories. Turns out, Class not only has static Class<?> forName(String) (good), but also static native Class<?> getPrimitiveClass(String) (bad).
We could add static Class<?> forName(String) to the list of well-known and supported factories.
On it.
Thanks so much @nicolaiparlog and @sormuras for not only answering, but working on an even nicer solution so quickly!
Tentatively slated for 5.3 GA for _team discussion_
@sbrannen; I noticed you changed the title to indicate that a fully qualified class name is required. Is this accurate? Can I not refer to just the class name without the package hierarchy specified when the class is imported into the test module?
Since JUnit does not analyze the byte code of your compiled class, JUnit does not know what types you imported when your class was compiled. Consequently, the fully qualified class name is in fact necessary.
Thanks for the clarification @sbrannen.