In this lesson, we explore a very practical concept of the JUnit Jupiter API, which makes parameterized tests so powerful and easy to write: Argument Conversion. It allows for a limited notion of type inference when it comes to the arguments of a
@ParamterizedTest method, and it comes in three flavours.
For instance, when using the
@CsvSource annotation, all data is given as strings. The implicit conversion makes it possible to parse an integer inside of the CSV string into an actual
int variable on the test method.
The second variant of this concept, the fallback-string-to-object conversion, tries to create arbitrary types from a string representation. If your custom class can be constructed from a single string, and it has a public constructor or factory method, JUnit Jupiter can instantiate this class and pass it as a parameter to your
For all other cases, developers are given the power to write explicit converters for arguments. By annotating a parameter of a test method with
ArgumentConverter implementation can be given to the TestEngine, so that it knows how to create this particular type.
- Implicit argument conversion: Type inference for primitives, strings, Java Date/Time APIs,
Localeand more built-in types
- Fallback-string-to-object conversion: Transparently instantiate a class from a single string through its public constructor
- Explicit argument conversion: Implement an
ArgumentConverterand annotate the offending parameter with