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
This commit is contained in:
ayudovin 2019-06-17 09:38:59 -07:00 committed by Phillip Webb
parent 88fbc529e6
commit c2d1cb2c70
2 changed files with 15 additions and 2 deletions

View File

@ -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);
}
/**

View File

@ -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);