Explicit conversion

If the implicit conversion provided by JUnit 5 is not enough to cover our needs, we can use the explicit conversion capability. Thanks to this feature, we can specify a class which is going to make the custom conversion of parameter types. This custom converter is identified with the annotation @ConvertWith, referring to the argument to be converted with. Consider the following example. This parameterized test declares a custom converter for its test method argument:

package io.github.bonigarcia;

import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.concurrent.TimeUnit;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.converter.ConvertWith;
import org.junit.jupiter.params.provider.EnumSource;

class ExplicitConversionParameterizedTest {

@ParameterizedTest
@EnumSource(TimeUnit.class)
void testWithExplicitArgumentConversion(
@ConvertWith(CustomArgumentsConverter.class) String
argument) {
System.out.println("Argument " + argument + " is a type of "
+ argument.getClass());
assertNotNull(argument);
}

}

Our custom converted is a class that extends the JUnit 5's SimpleArgumentConverter. This class overrides the method convert, in which the actual conversion takes place. In the example, we simply transform whatever argument source to String.

package io.github.bonigarcia;

import org.junit.jupiter.params.converter.SimpleArgumentConverter;

public
class CustomArgumentsConverter extends SimpleArgumentConverter {

@Override
protected Object convert(Object source, Class<?> targetType) {
return String.valueOf(source);
}
}

All in all, when the test is executed, the seven enumeration constants defined in TimeUnit will be passed as arguments to the test, prior conversion to String in CustomArgumentsConverter:

Execution of parameterized tests using explicit argument conversion
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.201