Commit c2d1cb2c authored by ayudovin's avatar ayudovin Committed by Phillip Webb

Chain predicates in PropertyMapper when methods

Update `PropertyMapper` to correctly combine predicates when repeated
calls are made to `when` and `whenNot`. Prior to this commit, subsequent
invocations would replace the previous predicate.

Fixes gh-17225
parent 88fbc529
......@@ -50,6 +50,7 @@ import org.springframework.util.StringUtils;
* {@link Source#toInstance(Function) new instance}.
*
* @author Phillip Webb
* @author Artsiom Yudovin
* @since 2.0.0
*/
public final class PropertyMapper {
......@@ -288,7 +289,7 @@ public final class PropertyMapper {
*/
public Source<T> whenNot(Predicate<T> predicate) {
Assert.notNull(predicate, "Predicate must not be null");
return new Source<>(this.supplier, predicate.negate());
return when(predicate.negate());
}
/**
......@@ -299,7 +300,7 @@ public final class PropertyMapper {
*/
public Source<T> when(Predicate<T> predicate) {
Assert.notNull(predicate, "Predicate must not be null");
return new Source<>(this.supplier, predicate);
return new Source<>(this.supplier, (this.predicate != null) ? this.predicate.and(predicate) : predicate);
}
/**
......
......@@ -28,6 +28,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* Tests for {@link PropertyMapper}.
*
* @author Phillip Webb
* @author Artsiom Yudovin
*/
public class PropertyMapperTests {
......@@ -190,6 +191,17 @@ public class PropertyMapperTests {
assertThat(source.getCount()).isOne();
}
@Test
public void whenWhenValueNotMatchesShouldSupportChainedCalls() {
this.map.from("123").when("456"::equals).when("123"::equals).toCall(Assert::fail);
}
@Test
public void whenWhenValueMatchesShouldSupportChainedCalls() {
String result = this.map.from("123").when((s) -> s.contains("2")).when("123"::equals).toInstance(String::new);
assertThat(result).isEqualTo("123");
}
@Test
public void alwaysApplyingWhenNonNullShouldAlwaysApplyNonNullToSource() {
this.map.alwaysApplyingWhenNonNull().from(() -> null).toCall(Assert::fail);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment