Skip to content

Commit

Permalink
Unwrap Optional in MethodValidationAdapter
Browse files Browse the repository at this point in the history
  • Loading branch information
rstoyanchev committed Dec 21, 2023
1 parent f0add92 commit 459338f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
Expand Down Expand Up @@ -354,6 +355,10 @@ else if (containerKey != null && arg instanceof Map<?, ?> map) {
bean = map.get(containerKey);
container = map;
}
else if (arg instanceof Optional<?> optional) {
bean = optional.orElse(null);
container = optional;
}
else {
Assert.state(!node.isInIterable(), "No way to unwrap Iterable without index");
bean = arg;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
Expand Down Expand Up @@ -146,6 +147,20 @@ void fieldOfObjectPropertyOfMapValue() {
assertSingleFieldError(errors, 1, courses, null, "CS 101", "professor.name", invalidPerson.name());
}

@Test
void fieldOfObjectPropertyOfOptionalBean() {
Method method = getMethod("addOptionalCourse");
Optional<Course> optional = Optional.of(new Course("CS 101", invalidPerson, Collections.emptyList()));
Object[] args = {optional};

MethodValidationResult result =
validationAdapter.validateArguments(new MyService(), method, null, args, HINTS);

assertThat(result.getAllErrors()).hasSize(1);
ParameterErrors errors = result.getBeanResults().get(0);
assertSingleFieldError(errors, 1, optional, null, null, "professor.name", invalidPerson.name());
}

}


Expand Down Expand Up @@ -204,7 +219,7 @@ private static Method getMethod(String methodName) {
}


@SuppressWarnings("unused")
@SuppressWarnings({"unused", "OptionalUsedAsFieldOrParameterType"})
private static class MyService {

public void addCourse(@Valid Course course) {
Expand All @@ -219,6 +234,9 @@ public void addCourseArray(@Valid Course[] courses) {
public void addCourseMap(@Valid Map<String, Course> courses) {
}

public void addOptionalCourse(@Valid Optional<Course> course) {
}

@Valid
public Course getCourse(Course course) {
throw new UnsupportedOperationException();
Expand Down

0 comments on commit 459338f

Please sign in to comment.