Skip to content

Commit

Permalink
Allow nullable Java Time parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
Clemens-L committed Sep 19, 2024
1 parent 6be5547 commit adb59ba
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,11 @@ class JavaTimeArgumentConverter extends AnnotationBasedArgumentConverter<JavaTim
@Override
protected Object convert(Object input, Class<?> targetClass, JavaTimeConversionPattern annotation) {
if (input == null) {
throw new ArgumentConversionException("Cannot convert null to " + targetClass.getName());
if (annotation.nullable()) {
return null;
}
throw new ArgumentConversionException(
"Cannot convert null to " + targetClass.getName() + ", consider setting 'nullable = true'");
}
TemporalQuery<?> temporalQuery = TEMPORAL_QUERIES.get(targetClass);
if (temporalQuery == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,9 @@
*/
String value();

/**
* Whether this Java Time parameter may be null or not.
*/
boolean nullable() default false;

}
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,29 @@ void throwsExceptionOnInvalidTargetType() {
assertThat(exception).hasMessage("Cannot convert to java.lang.Integer: 2017");
}

@Test
void throwsExceptionOnNullParameterWithoutNullable() {
var exception = assertThrows(ArgumentConversionException.class,
() -> convert(null, "dd.MM.yyyy", LocalDate.class));

assertThat(exception).hasMessage(
"Cannot convert null to java.time.LocalDate, consider setting 'nullable = true'");
}

@Test
void convertsNullableParameter() {
assertThat(convert(null, "dd.MM.yyyy", true, LocalDate.class)).isEqualTo(null);
}

private Object convert(Object input, String pattern, Class<?> targetClass) {
return convert(input, pattern, false, targetClass);
}

private Object convert(Object input, String pattern, boolean nullable, Class<?> targetClass) {
var converter = new JavaTimeArgumentConverter();
var annotation = mock(JavaTimeConversionPattern.class);
when(annotation.value()).thenReturn(pattern);
when(annotation.nullable()).thenReturn(nullable);

return converter.convert(input, targetClass, annotation);
}
Expand Down

0 comments on commit adb59ba

Please sign in to comment.