Skip to content

@SpringConversion

@SpringConversion is an annotation that converts instances using the type conversion provided by the Spring Framework:

import io.github.scordio.junit.converters.SpringConversion;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@ParameterizedTest
@ValueSource(strings = "123, 456")
void test(@SpringConversion List<Integer> ints) {
    assertEquals(List.of(123, 456), ints);
}

The converter delegates the conversion to the DefaultConversionService, which provides a wide range of built-in converters for common Java types, including:

  • Primitives and their wrappers
  • Arrays
  • Collections (List, Set, Map, etc.)
  • Enums
  • Common value types (UUID, Currency, Locale, etc.)

Requirements

The annotation requires spring-core available in the test classpath:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring-framework.version}</version>
  <scope>test</scope>
</dependency>
testImplementation("org.springframework:spring-core:${springFrameworkVersion}")

However, declaring this dependency is generally not required in a Spring application.

Examples

The following sections demonstrate some of the possible conversions. For a complete list of supported conversions, refer to the Spring Framework reference documentation.

Array → Array

Source Type Target Declaration Example
String[] @SpringConversion int[] new String[] { "123", "456" }new int[] { 123, 456 }

Array → Collection

Source Type Target Declaration Example
int[] @SpringConversion List<Integer> new int[] { 123, 456 }List.of(123, 456)
Integer[] @SpringConversion List<Integer> new Integer[] { 123, 456 }List.of(123, 456)
String[] @SpringConversion List<Integer> new String[] { "123", "456" }List.of(123, 456)

Array → Object

Source Type Target Declaration Example
int[] @SpringConversion int new int[] { 123, 456 }123
Integer[] @SpringConversion int new Integer[] { 123, 456 }123
String[] @SpringConversion int new String[] { "123", "456" }123

Array → String

Source Type Target Declaration Example
int[] @SpringConversion String new int[] { 123, 456 }"123,456"
Integer[] @SpringConversion String new Integer[] { 123, 456 }"123,456"
String[] @SpringConversion String new String[] { "123", "456" }"123,456"

Collection → Collection

Source Type Target Declaration Example
List<String> @SpringConversion List<Integer> List.of("123", "456")List.of(123, 456)

Map → Map

Source Type Target Declaration Example
Map<String, String> @SpringConversion Map<Integer, Double> Map.of("1", "123.4", "2", "567.8")Map.of(1, 123.4, 2, 567.8)

String → Collection

Source Type Target Declaration Example
String @SpringConversion List<Integer> "123, 456"List.of(123, 456)