Compare commits

...

14 Commits

Author SHA1 Message Date
f15178f500 Merge branch 'prepare/1.0.0' of http://zhouxy.xyz:3000/plusone/plusone-validator into prepare/1.0.0 2025-05-28 03:02:19 +08:00
83d9b05d63 test: 完成单元测试 2025-05-28 02:36:34 +08:00
d81e6acc23 fix: StringPropertyValidator 默认匹配正则时不对 null 进行校验 2025-05-28 02:36:14 +08:00
124ce63323 refactor!: 删除 ValidTools 2025-05-28 02:35:21 +08:00
ff374a049e style: 格式化代码 2025-05-28 00:00:55 +08:00
ae970cb393 feat: 重载校验规则
`BasePropertyValidator#notNull`、`CollectionPropertyValidator#notEmpty` 和 `CollectionPropertyValidator#isEmpty` 提供无参的版本
2025-05-27 23:53:58 +08:00
a28a6135a8 refactor: 优化错误提示 2025-05-27 23:46:09 +08:00
9f2ade6252 refactor: 修改类型参数名称 2025-05-27 23:33:03 +08:00
e38be765a7 refactor!: 修改字符串校验逻辑
`StringPropertyValidator` 内置的校验规则中,除了 `notEmpty` 和 `notBlank` 之外,属性值为 null 时不做校验。
2025-05-20 18:00:19 +08:00
bce648dc51 test: 完善单元测试 2025-05-20 17:41:23 +08:00
ad74a0bcd0 test: 完成 ComparablePropertyValidator 单元测试 2025-05-20 11:36:24 +08:00
dcf620b63e refactor: 修改 BaseComparablePropertyValidator#inRange 默认提示语 2025-05-20 11:36:21 +08:00
358cdaf1ad test: 完善单元测试 2025-05-20 11:36:17 +08:00
07483627a8 refactor!: StringPropertyValidator#length 使用闭区间
`StringPropertyValidator#length` 校验字符串长度在区间内时,要求字符串长度大于等于最小长度(min),小于等于最大长度(max)。
2025-05-20 11:08:52 +08:00
28 changed files with 5580 additions and 509 deletions

View File

@@ -33,12 +33,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@@ -21,19 +21,17 @@ import java.util.function.Supplier;
import com.google.common.collect.Range; import com.google.common.collect.Range;
public abstract public abstract class BaseComparablePropertyValidator<T, TProperty extends Comparable<TProperty>, TPropertyValidator extends BaseComparablePropertyValidator<T, TProperty, TPropertyValidator>>
class BaseComparablePropertyValidator<TObj, extends BasePropertyValidator<T, TProperty, TPropertyValidator> {
TProperty extends Comparable<TProperty>,
TPropertyValidator extends BaseComparablePropertyValidator<TObj, TProperty, TPropertyValidator>>
extends BasePropertyValidator<TObj, TProperty, TPropertyValidator> {
BaseComparablePropertyValidator(Function<TObj, ? extends TProperty> getter) { BaseComparablePropertyValidator(Function<T, ? extends TProperty> getter) {
super(getter); super(getter);
} }
public TPropertyValidator inRange(Range<TProperty> range) { public TPropertyValidator inRange(Range<TProperty> range) {
withRule(value -> value != null && range.contains(value), withRule(value -> value != null && range.contains(value),
convertExceptionCreator("The value is not in " + range.toString())); value -> new IllegalArgumentException(
String.format("The input must in the interval %s. You entered %s.", range, value)));
return thisObject(); return thisObject();
} }

View File

@@ -25,16 +25,13 @@ import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.Supplier; import java.util.function.Supplier;
public abstract class BasePropertyValidator< // public abstract class BasePropertyValidator<T, TProperty, TPropertyValidator extends BasePropertyValidator<T, TProperty, TPropertyValidator>> {
TObj, //
TProperty, //
TPropertyValidator extends BasePropertyValidator<TObj, TProperty, TPropertyValidator>> {
private final Function<TObj, ? extends TProperty> getter; private final Function<T, ? extends TProperty> getter;
private final List<Consumer<? super TProperty>> consumers = new LinkedList<>(); private final List<Consumer<? super TProperty>> consumers = new LinkedList<>();
protected BasePropertyValidator(Function<TObj, ? extends TProperty> getter) { protected BasePropertyValidator(Function<T, ? extends TProperty> getter) {
this.getter = getter; this.getter = getter;
} }
@@ -62,7 +59,7 @@ public abstract class BasePropertyValidator< //
return thisObject(); return thisObject();
} }
public final <T extends TObj> void validate(T obj) { public final void validate(T obj) {
for (Consumer<? super TProperty> consumer : consumers) { for (Consumer<? super TProperty> consumer : consumers) {
consumer.accept(getter.apply(obj)); consumer.accept(getter.apply(obj));
} }
@@ -74,10 +71,12 @@ public abstract class BasePropertyValidator< //
// ====== Object ====== // ====== Object ======
// ==================== // ====================
// ====== notNull ===== // ================================
// #region - notNull
// ================================
public TPropertyValidator notNull() { public TPropertyValidator notNull() {
return notNull("Value could not be null."); return notNull("The input must not be null.");
} }
public TPropertyValidator notNull(String errMsg) { public TPropertyValidator notNull(String errMsg) {
@@ -93,7 +92,17 @@ public abstract class BasePropertyValidator< //
return thisObject(); return thisObject();
} }
// ====== isNull ===== // ================================
// #endregion - notNull
// ================================
// ================================
// #region - isNull
// ================================
public TPropertyValidator isNull() {
return isNull("The input must be null.");
}
public TPropertyValidator isNull(String errMsg) { public TPropertyValidator isNull(String errMsg) {
return isNull(convertExceptionCreator(errMsg)); return isNull(convertExceptionCreator(errMsg));
@@ -108,10 +117,17 @@ public abstract class BasePropertyValidator< //
return thisObject(); return thisObject();
} }
// ===== equals ===== // ================================
// #endregion - isNull
// ================================
// ================================
// #region - equals
// ================================
public TPropertyValidator equalsThat(Object that) { public TPropertyValidator equalsThat(Object that) {
return equalsThat(that, value -> new IllegalArgumentException(String.format("(%s) 必须与 (%s) 相等", value, that))); return equalsThat(that,
value -> new IllegalArgumentException(String.format("The input must be equal to '%s'.", that)));
} }
public TPropertyValidator equalsThat(Object that, String errMsg) { public TPropertyValidator equalsThat(Object that, String errMsg) {
@@ -129,10 +145,16 @@ public abstract class BasePropertyValidator< //
return thisObject(); return thisObject();
} }
// ===== must ===== // ================================
// #endregion - equals
// ================================
// ================================
// #region - must
// ================================
public TPropertyValidator must(Predicate<? super TProperty> condition) { public TPropertyValidator must(Predicate<? super TProperty> condition) {
return must(condition, "无效的用户输入"); return must(condition, "The specified condition was not met for the input.");
} }
public TPropertyValidator must(Predicate<? super TProperty> condition, String errMsg) { public TPropertyValidator must(Predicate<? super TProperty> condition, String errMsg) {
@@ -152,10 +174,8 @@ public abstract class BasePropertyValidator< //
return thisObject(); return thisObject();
} }
// ===== must =====
public TPropertyValidator must(Collection<Predicate<? super TProperty>> conditions) { public TPropertyValidator must(Collection<Predicate<? super TProperty>> conditions) {
return must(conditions, "无效的用户输入"); return must(conditions, "The specified conditions were not met for the input.");
} }
public TPropertyValidator must(Collection<Predicate<? super TProperty>> conditions, String errMsg) { public TPropertyValidator must(Collection<Predicate<? super TProperty>> conditions, String errMsg) {
@@ -177,6 +197,10 @@ public abstract class BasePropertyValidator< //
return thisObject(); return thisObject();
} }
// ================================
// #endregion - must
// ================================
static <V> Function<V, IllegalArgumentException> convertExceptionCreator(String errMsg) { static <V> Function<V, IllegalArgumentException> convertExceptionCreator(String errMsg) {
return value -> new IllegalArgumentException(errMsg); return value -> new IllegalArgumentException(errMsg);
} }

View File

@@ -19,28 +19,28 @@ package xyz.zhouxy.plusone.validator;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
public class BoolPropertyValidator<DTO> extends BasePropertyValidator<DTO, Boolean, BoolPropertyValidator<DTO>> { public class BoolPropertyValidator<T> extends BasePropertyValidator<T, Boolean, BoolPropertyValidator<T>> {
BoolPropertyValidator(Function<DTO, Boolean> getter) { BoolPropertyValidator(Function<T, Boolean> getter) {
super(getter); super(getter);
} }
// ====== isTrueValue ====== // ====== isTrueValue ======
public BoolPropertyValidator<DTO> isTrueValue() { public BoolPropertyValidator<T> isTrueValue() {
return isTrueValue("The value must be true."); return isTrueValue("The input must be true.");
} }
public BoolPropertyValidator<DTO> isTrueValue(String errMsg) { public BoolPropertyValidator<T> isTrueValue(String errMsg) {
return isTrueValue(convertExceptionCreator(errMsg)); return isTrueValue(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> BoolPropertyValidator<DTO> isTrueValue( public <E extends RuntimeException> BoolPropertyValidator<T> isTrueValue(
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return isTrueValue(convertExceptionCreator(exceptionCreator)); return isTrueValue(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> BoolPropertyValidator<DTO> isTrueValue( public <E extends RuntimeException> BoolPropertyValidator<T> isTrueValue(
Function<Boolean, E> exceptionCreator) { Function<Boolean, E> exceptionCreator) {
withRule(Boolean.TRUE::equals, exceptionCreator); withRule(Boolean.TRUE::equals, exceptionCreator);
return this; return this;
@@ -48,27 +48,27 @@ public class BoolPropertyValidator<DTO> extends BasePropertyValidator<DTO, Boole
// ====== isFalseValue ====== // ====== isFalseValue ======
public BoolPropertyValidator<DTO> isFalseValue() { public BoolPropertyValidator<T> isFalseValue() {
return isFalseValue("The value must be false."); return isFalseValue("The input must be false.");
} }
public BoolPropertyValidator<DTO> isFalseValue(String errMsg) { public BoolPropertyValidator<T> isFalseValue(String errMsg) {
return isFalseValue(convertExceptionCreator(errMsg)); return isFalseValue(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> BoolPropertyValidator<DTO> isFalseValue( public <E extends RuntimeException> BoolPropertyValidator<T> isFalseValue(
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return isFalseValue(convertExceptionCreator(exceptionCreator)); return isFalseValue(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> BoolPropertyValidator<DTO> isFalseValue( public <E extends RuntimeException> BoolPropertyValidator<T> isFalseValue(
Function<Boolean, E> exceptionCreator) { Function<Boolean, E> exceptionCreator) {
withRule(Boolean.FALSE::equals, exceptionCreator); withRule(Boolean.FALSE::equals, exceptionCreator);
return this; return this;
} }
@Override @Override
protected BoolPropertyValidator<DTO> thisObject() { protected BoolPropertyValidator<T> thisObject() {
return this; return this;
} }
} }

View File

@@ -22,47 +22,57 @@ import java.util.function.Supplier;
import xyz.zhouxy.plusone.commons.collection.CollectionTools; import xyz.zhouxy.plusone.commons.collection.CollectionTools;
public class CollectionPropertyValidator<DTO, T> public class CollectionPropertyValidator<T, TElement>
extends BasePropertyValidator<DTO, Collection<T>, CollectionPropertyValidator<DTO, T>> { extends BasePropertyValidator<T, Collection<TElement>, CollectionPropertyValidator<T, TElement>> {
CollectionPropertyValidator(Function<DTO, Collection<T>> getter) { CollectionPropertyValidator(Function<T, Collection<TElement>> getter) {
super(getter); super(getter);
} }
// ====== notEmpty ===== // ====== notEmpty =====
public CollectionPropertyValidator<DTO, T> notEmpty(String errMsg) { public CollectionPropertyValidator<T, TElement> notEmpty() {
return notEmpty("The input must not be empty.");
}
public CollectionPropertyValidator<T, TElement> notEmpty(String errMsg) {
return notEmpty(convertExceptionCreator(errMsg)); return notEmpty(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> CollectionPropertyValidator<DTO, T> notEmpty(Supplier<E> exceptionCreator) { public <E extends RuntimeException> CollectionPropertyValidator<T, TElement> notEmpty(
Supplier<E> exceptionCreator) {
return notEmpty(convertExceptionCreator(exceptionCreator)); return notEmpty(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> CollectionPropertyValidator<DTO, T> notEmpty( public <E extends RuntimeException> CollectionPropertyValidator<T, TElement> notEmpty(
Function<Collection<T>, E> exceptionCreator) { Function<Collection<TElement>, E> exceptionCreator) {
withRule(CollectionTools::isNotEmpty, exceptionCreator); withRule(CollectionTools::isNotEmpty, exceptionCreator);
return this; return this;
} }
// ====== isEmpty ===== // ====== isEmpty =====
public CollectionPropertyValidator<DTO, T> isEmpty(String errMsg) { public CollectionPropertyValidator<T, TElement> isEmpty() {
return isEmpty("The input must be empty.");
}
public CollectionPropertyValidator<T, TElement> isEmpty(String errMsg) {
return isEmpty(convertExceptionCreator(errMsg)); return isEmpty(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> CollectionPropertyValidator<DTO, T> isEmpty(Supplier<E> exceptionCreator) { public <E extends RuntimeException> CollectionPropertyValidator<T, TElement> isEmpty(
Supplier<E> exceptionCreator) {
return isEmpty(convertExceptionCreator(exceptionCreator)); return isEmpty(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> CollectionPropertyValidator<DTO, T> isEmpty( public <E extends RuntimeException> CollectionPropertyValidator<T, TElement> isEmpty(
Function<Collection<T>, E> exceptionCreator) { Function<Collection<TElement>, E> exceptionCreator) {
withRule(CollectionTools::isEmpty, exceptionCreator); withRule(CollectionTools::isEmpty, exceptionCreator);
return this; return this;
} }
@Override @Override
protected CollectionPropertyValidator<DTO, T> thisObject() { protected CollectionPropertyValidator<T, TElement> thisObject() {
return this; return this;
} }
} }

View File

@@ -18,15 +18,15 @@ package xyz.zhouxy.plusone.validator;
import java.util.function.Function; import java.util.function.Function;
public class ComparablePropertyValidator<TObj, TProperty extends Comparable<TProperty>> public class ComparablePropertyValidator<T, TProperty extends Comparable<TProperty>>
extends BaseComparablePropertyValidator<TObj, TProperty, ComparablePropertyValidator<TObj, TProperty>> { extends BaseComparablePropertyValidator<T, TProperty, ComparablePropertyValidator<T, TProperty>> {
ComparablePropertyValidator(Function<TObj, ? extends TProperty> getter) { ComparablePropertyValidator(Function<T, ? extends TProperty> getter) {
super(getter); super(getter);
} }
@Override @Override
protected ComparablePropertyValidator<TObj, TProperty> thisObject() { protected ComparablePropertyValidator<T, TProperty> thisObject() {
return this; return this;
} }
} }

View File

@@ -19,10 +19,10 @@ package xyz.zhouxy.plusone.validator;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
public class DoublePropertyValidator<DTO> public class DoublePropertyValidator<T>
extends BaseComparablePropertyValidator<DTO, Double, DoublePropertyValidator<DTO>> { extends BaseComparablePropertyValidator<T, Double, DoublePropertyValidator<T>> {
DoublePropertyValidator(Function<DTO, Double> getter) { DoublePropertyValidator(Function<T, Double> getter) {
super(getter); super(getter);
} }
@@ -30,20 +30,21 @@ public class DoublePropertyValidator<DTO>
// #region - greater than // #region - greater than
// ================================ // ================================
public DoublePropertyValidator<DTO> gt(double min) { public DoublePropertyValidator<T> gt(double min) {
return gt(min, String.format("The value should be greater than %s", min)); return gt(min, () -> new IllegalArgumentException(
String.format("The input must be greater than '%s'.", min)));
} }
public DoublePropertyValidator<DTO> gt(double min, String errMsg) { public DoublePropertyValidator<T> gt(double min, String errMsg) {
return gt(min, convertExceptionCreator(errMsg)); return gt(min, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> gt( public <E extends RuntimeException> DoublePropertyValidator<T> gt(
double min, Supplier<E> exceptionCreator) { double min, Supplier<E> exceptionCreator) {
return gt(min, convertExceptionCreator(exceptionCreator)); return gt(min, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> gt( public <E extends RuntimeException> DoublePropertyValidator<T> gt(
double min, Function<Double, E> exceptionCreator) { double min, Function<Double, E> exceptionCreator) {
withRule(value -> (value != null && value > min), exceptionCreator); withRule(value -> (value != null && value > min), exceptionCreator);
return this; return this;
@@ -57,20 +58,21 @@ public class DoublePropertyValidator<DTO>
// #region - greater than or equal to // #region - greater than or equal to
// ================================ // ================================
public DoublePropertyValidator<DTO> ge(double min) { public DoublePropertyValidator<T> ge(double min) {
return ge(min, String.format("The value should be greater than or equal to %s", min)); return ge(min, () -> new IllegalArgumentException(
String.format("The input must be greater than or equal to '%s'.", min)));
} }
public DoublePropertyValidator<DTO> ge(double min, String errMsg) { public DoublePropertyValidator<T> ge(double min, String errMsg) {
return ge(min, convertExceptionCreator(errMsg)); return ge(min, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> ge( public <E extends RuntimeException> DoublePropertyValidator<T> ge(
double min, Supplier<E> exceptionCreator) { double min, Supplier<E> exceptionCreator) {
return ge(min, convertExceptionCreator(exceptionCreator)); return ge(min, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> ge( public <E extends RuntimeException> DoublePropertyValidator<T> ge(
double min, Function<Double, E> exceptionCreator) { double min, Function<Double, E> exceptionCreator) {
withRule(value -> (value != null && value >= min), exceptionCreator); withRule(value -> (value != null && value >= min), exceptionCreator);
return this; return this;
@@ -84,20 +86,21 @@ public class DoublePropertyValidator<DTO>
// #region - less than // #region - less than
// ================================ // ================================
public DoublePropertyValidator<DTO> lt(double max) { public DoublePropertyValidator<T> lt(double max) {
return lt(max, String.format("The value should be less than %s", max)); return lt(max, () -> new IllegalArgumentException(
String.format("The input must be less than '%s'.", max)));
} }
public DoublePropertyValidator<DTO> lt(double max, String errMsg) { public DoublePropertyValidator<T> lt(double max, String errMsg) {
return lt(max, convertExceptionCreator(errMsg)); return lt(max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> lt( public <E extends RuntimeException> DoublePropertyValidator<T> lt(
double max, Supplier<E> exceptionCreator) { double max, Supplier<E> exceptionCreator) {
return lt(max, convertExceptionCreator(exceptionCreator)); return lt(max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> lt( public <E extends RuntimeException> DoublePropertyValidator<T> lt(
double max, Function<Double, E> exceptionCreator) { double max, Function<Double, E> exceptionCreator) {
withRule(value -> (value != null && value < max), exceptionCreator); withRule(value -> (value != null && value < max), exceptionCreator);
return this; return this;
@@ -111,20 +114,21 @@ public class DoublePropertyValidator<DTO>
// #region - less than or equal to // #region - less than or equal to
// ================================ // ================================
public DoublePropertyValidator<DTO> le(double max) { public DoublePropertyValidator<T> le(double max) {
return le(max, String.format("The value should be less than or equal to %s", max)); return le(max, () -> new IllegalArgumentException(
String.format("The input must be less than or equal to '%s'.", max)));
} }
public DoublePropertyValidator<DTO> le(double max, String errMsg) { public DoublePropertyValidator<T> le(double max, String errMsg) {
return le(max, convertExceptionCreator(errMsg)); return le(max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> le( public <E extends RuntimeException> DoublePropertyValidator<T> le(
double max, Supplier<E> exceptionCreator) { double max, Supplier<E> exceptionCreator) {
return le(max, convertExceptionCreator(exceptionCreator)); return le(max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> DoublePropertyValidator<DTO> le( public <E extends RuntimeException> DoublePropertyValidator<T> le(
double max, Function<Double, E> exceptionCreator) { double max, Function<Double, E> exceptionCreator) {
withRule(value -> (value != null && value <= max), exceptionCreator); withRule(value -> (value != null && value <= max), exceptionCreator);
return this; return this;
@@ -135,7 +139,7 @@ public class DoublePropertyValidator<DTO>
// ================================ // ================================
@Override @Override
protected DoublePropertyValidator<DTO> thisObject() { protected DoublePropertyValidator<T> thisObject() {
return this; return this;
} }
} }

View File

@@ -19,10 +19,10 @@ package xyz.zhouxy.plusone.validator;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
public class IntPropertyValidator<DTO> public class IntPropertyValidator<T>
extends BaseComparablePropertyValidator<DTO, Integer, IntPropertyValidator<DTO>> { extends BaseComparablePropertyValidator<T, Integer, IntPropertyValidator<T>> {
IntPropertyValidator(Function<DTO, Integer> getter) { IntPropertyValidator(Function<T, Integer> getter) {
super(getter); super(getter);
} }
@@ -30,20 +30,21 @@ public class IntPropertyValidator<DTO>
// #region - greater than // #region - greater than
// ================================ // ================================
public IntPropertyValidator<DTO> gt(int min) { public IntPropertyValidator<T> gt(int min) {
return gt(min, String.format("The value should be greater than %d", min)); return gt(min, () -> new IllegalArgumentException(
String.format("The input must be greater than '%d'.", min)));
} }
public IntPropertyValidator<DTO> gt(int min, String errMsg) { public IntPropertyValidator<T> gt(int min, String errMsg) {
return gt(min, convertExceptionCreator(errMsg)); return gt(min, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> gt( public <E extends RuntimeException> IntPropertyValidator<T> gt(
int min, Supplier<E> exceptionCreator) { int min, Supplier<E> exceptionCreator) {
return gt(min, convertExceptionCreator(exceptionCreator)); return gt(min, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> gt( public <E extends RuntimeException> IntPropertyValidator<T> gt(
int min, Function<Integer, E> exceptionCreator) { int min, Function<Integer, E> exceptionCreator) {
withRule(value -> (value != null && value > min), exceptionCreator); withRule(value -> (value != null && value > min), exceptionCreator);
return this; return this;
@@ -57,20 +58,21 @@ public class IntPropertyValidator<DTO>
// #region - greater than or equal to // #region - greater than or equal to
// ================================ // ================================
public IntPropertyValidator<DTO> ge(int min) { public IntPropertyValidator<T> ge(int min) {
return ge(min, String.format("The value should be greater than or equal to %d", min)); return ge(min, () -> new IllegalArgumentException(
String.format("The input must be greater than or equal to '%d'.", min)));
} }
public IntPropertyValidator<DTO> ge(int min, String errMsg) { public IntPropertyValidator<T> ge(int min, String errMsg) {
return ge(min, convertExceptionCreator(errMsg)); return ge(min, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> ge( public <E extends RuntimeException> IntPropertyValidator<T> ge(
int min, Supplier<E> exceptionCreator) { int min, Supplier<E> exceptionCreator) {
return ge(min, convertExceptionCreator(exceptionCreator)); return ge(min, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> ge( public <E extends RuntimeException> IntPropertyValidator<T> ge(
int min, Function<Integer, E> exceptionCreator) { int min, Function<Integer, E> exceptionCreator) {
withRule(value -> (value != null && value >= min), exceptionCreator); withRule(value -> (value != null && value >= min), exceptionCreator);
return this; return this;
@@ -84,20 +86,21 @@ public class IntPropertyValidator<DTO>
// #region - less than // #region - less than
// ================================ // ================================
public IntPropertyValidator<DTO> lt(int max) { public IntPropertyValidator<T> lt(int max) {
return lt(max, String.format("The value should be less than %d", max)); return lt(max, () -> new IllegalArgumentException(
String.format("The input must be less than '%d'.", max)));
} }
public IntPropertyValidator<DTO> lt(int max, String errMsg) { public IntPropertyValidator<T> lt(int max, String errMsg) {
return lt(max, convertExceptionCreator(errMsg)); return lt(max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> lt( public <E extends RuntimeException> IntPropertyValidator<T> lt(
int max, Supplier<E> exceptionCreator) { int max, Supplier<E> exceptionCreator) {
return lt(max, convertExceptionCreator(exceptionCreator)); return lt(max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> lt( public <E extends RuntimeException> IntPropertyValidator<T> lt(
int max, Function<Integer, E> exceptionCreator) { int max, Function<Integer, E> exceptionCreator) {
withRule(value -> (value != null && value < max), exceptionCreator); withRule(value -> (value != null && value < max), exceptionCreator);
return this; return this;
@@ -111,20 +114,21 @@ public class IntPropertyValidator<DTO>
// #region - less than or equal to // #region - less than or equal to
// ================================ // ================================
public IntPropertyValidator<DTO> le(int max) { public IntPropertyValidator<T> le(int max) {
return le(max, String.format("The value should be less than or equal to %d", max)); return le(max, () -> new IllegalArgumentException(
String.format("The input must be less than or equal to '%d'.", max)));
} }
public IntPropertyValidator<DTO> le(int max, String errMsg) { public IntPropertyValidator<T> le(int max, String errMsg) {
return le(max, convertExceptionCreator(errMsg)); return le(max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> le( public <E extends RuntimeException> IntPropertyValidator<T> le(
int max, Supplier<E> exceptionCreator) { int max, Supplier<E> exceptionCreator) {
return le(max, convertExceptionCreator(exceptionCreator)); return le(max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> IntPropertyValidator<DTO> le( public <E extends RuntimeException> IntPropertyValidator<T> le(
int max, Function<Integer, E> exceptionCreator) { int max, Function<Integer, E> exceptionCreator) {
withRule(value -> (value != null && value <= max), exceptionCreator); withRule(value -> (value != null && value <= max), exceptionCreator);
return this; return this;
@@ -135,7 +139,7 @@ public class IntPropertyValidator<DTO>
// ================================ // ================================
@Override @Override
protected IntPropertyValidator<DTO> thisObject() { protected IntPropertyValidator<T> thisObject() {
return this; return this;
} }
} }

View File

@@ -19,10 +19,10 @@ package xyz.zhouxy.plusone.validator;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
public class LongPropertyValidator<DTO> public class LongPropertyValidator<T>
extends BaseComparablePropertyValidator<DTO, Long, LongPropertyValidator<DTO>> { extends BaseComparablePropertyValidator<T, Long, LongPropertyValidator<T>> {
LongPropertyValidator(Function<DTO, Long> getter) { LongPropertyValidator(Function<T, Long> getter) {
super(getter); super(getter);
} }
@@ -30,20 +30,21 @@ public class LongPropertyValidator<DTO>
// #region - greater than // #region - greater than
// ================================ // ================================
public LongPropertyValidator<DTO> gt(long min) { public LongPropertyValidator<T> gt(long min) {
return gt(min, String.format("The value should be greater than %d", min)); return gt(min, () -> new IllegalArgumentException(
String.format("The input must be greater than '%d'.", min)));
} }
public LongPropertyValidator<DTO> gt(long min, String errMsg) { public LongPropertyValidator<T> gt(long min, String errMsg) {
return gt(min, convertExceptionCreator(errMsg)); return gt(min, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> gt( public <E extends RuntimeException> LongPropertyValidator<T> gt(
long min, Supplier<E> exceptionCreator) { long min, Supplier<E> exceptionCreator) {
return gt(min, convertExceptionCreator(exceptionCreator)); return gt(min, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> gt( public <E extends RuntimeException> LongPropertyValidator<T> gt(
long min, Function<Long, E> exceptionCreator) { long min, Function<Long, E> exceptionCreator) {
withRule(value -> (value != null && value > min), exceptionCreator); withRule(value -> (value != null && value > min), exceptionCreator);
return this; return this;
@@ -57,20 +58,21 @@ public class LongPropertyValidator<DTO>
// #region - greater than or equal to // #region - greater than or equal to
// ================================ // ================================
public LongPropertyValidator<DTO> ge(long min) { public LongPropertyValidator<T> ge(long min) {
return ge(min, String.format("The value should be greater than or equal to %d", min)); return ge(min, () -> new IllegalArgumentException(
String.format("The input must be greater than or equal to '%d'.", min)));
} }
public LongPropertyValidator<DTO> ge(long min, String errMsg) { public LongPropertyValidator<T> ge(long min, String errMsg) {
return ge(min, convertExceptionCreator(errMsg)); return ge(min, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> ge( public <E extends RuntimeException> LongPropertyValidator<T> ge(
long min, Supplier<E> exceptionCreator) { long min, Supplier<E> exceptionCreator) {
return ge(min, convertExceptionCreator(exceptionCreator)); return ge(min, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> ge( public <E extends RuntimeException> LongPropertyValidator<T> ge(
long min, Function<Long, E> exceptionCreator) { long min, Function<Long, E> exceptionCreator) {
withRule(value -> (value != null && value >= min), exceptionCreator); withRule(value -> (value != null && value >= min), exceptionCreator);
return this; return this;
@@ -84,20 +86,21 @@ public class LongPropertyValidator<DTO>
// #region - less than // #region - less than
// ================================ // ================================
public LongPropertyValidator<DTO> lt(long max) { public LongPropertyValidator<T> lt(long max) {
return lt(max, String.format("The value should be less than %d", max)); return lt(max, () -> new IllegalArgumentException(
String.format("The input must be less than '%d'.", max)));
} }
public LongPropertyValidator<DTO> lt(long max, String errMsg) { public LongPropertyValidator<T> lt(long max, String errMsg) {
return lt(max, convertExceptionCreator(errMsg)); return lt(max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> lt( public <E extends RuntimeException> LongPropertyValidator<T> lt(
long max, Supplier<E> exceptionCreator) { long max, Supplier<E> exceptionCreator) {
return lt(max, convertExceptionCreator(exceptionCreator)); return lt(max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> lt( public <E extends RuntimeException> LongPropertyValidator<T> lt(
long max, Function<Long, E> exceptionCreator) { long max, Function<Long, E> exceptionCreator) {
withRule(value -> (value != null && value < max), exceptionCreator); withRule(value -> (value != null && value < max), exceptionCreator);
return this; return this;
@@ -111,20 +114,21 @@ public class LongPropertyValidator<DTO>
// #region - less than or equal to // #region - less than or equal to
// ================================ // ================================
public LongPropertyValidator<DTO> le(long max) { public LongPropertyValidator<T> le(long max) {
return le(max, String.format("The value should be less than or equal to %d", max)); return le(max, () -> new IllegalArgumentException(
String.format("The input must be less than or equal to '%d'.", max)));
} }
public LongPropertyValidator<DTO> le(long max, String errMsg) { public LongPropertyValidator<T> le(long max, String errMsg) {
return le(max, convertExceptionCreator(errMsg)); return le(max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> le( public <E extends RuntimeException> LongPropertyValidator<T> le(
long max, Supplier<E> exceptionCreator) { long max, Supplier<E> exceptionCreator) {
return le(max, convertExceptionCreator(exceptionCreator)); return le(max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> LongPropertyValidator<DTO> le( public <E extends RuntimeException> LongPropertyValidator<T> le(
long max, Function<Long, E> exceptionCreator) { long max, Function<Long, E> exceptionCreator) {
withRule(value -> (value != null && value <= max), exceptionCreator); withRule(value -> (value != null && value <= max), exceptionCreator);
return this; return this;
@@ -135,7 +139,7 @@ public class LongPropertyValidator<DTO>
// ================================ // ================================
@Override @Override
protected LongPropertyValidator<DTO> thisObject() { protected LongPropertyValidator<T> thisObject() {
return this; return this;
} }
} }

View File

@@ -18,14 +18,15 @@ package xyz.zhouxy.plusone.validator;
import java.util.function.Function; import java.util.function.Function;
public class ObjectPropertyValidator<DTO, T> extends BasePropertyValidator<DTO, T, ObjectPropertyValidator<DTO, T>> { public class ObjectPropertyValidator<T, TProperty>
extends BasePropertyValidator<T, TProperty, ObjectPropertyValidator<T, TProperty>> {
ObjectPropertyValidator(Function<DTO, T> getter) { ObjectPropertyValidator(Function<T, TProperty> getter) {
super(getter); super(getter);
} }
@Override @Override
protected ObjectPropertyValidator<DTO, T> thisObject() { protected ObjectPropertyValidator<T, TProperty> thisObject() {
return this; return this;
} }
} }

View File

@@ -22,8 +22,6 @@ import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.google.common.base.Strings;
import xyz.zhouxy.plusone.commons.constant.PatternConsts; import xyz.zhouxy.plusone.commons.constant.PatternConsts;
import xyz.zhouxy.plusone.commons.util.AssertTools; import xyz.zhouxy.plusone.commons.util.AssertTools;
import xyz.zhouxy.plusone.commons.util.RegexTools; import xyz.zhouxy.plusone.commons.util.RegexTools;
@@ -38,9 +36,9 @@ import xyz.zhouxy.plusone.commons.util.StringTools;
* *
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a> * @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
*/ */
public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidator<DTO, String, StringPropertyValidator<DTO>> { public class StringPropertyValidator<T> extends BaseComparablePropertyValidator<T, String, StringPropertyValidator<T>> {
StringPropertyValidator(Function<DTO, String> getter) { StringPropertyValidator(Function<T, String> getter) {
super(getter); super(getter);
} }
@@ -48,20 +46,20 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #region - matches // #region - matches
// ================================ // ================================
public StringPropertyValidator<DTO> matches(Pattern regex, String errMsg) { public StringPropertyValidator<T> matches(Pattern regex, String errMsg) {
return matches(regex, convertExceptionCreator(errMsg)); return matches(regex, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matches( public <E extends RuntimeException> StringPropertyValidator<T> matches(
Pattern regex, Pattern regex,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return matches(regex, convertExceptionCreator(exceptionCreator)); return matches(regex, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matches( public <E extends RuntimeException> StringPropertyValidator<T> matches(
Pattern regex, Pattern regex,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(input -> RegexTools.matches(input, regex), exceptionCreator); withRule(input -> (input == null || RegexTools.matches(input, regex)), exceptionCreator);
return this; return this;
} }
@@ -73,37 +71,37 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #region - matchesOne // #region - matchesOne
// ================================ // ================================
public StringPropertyValidator<DTO> matchesOne(Pattern[] regexs, String errMsg) { public StringPropertyValidator<T> matchesOne(Pattern[] regexs, String errMsg) {
return matchesOne(regexs, convertExceptionCreator(errMsg)); return matchesOne(regexs, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesOne( public <E extends RuntimeException> StringPropertyValidator<T> matchesOne(
Pattern[] regexs, Pattern[] regexs,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return matchesOne(regexs, convertExceptionCreator(exceptionCreator)); return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesOne( public <E extends RuntimeException> StringPropertyValidator<T> matchesOne(
Pattern[] regexs, Pattern[] regexs,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(input -> RegexTools.matchesOne(input, regexs), exceptionCreator); withRule(input -> input == null || RegexTools.matchesOne(input, regexs), exceptionCreator);
return this; return this;
} }
public StringPropertyValidator<DTO> matchesOne(List<Pattern> regexs, String errMsg) { public StringPropertyValidator<T> matchesOne(List<Pattern> regexs, String errMsg) {
return matchesOne(regexs, convertExceptionCreator(errMsg)); return matchesOne(regexs, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesOne( public <E extends RuntimeException> StringPropertyValidator<T> matchesOne(
List<Pattern> regexs, List<Pattern> regexs,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return matchesOne(regexs, convertExceptionCreator(exceptionCreator)); return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesOne( public <E extends RuntimeException> StringPropertyValidator<T> matchesOne(
List<Pattern> regexs, List<Pattern> regexs,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(input -> RegexTools.matchesOne(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator); withRule(input -> input == null || RegexTools.matchesOne(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
return this; return this;
} }
@@ -115,37 +113,37 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #region - matchesAll // #region - matchesAll
// ================================ // ================================
public StringPropertyValidator<DTO> matchesAll(Pattern[] regexs, String errMsg) { public StringPropertyValidator<T> matchesAll(Pattern[] regexs, String errMsg) {
return matchesAll(regexs, convertExceptionCreator(errMsg)); return matchesAll(regexs, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesAll( public <E extends RuntimeException> StringPropertyValidator<T> matchesAll(
Pattern[] regexs, Pattern[] regexs,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return matchesAll(regexs, convertExceptionCreator(exceptionCreator)); return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesAll( public <E extends RuntimeException> StringPropertyValidator<T> matchesAll(
Pattern[] regexs, Pattern[] regexs,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(input -> RegexTools.matchesAll(input, regexs), exceptionCreator); withRule(input -> input == null || RegexTools.matchesAll(input, regexs), exceptionCreator);
return this; return this;
} }
public StringPropertyValidator<DTO> matchesAll(Collection<Pattern> regexs, String errMsg) { public StringPropertyValidator<T> matchesAll(Collection<Pattern> regexs, String errMsg) {
return matchesAll(regexs, convertExceptionCreator(errMsg)); return matchesAll(regexs, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesAll( public <E extends RuntimeException> StringPropertyValidator<T> matchesAll(
Collection<Pattern> regexs, Collection<Pattern> regexs,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return matchesAll(regexs, convertExceptionCreator(exceptionCreator)); return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> matchesAll( public <E extends RuntimeException> StringPropertyValidator<T> matchesAll(
Collection<Pattern> regexs, Collection<Pattern> regexs,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(input -> RegexTools.matchesAll(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator); withRule(input -> input == null || RegexTools.matchesAll(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
return this; return this;
} }
@@ -157,19 +155,19 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #region - notBlank // #region - notBlank
// ================================ // ================================
public StringPropertyValidator<DTO> notBlank() { public StringPropertyValidator<T> notBlank() {
return notBlank("This String argument must have text; it must not be null, empty, or blank"); return notBlank("The input must not be blank.");
} }
public StringPropertyValidator<DTO> notBlank(String errMsg) { public StringPropertyValidator<T> notBlank(String errMsg) {
return notBlank(convertExceptionCreator(errMsg)); return notBlank(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> notBlank(Supplier<E> exceptionCreator) { public <E extends RuntimeException> StringPropertyValidator<T> notBlank(Supplier<E> exceptionCreator) {
return notBlank(convertExceptionCreator(exceptionCreator)); return notBlank(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> notBlank( public <E extends RuntimeException> StringPropertyValidator<T> notBlank(
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(StringTools::isNotBlank, exceptionCreator); withRule(StringTools::isNotBlank, exceptionCreator);
return this; return this;
@@ -183,20 +181,20 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #region - emailAddress // #region - emailAddress
// ================================ // ================================
public StringPropertyValidator<DTO> emailAddress() { public StringPropertyValidator<T> emailAddress() {
return emailAddress("The value is not an email address."); return emailAddress("The input is not a valid email address.");
} }
public StringPropertyValidator<DTO> emailAddress(String errMsg) { public StringPropertyValidator<T> emailAddress(String errMsg) {
return emailAddress(convertExceptionCreator(errMsg)); return emailAddress(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> emailAddress( public <E extends RuntimeException> StringPropertyValidator<T> emailAddress(
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return emailAddress(convertExceptionCreator(exceptionCreator)); return emailAddress(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> emailAddress( public <E extends RuntimeException> StringPropertyValidator<T> emailAddress(
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
return matches(PatternConsts.EMAIL, exceptionCreator); return matches(PatternConsts.EMAIL, exceptionCreator);
} }
@@ -209,15 +207,19 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #region - notEmpty // #region - notEmpty
// ================================ // ================================
public StringPropertyValidator<DTO> notEmpty(String errMsg) { public StringPropertyValidator<T> notEmpty() {
return notEmpty("The input must not be empty.");
}
public StringPropertyValidator<T> notEmpty(String errMsg) {
return notEmpty(convertExceptionCreator(errMsg)); return notEmpty(convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> notEmpty(Supplier<E> exceptionCreator) { public <E extends RuntimeException> StringPropertyValidator<T> notEmpty(Supplier<E> exceptionCreator) {
return notEmpty(convertExceptionCreator(exceptionCreator)); return notEmpty(convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> notEmpty( public <E extends RuntimeException> StringPropertyValidator<T> notEmpty(
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
withRule(s -> s != null && !s.isEmpty(), exceptionCreator); withRule(s -> s != null && !s.isEmpty(), exceptionCreator);
return this; return this;
@@ -227,70 +229,48 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// #endregion - notEmpty // #endregion - notEmpty
// ================================ // ================================
// ================================
// #region - isNullOrEmpty
// ================================
public StringPropertyValidator<DTO> isNullOrEmpty(String errMsg) {
return isNullOrEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringPropertyValidator<DTO> isNullOrEmpty(Supplier<E> exceptionCreator) {
return isNullOrEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringPropertyValidator<DTO> isNullOrEmpty(
Function<String, E> exceptionCreator) {
withRule(Strings::isNullOrEmpty, exceptionCreator);
return this;
}
// ================================
// #endregion - isNullOrEmpty
// ================================
// ================================ // ================================
// #region - length // #region - length
// ================================ // ================================
public StringPropertyValidator<DTO> length(int length, String errMsg) { public StringPropertyValidator<T> length(int length, String errMsg) {
return length(length, convertExceptionCreator(errMsg)); return length(length, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> length(int length, public <E extends RuntimeException> StringPropertyValidator<T> length(int length,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return length(length, convertExceptionCreator(exceptionCreator)); return length(length, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> length(int length, public <E extends RuntimeException> StringPropertyValidator<T> length(int length,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
AssertTools.checkArgument(length >= 0, AssertTools.checkArgument(length >= 0,
"The required length must be greater than or equal to 0."); "The expected length must be greater than or equal to 0.");
withRule(s -> s != null && s.length() == length, exceptionCreator); withRule(s -> s == null || s.length() == length, exceptionCreator);
return this; return this;
} }
static boolean length(String str, int min, int max) { static boolean length(String str, int min, int max) {
if (str == null) { if (str == null) {
return false; return true;
} }
final int len = str.length(); final int len = str.length();
return len >= min && len < max; return len >= min && len <= max;
} }
public StringPropertyValidator<DTO> length(int min, int max, String errMsg) { public StringPropertyValidator<T> length(int min, int max, String errMsg) {
return length(min, max, convertExceptionCreator(errMsg)); return length(min, max, convertExceptionCreator(errMsg));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> length(int min, int max, public <E extends RuntimeException> StringPropertyValidator<T> length(int min, int max,
Supplier<E> exceptionCreator) { Supplier<E> exceptionCreator) {
return length(min, max, convertExceptionCreator(exceptionCreator)); return length(min, max, convertExceptionCreator(exceptionCreator));
} }
public <E extends RuntimeException> StringPropertyValidator<DTO> length(int min, int max, public <E extends RuntimeException> StringPropertyValidator<T> length(int min, int max,
Function<String, E> exceptionCreator) { Function<String, E> exceptionCreator) {
AssertTools.checkArgument(min >= 0, "The minimum value must be greater than equal to 0."); AssertTools.checkArgument(min >= 0, "The 'min' must be greater than or equal to 0.");
AssertTools.checkArgument(min < max, "The minimum value must be less than the maximum value."); AssertTools.checkArgument(min <= max, "The 'min' must be less than or equal to the 'max'.");
withRule(s -> length(s, min, max), exceptionCreator); withRule(s -> length(s, min, max), exceptionCreator);
return this; return this;
} }
@@ -300,7 +280,7 @@ public class StringPropertyValidator<DTO> extends BaseComparablePropertyValidato
// ================================ // ================================
@Override @Override
protected StringPropertyValidator<DTO> thisObject() { protected StringPropertyValidator<T> thisObject() {
return this; return this;
} }
} }

View File

@@ -1,45 +0,0 @@
/*
* Copyright 2022-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.validator;
/**
* 校验工具类
* <p>
* 对 {@link IValidateRequired} 的实现类对象进行校验
* </p>
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
*
* @see BaseValidator
* @see Validator
* @see IValidateRequired
*/
public class ValidTools {
private ValidTools() {
throw new IllegalStateException("Utility class");
}
public static void validate(Object obj) {
if (obj instanceof IValidateRequired) {
((IValidateRequired) obj).validate();
}
}
public static <T> void validate(T obj, BaseValidator<T> validator) {
validator.validate(obj);
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone;
import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
public class ExampleException extends RuntimeException {
private ExampleException(String message) {
super(message);
}
@StaticFactoryMethod
public static ExampleException withMessage(String message) {
return new ExampleException(message);
}
@StaticFactoryMethod
public static ExampleException withMessage(String format, Object... args) {
return new ExampleException(String.format(format, args));
}
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example;
import java.time.LocalDateTime;
import java.util.List;
/**
* 接口入参的 DTO 示例
*/
public class ExampleCommand {
private Boolean boolProperty;
private Integer intProperty;
private Long longProperty;
private Double doubleProperty;
private String stringProperty;
private LocalDateTime dateTimeProperty;
private Foo objectProperty;
private List<String> stringListProperty;
public ExampleCommand() {
}
public ExampleCommand(Boolean boolProperty, Integer intProperty, Long longProperty, Double doubleProperty,
String stringProperty, LocalDateTime dateTimeProperty, Foo objectProperty,
List<String> stringListProperty) {
this.boolProperty = boolProperty;
this.intProperty = intProperty;
this.longProperty = longProperty;
this.doubleProperty = doubleProperty;
this.stringProperty = stringProperty;
this.dateTimeProperty = dateTimeProperty;
this.objectProperty = objectProperty;
this.stringListProperty = stringListProperty;
}
public Boolean getBoolProperty() {
return boolProperty;
}
public void setBoolProperty(Boolean boolProperty) {
this.boolProperty = boolProperty;
}
public Integer getIntProperty() {
return intProperty;
}
public void setIntProperty(Integer intProperty) {
this.intProperty = intProperty;
}
public Long getLongProperty() {
return longProperty;
}
public void setLongProperty(Long longProperty) {
this.longProperty = longProperty;
}
public Double getDoubleProperty() {
return doubleProperty;
}
public void setDoubleProperty(Double doubleProperty) {
this.doubleProperty = doubleProperty;
}
public String getStringProperty() {
return stringProperty;
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
public LocalDateTime getDateTimeProperty() {
return dateTimeProperty;
}
public void setDateTimeProperty(LocalDateTime dateTimeProperty) {
this.dateTimeProperty = dateTimeProperty;
}
public Foo getObjectProperty() {
return objectProperty;
}
public void setObjectProperty(Foo objectProperty) {
this.objectProperty = objectProperty;
}
public List<String> getStringListProperty() {
return stringListProperty;
}
public void setStringListProperty(List<String> stringListProperty) {
this.stringListProperty = stringListProperty;
}
@Override
public String toString() {
return "ExampleCommand [boolProperty=" + boolProperty + ", intProperty=" + intProperty + ", longProperty="
+ longProperty + ", doubleProperty=" + doubleProperty + ", stringProperty=" + stringProperty
+ ", dateTimeProperty=" + dateTimeProperty + ", objectProperty=" + objectProperty
+ ", stringListProperty=" + stringListProperty + "]";
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example;
import java.util.Objects;
public class Foo {
private Integer intProperty;
private String stringProperty;
public Foo() {
}
public Foo(Integer intProperty, String stringProperty) {
this.intProperty = intProperty;
this.stringProperty = stringProperty;
}
public Integer getIntProperty() {
return intProperty;
}
public void setIntProperty(Integer intProperty) {
this.intProperty = intProperty;
}
public String getStringProperty() {
return stringProperty;
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
@Override
public String toString() {
return "Foo [intProperty=" + intProperty + ", stringProperty=" + stringProperty + "]";
}
@Override
public int hashCode() {
return Objects.hash(intProperty, stringProperty);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Foo))
return false;
Foo other = (Foo) obj;
return Objects.equals(intProperty, other.intProperty) && Objects.equals(stringProperty, other.stringProperty);
}
}

View File

@@ -0,0 +1,88 @@
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
class BaseValidatorTest {
@Test
void withRule_validInput() {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setStringProperty("Foo");
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
withRule(command -> Objects.equals(command.getStringProperty(), "Foo"),
"The stringProperty must be equal to 'Foo'");
withRule(command -> Objects.equals(command.getStringProperty(), "Foo"),
() -> ExampleException.withMessage("The stringProperty must be equal to 'Foo'"));
withRule(command -> Objects.equals(command.getStringProperty(), "Foo"),
str -> ExampleException.withMessage("The stringProperty must be equal to 'Foo', but is was '%s'.", str));
withRule(command -> {
final String stringProperty = command.getStringProperty();
if (!Objects.equals(stringProperty, "Foo")) {
throw ExampleException.withMessage("");
}
});
}
};
assertDoesNotThrow(() -> validator.validate(exampleCommand));
}
@Test
void withRule_invalidInput() {
ExampleCommand command = new ExampleCommand();
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
withRule(command -> Objects.equals(command.getStringProperty(), "Foo"),
"The stringProperty must be equal to 'Foo'");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The stringProperty must be equal to 'Foo'", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
withRule(command -> Objects.equals(command.getStringProperty(), "Foo"),
() -> ExampleException.withMessage("The stringProperty must be equal to 'Foo'"));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class,
() -> ruleWithExceptionSupplier.validate(command));
assertEquals("The stringProperty must be equal to 'Foo'", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
withRule(command -> Objects.equals(command.getStringProperty(), "Foo"), command -> ExampleException
.withMessage("The stringProperty must be equal to 'Foo', but is was '%s'.", command.getStringProperty()));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class,
() -> ruleWithExceptionFunction.validate(command));
assertEquals("The stringProperty must be equal to 'Foo', but is was 'null'.", specifiedException2.getMessage());
BaseValidator<ExampleCommand> rule = new BaseValidator<ExampleCommand>() {
{
withRule(command -> {
final String stringProperty = command.getStringProperty();
if (!Objects.equals(stringProperty, "Foo")) {
throw ExampleException.withMessage("");
}
});
}
};
ExampleException e = assertThrows(ExampleException.class, () -> rule.validate(command));
assertEquals("", e.getMessage());
}
}

View File

@@ -0,0 +1,385 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class BoolPropertyValidatorTests {
// ================================
// #region - isTrueValue
// ================================
@Test
void isTrueValue_trueProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty).isTrueValue();
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue("The boolProperty should be true.");
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(() -> ExampleException.withMessage("The boolProperty should be true."));
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(property -> ExampleException.withMessage(
"The boolProperty should be true, but it is `%s`", property));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(true);
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void isTrueValue_default_falseProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty).isTrueValue();
}
};
ExampleCommand command = exampleCommandWithBoolProperty(false);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals("The input must be true.", exception.getMessage());
}
@Test
void isTrueValue_message_falseProperty() {
final String message = "The boolProperty should be true.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(message);
}
};
ExampleCommand command = exampleCommandWithBoolProperty(false);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isTrueValue_exceptionSupplier_falseProperty() {
final String message = "The boolProperty should be true.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(() -> ExampleException.withMessage(message));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(false);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isTrueValue_exceptionFunction_falseProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(property -> ExampleException.withMessage(
"The boolProperty should be true, but it is `%s`", property));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(false);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals("The boolProperty should be true, but it is `false`", exception.getMessage());
}
@Test
void isTrueValue_default_nullProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty).isTrueValue();
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals("The input must be true.", exception.getMessage());
}
@Test
void isTrueValue_message_nullProperty() {
final String message = "The boolProperty should be true.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(message);
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isTrueValue_exceptionSupplier_nullProperty() {
final String message = "The boolProperty should be true.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(() -> ExampleException.withMessage(message));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isTrueValue_exceptionFunction_nullProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isTrueValue(property -> ExampleException.withMessage(
"The boolProperty should be true, but it is `%s`", property));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals("The boolProperty should be true, but it is `null`", exception.getMessage());
}
// ================================
// #endregion - isTrueValue
// ================================
// ================================
// #region - isFalseValue
// ================================
@Test
void isFalseValue_falseProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty).isFalseValue();
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue("The boolProperty should be false.");
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(() -> ExampleException.withMessage("The boolProperty should be false."));
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(property -> ExampleException.withMessage(
"The boolProperty should be false, but it is `%s`", property));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(false);
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void isFalseValue_default_trueProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty).isFalseValue();
}
};
ExampleCommand command = exampleCommandWithBoolProperty(true);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals("The input must be false.", exception.getMessage());
}
@Test
void isFalseValue_message_trueProperty() {
final String message = "The boolProperty should be false.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(message);
}
};
ExampleCommand command = exampleCommandWithBoolProperty(true);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isFalseValue_exceptionSupplier_trueProperty() {
final String message = "The boolProperty should be false.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(() -> ExampleException.withMessage(message));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(true);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isFalseValue_exceptionFunction_trueProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(property -> ExampleException.withMessage(
"The boolProperty should be false, but it is `%s`", property));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(true);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals("The boolProperty should be false, but it is `true`", exception.getMessage());
}
@Test
void isFalseValue_default_nullProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty).isFalseValue();
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals("The input must be false.", exception.getMessage());
}
@Test
void isFalseValue_message_nullProperty() {
final String message = "The boolProperty should be false.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(message);
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isFalseValue_exceptionSupplier_nullProperty() {
final String message = "The boolProperty should be false.";
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(() -> ExampleException.withMessage(message));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals(message, exception.getMessage());
}
@Test
void isFalseValue_exceptionFunction_nullProperty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isFalseValue(property -> ExampleException.withMessage(
"The boolProperty should be false, but it is `%s`", property));
}
};
ExampleCommand command = exampleCommandWithBoolProperty(null);
ExampleException exception = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals("The boolProperty should be false, but it is `null`", exception.getMessage());
}
// ================================
// #endregion - isFalseValue
// ================================
static ExampleCommand exampleCommandWithBoolProperty(Boolean boolProperty) {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setBoolProperty(boolProperty);
return exampleCommand;
}
}

View File

@@ -0,0 +1,277 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Lists;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class CollectionPropertyValidatorTests {
static final String MESSAGE_NOT_EMPTY = "The stringListProperty should not be empty.";
static final String MESSAGE_EMPTY = "The stringListProperty should be empty.";
// ================================
// #region - notEmpty
// ================================
@Test
void notEmpty_stringListIsNotEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).notEmpty();
ruleForCollection(ExampleCommand::getStringListProperty).notEmpty(MESSAGE_NOT_EMPTY);
ruleForCollection(ExampleCommand::getStringListProperty)
.notEmpty(() -> ExampleException.withMessage(MESSAGE_NOT_EMPTY));
ruleForCollection(ExampleCommand::getStringListProperty)
.notEmpty(strList -> ExampleException.withMessage(
"The stringListProperty should not be empty, but it is %s.", strList));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Lists.newArrayList("A", "B", "C"));
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void notEmpty_default_stringListIsEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).notEmpty();
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Collections.emptyList());
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> validator.validate(command));
assertEquals("The input must not be empty.", e.getMessage());
}
@Test
void notEmpty_message_stringListIsEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).notEmpty(MESSAGE_NOT_EMPTY);
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Collections.emptyList());
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_NOT_EMPTY, e.getMessage());
}
@Test
void notEmpty_exceptionSupplier_stringListIsEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty)
.notEmpty(() -> ExampleException.withMessage(MESSAGE_NOT_EMPTY));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Collections.emptyList());
ExampleException e = assertThrows(ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_NOT_EMPTY, e.getMessage());
}
@Test
void notEmpty_exceptionFunction_stringListIsEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty)
.notEmpty(strList -> ExampleException.withMessage(
"The stringListProperty should not be empty, but it is %s.", strList));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Collections.emptyList());
ExampleException e = assertThrows(ExampleException.class, () -> validator.validate(command));
assertEquals("The stringListProperty should not be empty, but it is [].", e.getMessage());
}
@Test
void notEmpty_message_stringListIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).notEmpty(MESSAGE_NOT_EMPTY);
}
};
ExampleCommand command = exampleCommandWithStringListProperty(null);
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_NOT_EMPTY, e.getMessage());
}
@Test
void notEmpty_exceptionSupplier_stringListIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty)
.notEmpty(() -> ExampleException.withMessage(MESSAGE_NOT_EMPTY));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(null);
ExampleException e = assertThrows(ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_NOT_EMPTY, e.getMessage());
}
@Test
void notEmpty_exceptionFunction_stringListIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty)
.notEmpty(strList -> ExampleException.withMessage(
"The stringListProperty should not be empty, but it is %s.", strList));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(null);
ExampleException e = assertThrows(ExampleException.class, () -> validator.validate(command));
assertEquals("The stringListProperty should not be empty, but it is null.", e.getMessage());
}
// ================================
// #endregion - notEmpty
// ================================
// ================================
// #region - isEmpty
// ================================
@Test
void isEmpty_stringListIsEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).isEmpty();
ruleForCollection(ExampleCommand::getStringListProperty).isEmpty(MESSAGE_EMPTY);
ruleForCollection(ExampleCommand::getStringListProperty)
.isEmpty(() -> ExampleException.withMessage(MESSAGE_EMPTY));
ruleForCollection(ExampleCommand::getStringListProperty)
.isEmpty(strList -> ExampleException.withMessage(
"The stringListProperty should be empty, but it is %s.", strList));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Collections.emptyList());
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void isEmpty_stringListIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).isEmpty();
ruleForCollection(ExampleCommand::getStringListProperty).isEmpty(MESSAGE_EMPTY);
ruleForCollection(ExampleCommand::getStringListProperty)
.isEmpty(() -> ExampleException.withMessage(MESSAGE_EMPTY));
ruleForCollection(ExampleCommand::getStringListProperty)
.isEmpty(strList -> ExampleException.withMessage(
"The stringListProperty should be empty, but it is %s.", strList));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(null);
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void isEmpty_default_stringListIsNotEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).isEmpty();
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Lists.newArrayList("A", "B", "C"));
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> validator.validate(command));
assertEquals("The input must be empty.", e.getMessage());
}
@Test
void isEmpty_message_stringListIsNotEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty).isEmpty(MESSAGE_EMPTY);
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Lists.newArrayList("A", "B", "C"));
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_EMPTY, e.getMessage());
}
@Test
void isEmpty_exceptionSupplier_stringListIsNotEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty)
.isEmpty(() -> ExampleException.withMessage(MESSAGE_EMPTY));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Lists.newArrayList("A", "B", "C"));
ExampleException e = assertThrows(ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_EMPTY, e.getMessage());
}
@Test
void isEmpty_exceptionFunction_stringListIsNotEmpty() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForCollection(ExampleCommand::getStringListProperty)
.isEmpty(strList -> ExampleException.withMessage(
"The stringListProperty should be empty, but it is %s.", strList));
}
};
ExampleCommand command = exampleCommandWithStringListProperty(Lists.newArrayList("A", "B", "C"));
ExampleException e = assertThrows(ExampleException.class, () -> validator.validate(command));
assertEquals("The stringListProperty should be empty, but it is [A, B, C].", e.getMessage());
}
// ================================
// #endregion - isEmpty
// ================================
static ExampleCommand exampleCommandWithStringListProperty(List<String> property) {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setStringListProperty(property);
return exampleCommand;
}
}

View File

@@ -0,0 +1,250 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDateTime;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Range;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class ComparablePropertyValidatorTests {
static final LocalDateTime MIN = LocalDate.of(2025, 5, 1).atStartOfDay();
static final LocalDateTime MAX = LocalDate.of(2025, 5, 31).atStartOfDay();
static final Range<ChronoLocalDateTime<?>> DATE_TIME_RANGE = Range.closedOpen(MIN, MAX);
static final String MESSAGE = String.format("The value should in the interval [%s,%s)", MIN, MAX);
// ================================
// #region - in the interval
// ================================
@Test
void inRange_valueIsInTheInterval() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE);
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, MESSAGE);
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, () -> ExampleException.withMessage(MESSAGE));
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, property -> ExampleException.withMessage(
"The dateTimeProperty should in the interval [%s,%s), but it is %s", MIN, MAX, property));
ruleForInt(ExampleCommand::getIntProperty)
.inRange(Range.closed(18, 60));
ruleForLong(ExampleCommand::getLongProperty)
.inRange(Range.closed(10000000000L, 20000000000L));
}
};
ExampleCommand command = exampleCommandWithComparableProperty(18, 10000000000L, MIN);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - in the interval
// ================================
// ================================
// #region - not in the interval
// ================================
@Test
void inRange_default_valueIsNotInTheInterval() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE);
}
};
ExampleCommand command = exampleCommandWithComparableProperty(18, 10000000000L, MAX);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
final String expected = String.format("The input must in the interval %s. You entered %s.", DATE_TIME_RANGE, MAX);
assertEquals(expected, e.getMessage());
}
@Test
void inRange_message_valueIsNotInTheInterval() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, MESSAGE);
}
};
ExampleCommand command = exampleCommandWithComparableProperty(18, 10000000000L, MAX);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals(MESSAGE, e.getMessage());
}
@Test
void inRange_exceptionSupplier_valueIsNotInTheInterval() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, () -> ExampleException.withMessage(MESSAGE));
}
};
ExampleCommand command = exampleCommandWithComparableProperty(18, 10000000000L, MAX);
ExampleException e = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals(MESSAGE, e.getMessage());
}
@Test
void inRange_exceptionFunction_valueIsNotInTheInterval() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, property -> ExampleException.withMessage(
"The dateTimeProperty should in the interval [%s,%s), but it is %s", MIN, MAX, property));
}
};
ExampleCommand command = exampleCommandWithComparableProperty(18, 10000000000L, MAX);
ExampleException e = assertThrows(
ExampleException.class,
() -> validator.validate(command));
final String expected = String.format("The dateTimeProperty should in the interval [%s,%s), but it is %s", MIN, MAX, MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - not in the interval
// ================================
// ================================
// #region - null
// ================================
@Test
void inRange_default_valueIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE);
}
};
ExampleCommand command = exampleCommandWithComparableProperty(null, null, null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
final String expected = String.format("The input must in the interval %s. You entered null.", DATE_TIME_RANGE);
assertEquals(expected, e.getMessage());
}
@Test
void inRange_message_valueIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, MESSAGE);
}
};
ExampleCommand command = exampleCommandWithComparableProperty(null, null, null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class,
() -> validator.validate(command));
assertEquals(MESSAGE, e.getMessage());
}
@Test
void inRange_exceptionSupplier_valueIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, () -> ExampleException.withMessage(MESSAGE));
}
};
ExampleCommand command = exampleCommandWithComparableProperty(null, null, null);
ExampleException e = assertThrows(
ExampleException.class,
() -> validator.validate(command));
assertEquals(MESSAGE, e.getMessage());
}
@Test
void inRange_exceptionFunction_valueIsNull() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForComparable(ExampleCommand::getDateTimeProperty)
.inRange(DATE_TIME_RANGE, property -> ExampleException.withMessage(
"The dateTimeProperty should in the interval [%s,%s), but it is %s", MIN, MAX, property));
}
};
ExampleCommand command = exampleCommandWithComparableProperty(null, null, null);
ExampleException e = assertThrows(
ExampleException.class,
() -> validator.validate(command));
final String expected = String.format("The dateTimeProperty should in the interval [%s,%s), but it is null", MIN, MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - null
// ================================
static ExampleCommand exampleCommandWithComparableProperty(
Integer intProperty,
Long longProperty,
LocalDateTime dateTimeProperty) {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setIntProperty(intProperty);
exampleCommand.setLongProperty(longProperty);
exampleCommand.setDateTimeProperty(dateTimeProperty);
return exampleCommand;
}
}

View File

@@ -0,0 +1,773 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class DoublePropertyValidatorTests {
static final double MIN = 1.0;
static final double MAX = 5.0;
static final String MESSAGE_GT = "The input must be greater than " + MIN;
static final String MESSAGE_GE = "The input must be greater than or equal to " + MIN;
static final String MESSAGE_LT = "The input must be less than " + MAX;
static final String MESSAGE_LE = "The input must be less than or equal to " + MAX;
// ================================
// #region - gt_validValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MIN + 0.000000000000001, Double.MAX_VALUE })
void gt_all_validValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN);
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, MESSAGE_GT);
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The doubleProperty should be greater than %s, but it is %s", MIN, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - gt_validValue
// ================================
// ================================
// #region - gt_invalidValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MIN, MIN - 0.000000000000001, Double.MIN_VALUE })
void gt_default_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than '%s'.", MIN), e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MIN, MIN - 0.000000000000001, Double.MIN_VALUE })
void gt_message_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, MESSAGE_GT);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MIN, MIN - 0.000000000000001, Double.MIN_VALUE })
void gt_exceptionSupplier_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MIN, MIN - 0.000000000000001, Double.MIN_VALUE })
void gt_exceptionFunction_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The doubleProperty should be greater than %s, but it is %s", MIN, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be greater than %s, but it is %s", MIN, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - gt_invalidValue
// ================================
// ================================
// #region - gt_null
// ================================
@Test
void gt_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than '%s'.", MIN), e.getMessage());
}
@Test
void gt_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, MESSAGE_GT);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@Test
void gt_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@Test
void gt_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The doubleProperty should be greater than %s, but it is %s", MIN, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be greater than %s, but it is null", MIN);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - gt_null
// ================================
// ================================
// #region - ge_validValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MIN, MIN + 0.000000000000001, Double.MAX_VALUE })
void ge_all_validValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN);
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, MESSAGE_GE);
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The doubleProperty should be greater than or equal to %s, but it is %s", MIN, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - ge_validValue
// ================================
// ================================
// #region - ge_invalidValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MIN - 0.000000000000001, Double.MIN_VALUE })
void ge_default_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than or equal to '%s'.", MIN), e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MIN - 0.000000000000001, Double.MIN_VALUE })
void ge_message_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, MESSAGE_GE);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MIN - 0.000000000000001, Double.MIN_VALUE })
void ge_exceptionSupplier_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MIN - 0.000000000000001, Double.MIN_VALUE })
void ge_exceptionFunction_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The doubleProperty should be greater than or equal to %s, but it is %s", MIN, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be greater than or equal to %s, but it is %s", MIN, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - ge_invalidValue
// ================================
// ================================
// #region - ge_null
// ================================
@Test
void ge_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than or equal to '%s'.", MIN), e.getMessage());
}
@Test
void ge_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, MESSAGE_GE);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@Test
void ge_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@Test
void ge_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The doubleProperty should be greater than or equal to %s, but it is %s", MIN, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be greater than or equal to %s, but it is null", MIN);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - ge_null
// ================================
// ================================
// #region - lt_validValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MAX - 0.000000000000001, Double.MIN_VALUE })
void lt_all_validValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX);
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, MESSAGE_LT);
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The doubleProperty should be less than %s, but it is %s", MAX, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - lt_validValue
// ================================
// ================================
// #region - lt_invalidValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MAX, MAX + 0.000000000000001, Double.MAX_VALUE })
void lt_default_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than '%s'.", MAX), e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MAX, MAX + 0.000000000000001, Double.MAX_VALUE })
void lt_message_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, MESSAGE_LT);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MAX, MAX + 0.000000000000001, Double.MAX_VALUE })
void lt_exceptionSupplier_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MAX, MAX + 0.000000000000001, Double.MAX_VALUE })
void lt_exceptionFunction_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The doubleProperty should be less than %s, but it is %s", MAX, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be less than %s, but it is %s", MAX, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - lt_invalidValue
// ================================
// ================================
// #region - lt_null
// ================================
@Test
void lt_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than '%s'.", MAX), e.getMessage());
}
@Test
void lt_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, MESSAGE_LT);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@Test
void lt_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@Test
void lt_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The doubleProperty should be less than %s, but it is %s", MAX, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be less than %s, but it is null", MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - lt_null
// ================================
// ================================
// #region - le_validValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MAX, MAX - 0.000000000000001, Double.MIN_VALUE })
void le_all_validValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX);
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, MESSAGE_LE);
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, property -> ExampleException.withMessage(
"The doubleProperty should be less than or equal to %s, but it is %s", MAX, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - le_validValue
// ================================
// ================================
// #region - le_invalidValue
// ================================
@ParameterizedTest
@ValueSource(doubles = { MAX + 0.000000000000001, Double.MAX_VALUE })
void le_default_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than or equal to '%s'.", MAX), e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MAX + 0.000000000000001, Double.MAX_VALUE })
void le_message_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, MESSAGE_LE);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MAX + 0.000000000000001, Double.MAX_VALUE })
void le_exceptionSupplier_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = { MAX + 0.000000000000001, Double.MAX_VALUE })
void le_exceptionFunction_invalidValue(double value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, property -> ExampleException.withMessage(
"The doubleProperty should be less than or equal to %s, but it is %s", MAX, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be less than or equal to %s, but it is %s", MAX, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - le_invalidValue
// ================================
// ================================
// #region - le_null
// ================================
@Test
void le_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than or equal to '%s'.", MAX), e.getMessage());
}
@Test
void le_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, MESSAGE_LE);
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@Test
void le_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@Test
void le_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForDouble(ExampleCommand::getDoubleProperty)
.le(MAX, property -> ExampleException.withMessage(
"The doubleProperty should be less than or equal to %s, but it is %s", MAX, property));
}
};
ExampleCommand command = exampleCommandWithDoubleProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The doubleProperty should be less than or equal to %s, but it is null", MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - le_null
// ================================
static ExampleCommand exampleCommandWithDoubleProperty(Double doubleProperty) {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setDoubleProperty(doubleProperty);
return exampleCommand;
}
}

View File

@@ -0,0 +1,772 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class IntPropertyValidatorTests {
static final int MIN = 0;
static final int MAX = 5;
static final String MESSAGE_GT = "The value should be greater than " + MIN;
static final String MESSAGE_GE = "The value should be greater than or equal to " + MIN;
static final String MESSAGE_LT = "The value should be less than " + MAX;
static final String MESSAGE_LE = "The value should be less than or equal to " + MAX;
// ================================
// #region - gt_validValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MIN + 1, Integer.MAX_VALUE })
void gt_all_validValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN);
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, MESSAGE_GT);
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The intProperty should be greater than %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - gt_validValue
// ================================
// ================================
// #region - gt_invalidValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MIN, MIN - 1, Integer.MIN_VALUE })
void gt_default_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than '%d'.", MIN), e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MIN, MIN - 1, Integer.MIN_VALUE })
void gt_message_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, MESSAGE_GT);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MIN, MIN - 1, Integer.MIN_VALUE })
void gt_exceptionSupplier_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MIN, MIN - 1, Integer.MIN_VALUE })
void gt_exceptionFunction_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The intProperty should be greater than %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be greater than %d, but it is %d", MIN, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - gt_invalidValue
// ================================
// ================================
// #region - gt_null
// ================================
@Test
void gt_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than '%d'.", MIN), e.getMessage());
}
@Test
void gt_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, MESSAGE_GT);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@Test
void gt_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@Test
void gt_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The intProperty should be greater than %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be greater than %d, but it is null", MIN);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - gt_null
// ================================
// ================================
// #region - ge_validValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MIN, MIN + 1, Integer.MAX_VALUE })
void ge_all_validValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN);
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, MESSAGE_GE);
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The intProperty should be greater than or equal to %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - ge_validValue
// ================================
// ================================
// #region - ge_invalidValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MIN - 1, Integer.MIN_VALUE })
void ge_default_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than or equal to '%d'.", MIN), e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MIN - 1, Integer.MIN_VALUE })
void ge_message_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, MESSAGE_GE);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MIN - 1, Integer.MIN_VALUE })
void ge_exceptionSupplier_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MIN - 1, Integer.MIN_VALUE })
void ge_exceptionFunction_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The intProperty should be greater than or equal to %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be greater than or equal to %d, but it is %d", MIN, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - ge_invalidValue
// ================================
// ================================
// #region - ge_null
// ================================
@Test
void ge_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than or equal to '%d'.", MIN), e.getMessage());
}
@Test
void ge_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, MESSAGE_GE);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@Test
void ge_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@Test
void ge_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The intProperty should be greater than or equal to %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be greater than or equal to %d, but it is null", MIN);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - ge_null
// ================================
// ================================
// #region - lt_validValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MAX - 1, Integer.MIN_VALUE })
void lt_all_validValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX);
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, MESSAGE_LT);
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The intProperty should be less than %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - lt_validValue
// ================================
// ================================
// #region - lt_invalidValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MAX, MAX + 1, Integer.MAX_VALUE })
void lt_default_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than '%d'.", MAX), e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MAX, MAX + 1, Integer.MAX_VALUE })
void lt_message_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, MESSAGE_LT);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MAX, MAX + 1, Integer.MAX_VALUE })
void lt_exceptionSupplier_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MAX, MAX + 1, Integer.MAX_VALUE })
void lt_exceptionFunction_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The intProperty should be less than %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be less than %d, but it is %d", MAX, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - lt_invalidValue
// ================================
// ================================
// #region - lt_null
// ================================
@Test
void lt_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than '%d'.", MAX), e.getMessage());
}
@Test
void lt_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, MESSAGE_LT);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@Test
void lt_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@Test
void lt_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The intProperty should be less than %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be less than %d, but it is null", MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - lt_null
// ================================
// ================================
// #region - le_validValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MAX, MAX - 1, Integer.MIN_VALUE })
void le_all_validValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX);
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, MESSAGE_LE);
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, property -> ExampleException.withMessage(
"The intProperty should be less than or equal to %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - le_validValue
// ================================
// ================================
// #region - le_invalidValue
// ================================
@ParameterizedTest
@ValueSource(ints = { MAX + 1, Integer.MAX_VALUE })
void le_default_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than or equal to '%d'.", MAX), e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MAX + 1, Integer.MAX_VALUE })
void le_message_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, MESSAGE_LE);
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MAX + 1, Integer.MAX_VALUE })
void le_exceptionSupplier_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@ParameterizedTest
@ValueSource(ints = { MAX + 1, Integer.MAX_VALUE })
void le_exceptionFunction_invalidValue(int value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, property -> ExampleException.withMessage(
"The intProperty should be less than or equal to %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be less than or equal to %d, but it is %d", MAX, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - le_invalidValue
// ================================
// ================================
// #region - le_null
// ================================
@Test
void le_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than or equal to '%d'.", MAX), e.getMessage());
}
@Test
void le_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, MESSAGE_LE);
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@Test
void le_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@Test
void le_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForInt(ExampleCommand::getIntProperty)
.le(MAX, property -> ExampleException.withMessage(
"The intProperty should be less than or equal to %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithIntProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The intProperty should be less than or equal to %d, but it is null", MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - le_null
// ================================
static ExampleCommand exampleCommandWithIntProperty(Integer intProperty) {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setIntProperty(intProperty);
return exampleCommand;
}
}

View File

@@ -0,0 +1,773 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class LongPropertyValidatorTests {
static final long MIN = 10000000000L;
static final long MAX = 10000000008L;
static final String MESSAGE_GT = "The value should be greater than " + MIN;
static final String MESSAGE_GE = "The value should be greater than or equal to " + MIN;
static final String MESSAGE_LT = "The value should be less than " + MAX;
static final String MESSAGE_LE = "The value should be less than or equal to " + MAX;
// ================================
// #region - gt_validValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MIN + 1, Long.MAX_VALUE })
void gt_all_validValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN);
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, MESSAGE_GT);
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The longProperty should be greater than %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - gt_validValue
// ================================
// ================================
// #region - gt_invalidValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MIN, MIN - 1, Long.MIN_VALUE })
void gt_default_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than '%d'.", MIN), e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MIN, MIN - 1, Long.MIN_VALUE })
void gt_message_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, MESSAGE_GT);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MIN, MIN - 1, Long.MIN_VALUE })
void gt_exceptionSupplier_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MIN, MIN - 1, Long.MIN_VALUE })
void gt_exceptionFunction_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The longProperty should be greater than %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be greater than %d, but it is %d", MIN, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - gt_invalidValue
// ================================
// ================================
// #region - gt_null
// ================================
@Test
void gt_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than '%d'.", MIN), e.getMessage());
}
@Test
void gt_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, MESSAGE_GT);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@Test
void gt_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, () -> ExampleException.withMessage(MESSAGE_GT));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GT, e.getMessage());
}
@Test
void gt_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.gt(MIN, property -> ExampleException.withMessage(
"The longProperty should be greater than %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be greater than %d, but it is null", MIN);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - gt_null
// ================================
// ================================
// #region - ge_validValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MIN, MIN + 1, Long.MAX_VALUE })
void ge_all_validValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN);
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, MESSAGE_GE);
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The longProperty should be greater than or equal to %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - ge_validValue
// ================================
// ================================
// #region - ge_invalidValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MIN - 1, Long.MIN_VALUE })
void ge_default_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than or equal to '%d'.", MIN), e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MIN - 1, Long.MIN_VALUE })
void ge_message_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, MESSAGE_GE);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MIN - 1, Long.MIN_VALUE })
void ge_exceptionSupplier_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MIN - 1, Long.MIN_VALUE })
void ge_exceptionFunction_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The longProperty should be greater than or equal to %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be greater than or equal to %d, but it is %d", MIN, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - ge_invalidValue
// ================================
// ================================
// #region - ge_null
// ================================
@Test
void ge_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be greater than or equal to '%d'.", MIN), e.getMessage());
}
@Test
void ge_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, MESSAGE_GE);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@Test
void ge_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, () -> ExampleException.withMessage(MESSAGE_GE));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_GE, e.getMessage());
}
@Test
void ge_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.ge(MIN, property -> ExampleException.withMessage(
"The longProperty should be greater than or equal to %d, but it is %d", MIN, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be greater than or equal to %d, but it is null", MIN);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - ge_null
// ================================
// ================================
// #region - lt_validValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MAX - 1, Long.MIN_VALUE })
void lt_all_validValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX);
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, MESSAGE_LT);
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The longProperty should be less than %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - lt_validValue
// ================================
// ================================
// #region - lt_invalidValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MAX, MAX + 1, Long.MAX_VALUE })
void lt_default_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than '%d'.", MAX), e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MAX, MAX + 1, Long.MAX_VALUE })
void lt_message_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, MESSAGE_LT);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MAX, MAX + 1, Long.MAX_VALUE })
void lt_exceptionSupplier_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MAX, MAX + 1, Long.MAX_VALUE })
void lt_exceptionFunction_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The longProperty should be less than %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be less than %d, but it is %d", MAX, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - lt_invalidValue
// ================================
// ================================
// #region - lt_null
// ================================
@Test
void lt_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than '%d'.", MAX), e.getMessage());
}
@Test
void lt_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, MESSAGE_LT);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@Test
void lt_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, () -> ExampleException.withMessage(MESSAGE_LT));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LT, e.getMessage());
}
@Test
void lt_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.lt(MAX, property -> ExampleException.withMessage(
"The longProperty should be less than %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be less than %d, but it is null", MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - lt_null
// ================================
// ================================
// #region - le_validValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MAX, MAX - 1, Long.MIN_VALUE })
void le_all_validValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX);
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, MESSAGE_LE);
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, property -> ExampleException.withMessage(
"The longProperty should be less than or equal to %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - le_validValue
// ================================
// ================================
// #region - le_invalidValue
// ================================
@ParameterizedTest
@ValueSource(longs = { MAX + 1, Long.MAX_VALUE })
void le_default_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than or equal to '%d'.", MAX), e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MAX + 1, Long.MAX_VALUE })
void le_message_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, MESSAGE_LE);
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MAX + 1, Long.MAX_VALUE })
void le_exceptionSupplier_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@ParameterizedTest
@ValueSource(longs = { MAX + 1, Long.MAX_VALUE })
void le_exceptionFunction_invalidValue(long value) {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, property -> ExampleException.withMessage(
"The longProperty should be less than or equal to %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(value);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be less than or equal to %d, but it is %d", MAX, value);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - le_invalidValue
// ================================
// ================================
// #region - le_null
// ================================
@Test
void le_default_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(String.format("The input must be less than or equal to '%d'.", MAX), e.getMessage());
}
@Test
void le_message_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, MESSAGE_LE);
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
IllegalArgumentException e = assertThrows(
IllegalArgumentException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@Test
void le_exceptionSupplier_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, () -> ExampleException.withMessage(MESSAGE_LE));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
assertEquals(MESSAGE_LE, e.getMessage());
}
@Test
void le_exceptionFunction_null() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForLong(ExampleCommand::getLongProperty)
.le(MAX, property -> ExampleException.withMessage(
"The longProperty should be less than or equal to %d, but it is %d", MAX, property));
}
};
ExampleCommand command = exampleCommandWithLongProperty(null);
ExampleException e = assertThrows(
ExampleException.class, () -> validator.validate(command));
final String expected = String.format("The longProperty should be less than or equal to %d, but it is null", MAX);
assertEquals(expected, e.getMessage());
}
// ================================
// #endregion - le_null
// ================================
static ExampleCommand exampleCommandWithLongProperty(Long longProperty) {
ExampleCommand exampleCommand = new ExampleCommand();
exampleCommand.setLongProperty(longProperty);
return exampleCommand;
}
}

View File

@@ -0,0 +1,529 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
import xyz.zhouxy.plusone.commons.util.DateTimeTools;
import xyz.zhouxy.plusone.commons.util.StringTools;
import xyz.zhouxy.plusone.example.ExampleCommand;
import xyz.zhouxy.plusone.example.Foo;
import xyz.zhouxy.plusone.validator.BaseValidator;
public class ObjectPropertyValidatorTests {
// ================================
// #region - withRule
// ================================
@Test
void withRule() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getBoolProperty)
.notNull("The boolProperty cannot be null.")
.withRule(Boolean.TRUE::equals, "The boolProperty should be true.");
ruleFor(ExampleCommand::getIntProperty)
.withRule(intProperty -> intProperty > 0, "The intProperty should be greater than 0.");
ruleFor(ExampleCommand::getLongProperty)
.withRule(longProperty -> longProperty > 0L,
() -> ExampleException.withMessage("The longProperty should be greater than 0."));
ruleFor(ExampleCommand::getDoubleProperty)
.withRule(doubleProperty -> doubleProperty > 0.00,
doubleProperty -> ExampleException.withMessage("The doubleProperty should be greater than 0, but it was: %s", doubleProperty));
ruleFor(ExampleCommand::getStringProperty)
.notNull()
.withRule(stringProperty -> stringProperty.length() > 2,
() -> ExampleException.withMessage("The length of stringProperty should be greater than 2."));
ruleFor(ExampleCommand::getDateTimeProperty)
.withRule(DateTimeTools::isFuture,
() -> new DateTimeException("The dateTimeProperty should be a future time."));
ruleFor(ExampleCommand::getObjectProperty)
.notNull("The objectProperty cannot be null.");
ruleFor(ExampleCommand::getStringListProperty)
.withRule(CollectionTools::isNotEmpty, "The stringListProperty cannot be empty.");
withRule(command -> {
Foo objectProperty = command.getObjectProperty();
if (!Objects.equals(command.getIntProperty(), objectProperty.getIntProperty())) {
throw ExampleException.withMessage("intProperty invalid.");
}
});
}
};
ExampleCommand command = new ExampleCommand(
true,
Integer.MAX_VALUE,
Long.MAX_VALUE,
Double.MAX_VALUE,
"StringValue",
LocalDateTime.now().plusDays(1),
new Foo(Integer.MAX_VALUE, "StringValue"),
Lists.newArrayList("ABC", "DEF"));
assertDoesNotThrow(() -> validator.validate(command));
}
// ================================
// #endregion - withRule
// ================================
// ================================
// #region - notNull
// ================================
@Test
void notNull_validInput() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.notNull();
ruleForInt(ExampleCommand::getIntProperty)
.notNull("The intProperty cannot be null");
ruleForLong(ExampleCommand::getLongProperty)
.notNull(() -> ExampleException.withMessage("The longProperty cannot be null"));
ruleForDouble(ExampleCommand::getDoubleProperty)
.notNull(d -> ExampleException.withMessage("The doubleProperty cannot be null, but it was %s", d));
ruleForString(ExampleCommand::getStringProperty)
.notNull();
ruleForComparable(ExampleCommand::getDateTimeProperty)
.notNull("The dateTimeProperty cannot be null");
ruleFor(ExampleCommand::getObjectProperty)
.notNull(() -> ExampleException.withMessage("The objectProperty cannot be null"));
ruleForCollection(ExampleCommand::getStringListProperty)
.notNull(d -> ExampleException.withMessage("The stringListProperty cannot be null, but it was %s", d));
}
};
ExampleCommand command = new ExampleCommand(
true,
Integer.MAX_VALUE,
Long.MAX_VALUE,
Double.MAX_VALUE,
"StringValue",
LocalDateTime.now().plusDays(1),
new Foo(Integer.MAX_VALUE, "StringValue"),
Lists.newArrayList("ABC", "DEF"));
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void notNull_invalidInput() {
ExampleCommand command = new ExampleCommand();
BaseValidator<ExampleCommand> defaultRule = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.notNull();
}
};
IllegalArgumentException eWithDefaultMessage = assertThrows(
IllegalArgumentException.class, () -> defaultRule.validate(command));
assertEquals("The input must not be null.", eWithDefaultMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.notNull("The objectProperty could not be null.");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The objectProperty could not be null.", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.notNull(() -> ExampleException.withMessage("The objectProperty could not be null."));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class, () -> ruleWithExceptionSupplier.validate(command));
assertEquals("The objectProperty could not be null.", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.notNull(str -> ExampleException.withMessage("The objectProperty could not be null, but is was " + str));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class, () -> ruleWithExceptionFunction.validate(command));
assertEquals("The objectProperty could not be null, but is was null", specifiedException2.getMessage());
}
// ================================
// #endregion - notNull
// ================================
// ================================
// #region - isNull
// ================================
@Test
void isNull_validInput() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForBool(ExampleCommand::getBoolProperty)
.isNull();
ruleForInt(ExampleCommand::getIntProperty)
.isNull("The intProperty should be null");
ruleForLong(ExampleCommand::getLongProperty)
.isNull(() -> ExampleException.withMessage("The longProperty should be null"));
ruleForDouble(ExampleCommand::getDoubleProperty)
.isNull(d -> ExampleException.withMessage("The doubleProperty should be null, but it was %s", d));
ruleForString(ExampleCommand::getStringProperty)
.isNull();
ruleForComparable(ExampleCommand::getDateTimeProperty)
.isNull("The dateTimeProperty should be null");
ruleFor(ExampleCommand::getObjectProperty)
.isNull(() -> ExampleException.withMessage("The objectProperty should be null"));
ruleForCollection(ExampleCommand::getStringListProperty)
.isNull(d -> ExampleException.withMessage("The stringListProperty should be null, but it was %s", d));
}
};
ExampleCommand command = new ExampleCommand();
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void isNull_invalidInput() {
ExampleCommand command = new ExampleCommand();
command.setObjectProperty(new Foo(Integer.MAX_VALUE, "StringValue"));
BaseValidator<ExampleCommand> ruleWithDefaultMessage = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.isNull();
}
};
IllegalArgumentException eWithDefaultMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithDefaultMessage.validate(command));
assertEquals("The input must be null.", eWithDefaultMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.isNull("The objectProperty should be null.");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The objectProperty should be null.", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.isNull(() -> ExampleException.withMessage("The objectProperty should be null."));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class, () -> ruleWithExceptionSupplier.validate(command));
assertEquals("The objectProperty should be null.", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
ruleFor(ExampleCommand::getObjectProperty)
.isNull(str -> ExampleException.withMessage("The objectProperty should be null, but is was " + str));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class, () -> ruleWithExceptionFunction.validate(command));
assertEquals("The objectProperty should be null, but is was " + command.getObjectProperty(), specifiedException2.getMessage());
}
// ================================
// #endregion - isNull
// ================================
// ================================
// #region - equalsThat
// ================================
@Test
void equalsThat_validInput() {
BaseValidator<ExampleCommand> validator = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.equalsThat("Foo")
.equalsThat("Foo", "The stringProperty should be equal to 'Foo'.")
.equalsThat("Foo", () ->
ExampleException.withMessage("The stringProperty should be equal to 'Foo'."))
.equalsThat("Foo", str ->
ExampleException.withMessage("The stringProperty should be equal to 'Foo', but is was '%s'.", str));
}
};
ExampleCommand command = new ExampleCommand();
command.setStringProperty("Foo");
assertDoesNotThrow(() -> validator.validate(command));
}
@Test
void equalsThat_invalidInput() {
ExampleCommand command = new ExampleCommand();
command.setStringProperty("Bar");
BaseValidator<ExampleCommand> defaultRule = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo");
}
};
IllegalArgumentException eWithDefaultMessage = assertThrows(
IllegalArgumentException.class, () -> defaultRule.validate(command));
assertEquals("The input must be equal to 'Foo'.", eWithDefaultMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo",
"The stringProperty should be equal to 'Foo'.");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The stringProperty should be equal to 'Foo'.", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo",
() -> ExampleException.withMessage("The stringProperty should be equal to 'Foo'."));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class, () -> ruleWithExceptionSupplier.validate(command));
assertEquals("The stringProperty should be equal to 'Foo'.", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo",
str -> ExampleException.withMessage("The stringProperty should be equal to 'Foo', but is was '%s'.", str));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class, () -> ruleWithExceptionFunction.validate(command));
assertEquals("The stringProperty should be equal to 'Foo', but is was 'Bar'.", specifiedException2.getMessage());
}
@Test
void equalsThat_nullInput() {
ExampleCommand command = new ExampleCommand();
BaseValidator<ExampleCommand> defaultRule = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo");
}
};
IllegalArgumentException eWithDefaultMessage = assertThrows(
IllegalArgumentException.class, () -> defaultRule.validate(command));
assertEquals("The input must be equal to 'Foo'.", eWithDefaultMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo",
"The stringProperty should be equal to 'Foo'.");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The stringProperty should be equal to 'Foo'.", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo",
() -> ExampleException.withMessage("The stringProperty should be equal to 'Foo'."));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class, () -> ruleWithExceptionSupplier.validate(command));
assertEquals("The stringProperty should be equal to 'Foo'.", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty).equalsThat("Foo",
str -> ExampleException.withMessage("The stringProperty should be equal to 'Foo', but is was '%s'.", str));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class, () -> ruleWithExceptionFunction.validate(command));
assertEquals("The stringProperty should be equal to 'Foo', but is was 'null'.", specifiedException2.getMessage());
}
// ================================
// #endregion - equalsThat
// ================================
// ================================
// #region - must
// ================================
@Test
void must_oneCondition_valid() {
ExampleCommand command = new ExampleCommand();
command.setStringProperty("Foo");
BaseValidator<ExampleCommand> ruleWithDefaultMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(str -> Objects.equals(str, "Foo"))
.must(str -> Objects.equals(str, "Foo"), "The stringProperty must be equal to 'Foo'.")
.must(str -> Objects.equals(str, "Foo"), () -> ExampleException.withMessage("The stringProperty must be equal to 'Foo'."))
.must(str -> Objects.equals(str, "Foo"), str -> ExampleException.withMessage("The stringProperty must be equal to 'Foo', but is was '%s'.", str));
}
};
assertDoesNotThrow(() -> ruleWithDefaultMessage.validate(command));
}
@Test
void must_oneCondition_invalid() {
ExampleCommand command = new ExampleCommand();
BaseValidator<ExampleCommand> ruleWithDefaultMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(str -> Objects.equals(str, "Foo"));
}
};
IllegalArgumentException eWithDefaultMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithDefaultMessage.validate(command));
assertEquals("The specified condition was not met for the input.", eWithDefaultMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(str -> Objects.equals(str, "Foo"),
"The stringProperty must be equal to 'Foo'.");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The stringProperty must be equal to 'Foo'.", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(str -> Objects.equals(str, "Foo"),
() -> ExampleException.withMessage("The stringProperty must be equal to 'Foo'."));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class, () -> ruleWithExceptionSupplier.validate(command));
assertEquals("The stringProperty must be equal to 'Foo'.", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(str -> Objects.equals(str, "Foo"),
str -> ExampleException.withMessage("The stringProperty must be equal to 'Foo', but is was '%s'.", str));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class, () -> ruleWithExceptionFunction.validate(command));
assertEquals("The stringProperty must be equal to 'Foo', but is was 'null'.", specifiedException2.getMessage());
}
@Test
void must_multipleConditions_valid() {
ExampleCommand command = new ExampleCommand();
command.setStringProperty("Foo");
BaseValidator<ExampleCommand> ruleWithDefaultMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")))
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")), "The stringProperty must be equal to 'Foo'.")
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")), () -> ExampleException.withMessage("The stringProperty must be equal to 'Foo'."))
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")), str -> ExampleException.withMessage("The stringProperty must be equal to 'Foo', but is was '%s'.", str));
}
};
assertDoesNotThrow(() -> ruleWithDefaultMessage.validate(command));
}
@Test
void must_multipleConditions_invalid() {
ExampleCommand command = new ExampleCommand();
command.setStringProperty("Bar");
BaseValidator<ExampleCommand> ruleWithDefaultMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")));
}
};
IllegalArgumentException eWithDefaultMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithDefaultMessage.validate(command));
assertEquals("The specified conditions were not met for the input.", eWithDefaultMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithMessage = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")),
"The stringProperty must be equal to 'Foo'.");
}
};
IllegalArgumentException eWithSpecifiedMessage = assertThrows(
IllegalArgumentException.class, () -> ruleWithMessage.validate(command));
assertEquals("The stringProperty must be equal to 'Foo'.", eWithSpecifiedMessage.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionSupplier = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")),
() -> ExampleException.withMessage("The stringProperty must be equal to 'Foo'."));
}
};
ExampleException specifiedException = assertThrows(
ExampleException.class, () -> ruleWithExceptionSupplier.validate(command));
assertEquals("The stringProperty must be equal to 'Foo'.", specifiedException.getMessage());
BaseValidator<ExampleCommand> ruleWithExceptionFunction = new BaseValidator<ExampleCommand>() {
{
ruleForString(ExampleCommand::getStringProperty)
.must(ImmutableList.of(StringTools::isNotEmpty, str -> Objects.equals(str, "Foo")),
str -> ExampleException.withMessage("The stringProperty must be equal to 'Foo', but is was '%s'.", str));
}
};
ExampleException specifiedException2 = assertThrows(
ExampleException.class, () -> ruleWithExceptionFunction.validate(command));
assertEquals("The stringProperty must be equal to 'Foo', but is was 'Bar'.", specifiedException2.getMessage());
}
// ================================
// #endregion - must
// ================================
}

View File

@@ -1,5 +1,6 @@
package xyz.zhouxy.plusone.validator.test; package xyz.zhouxy.plusone.example.validator;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static xyz.zhouxy.plusone.commons.constant.PatternConsts.*; import static xyz.zhouxy.plusone.commons.constant.PatternConsts.*;
import java.util.Arrays; import java.util.Arrays;
@@ -57,8 +58,7 @@ class ValidatorTests {
// 传入 predicate error message // 传入 predicate error message
.addRule(command -> Objects.equals(command.getPassword(), command.getPassword2()), .addRule(command -> Objects.equals(command.getPassword(), command.getPassword2()),
"两次输入的密码不一致"); "两次输入的密码不一致");
registerCommandValidator.validate(registerCommand); assertDoesNotThrow(() -> registerCommandValidator.validate(registerCommand));
System.out.println(registerCommand);
} }
/** /**

View File

@@ -0,0 +1,121 @@
package xyz.zhouxy.plusone.map.validator;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableSet;
import xyz.zhouxy.plusone.ExampleException;
import xyz.zhouxy.plusone.example.Foo;
import xyz.zhouxy.plusone.validator.MapValidator;
class MapValidatorTests {
private static final MapValidator<String, Object> validator = ParamsValidator.INSTANCE;
@Test
void testValidateAndCopy() {
Map<String, Object> params = new HashMap<>();
params.put(ParamsValidator.BOOL_PROPERTY, true);
params.put(ParamsValidator.INT_PROPERTY, Integer.MAX_VALUE);
params.put(ParamsValidator.LONG_PROPERTY, Long.MAX_VALUE);
params.put(ParamsValidator.DOUBLE_PROPERTY, Double.MAX_VALUE);
params.put(ParamsValidator.STRING_PROPERTY, "Foo");
params.put(ParamsValidator.STRING_PROPERTY2, "Bar");
params.put(ParamsValidator.DATE_TIME_PROPERTY, LocalDateTime.of(2008, 8, 8, 20, 8));
params.put(ParamsValidator.OBJECT_PROPERTY, new Foo(1, "Foo"));
params.put(ParamsValidator.STRING_LIST_PROPERTY, Collections.emptyList());
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> {
validator.validateAndCopy(params);
});
assertEquals("'stringProperty' must be equal to 'stringProperty2'.", e.getMessage());
params.put(ParamsValidator.STRING_PROPERTY2, "Foo");
assertAll(() -> {
Map<String, Object> validatedParams = validator.validateAndCopy(params);
assertEquals(ParamsValidator.keySet(), validatedParams.keySet());
assertEquals(true, validatedParams.get(ParamsValidator.BOOL_PROPERTY));
assertEquals(Integer.MAX_VALUE, validatedParams.get(ParamsValidator.INT_PROPERTY));
assertEquals(Long.MAX_VALUE, validatedParams.get(ParamsValidator.LONG_PROPERTY));
assertEquals(Double.MAX_VALUE, validatedParams.get(ParamsValidator.DOUBLE_PROPERTY));
assertEquals("Foo", validatedParams.get(ParamsValidator.STRING_PROPERTY));
assertEquals(LocalDateTime.of(2008, 8, 8, 20, 8), validatedParams.get(ParamsValidator.DATE_TIME_PROPERTY));
assertEquals(new Foo(1, "Foo"), validatedParams.get(ParamsValidator.OBJECT_PROPERTY));
assertEquals(Collections.emptyList(), validatedParams.get(ParamsValidator.STRING_LIST_PROPERTY));
});
assertAll(() -> {
Map<String, Object> validatedParams = validator.validateAndCopy(params,
ParamsValidator.LONG_PROPERTY, ParamsValidator.STRING_PROPERTY2);
assertEquals(ImmutableSet.of(ParamsValidator.LONG_PROPERTY, ParamsValidator.STRING_PROPERTY2),
validatedParams.keySet());
assertEquals(Long.MAX_VALUE, validatedParams.get(ParamsValidator.LONG_PROPERTY));
assertEquals("Foo", validatedParams.get(ParamsValidator.STRING_PROPERTY2));
});
assertAll(() -> {
Set<String> keySet = ImmutableSet.of(ParamsValidator.LONG_PROPERTY, ParamsValidator.STRING_PROPERTY2);
Map<String, Object> validatedParams = validator.validateAndCopy(params, keySet);
assertEquals(keySet, validatedParams.keySet());
assertEquals(Long.MAX_VALUE, validatedParams.get(ParamsValidator.LONG_PROPERTY));
assertEquals("Foo", validatedParams.get(ParamsValidator.STRING_PROPERTY2));
});
}
}
class ParamsValidator extends MapValidator<String, Object> {
public static final String BOOL_PROPERTY = "boolProperty";
public static final String INT_PROPERTY = "intProperty";
public static final String LONG_PROPERTY = "longProperty";
public static final String DOUBLE_PROPERTY = "doubleProperty";
public static final String STRING_PROPERTY = "stringProperty";
public static final String STRING_PROPERTY2 = "stringProperty2";
public static final String DATE_TIME_PROPERTY = "dateTimeProperty";
public static final String OBJECT_PROPERTY = "objectProperty";
public static final String STRING_LIST_PROPERTY = "stringListProperty";
public static final ParamsValidator INSTANCE = new ParamsValidator();
private ParamsValidator() {
super(new String[] { BOOL_PROPERTY, INT_PROPERTY, LONG_PROPERTY, DOUBLE_PROPERTY, STRING_PROPERTY,
DATE_TIME_PROPERTY, OBJECT_PROPERTY, STRING_LIST_PROPERTY });
ruleForBool(BOOL_PROPERTY)
.notNull();
ruleForInt(INT_PROPERTY)
.notNull("The intProperty cannot be null");
ruleForLong(LONG_PROPERTY)
.notNull(() -> ExampleException.withMessage("The longProperty cannot be null"));
ruleForDouble(DOUBLE_PROPERTY)
.notNull(d -> ExampleException.withMessage("The doubleProperty cannot be null, but it was %s", d));
ruleForString(STRING_PROPERTY)
.notNull();
ruleFor(DATE_TIME_PROPERTY)
.notNull("The dateTimeProperty cannot be null");
ruleFor(OBJECT_PROPERTY)
.notNull(() -> ExampleException.withMessage("The objectProperty cannot be null"));
ruleForCollection(STRING_LIST_PROPERTY)
.notNull(d -> ExampleException.withMessage("The stringListProperty cannot be null, but it was %s", d));
// 校验到多个属性,只能针对 map 本身进行校验
withRule(m -> Objects.equals(m.get(STRING_PROPERTY), m.get(STRING_PROPERTY2)),
"'stringProperty' must be equal to 'stringProperty2'.");
}
public static Set<String> keySet() {
return ImmutableSet.of(BOOL_PROPERTY, INT_PROPERTY, LONG_PROPERTY, DOUBLE_PROPERTY, STRING_PROPERTY,
DATE_TIME_PROPERTY, OBJECT_PROPERTY, STRING_LIST_PROPERTY);
}
}

View File

@@ -1,86 +0,0 @@
package xyz.zhouxy.plusone.validator.map.test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
import xyz.zhouxy.plusone.commons.util.StringTools;
import xyz.zhouxy.plusone.validator.MapValidator;
class MapValidatorTests {
private static final MapValidator<String, Object> validator = ParamsValidator.INSTANCE;
@Test
void testValidateAndCopy() {
Map<String, Object> params = new HashMap<>();
params.put(ParamsValidator.USERNAME, "ZhouXY");
params.put(ParamsValidator.ACCOUNT, "zhouxy@code108.cn");
params.put(ParamsValidator.PASSWORD, "99Code108");
params.put(ParamsValidator.PASSWORD2, "99Code108");
params.put(ParamsValidator.AGE, 18);
params.put(ParamsValidator.BOOLEAN, true);
params.put(ParamsValidator.ROLE_LIST, Arrays.asList("admin", ""));
assertThrows(IllegalArgumentException.class, () -> {
validator.validateAndCopy(params);
});
params.put(ParamsValidator.ROLE_LIST, Arrays.asList("admin", "developer"));
Map<String, Object> validatedParams = validator.validateAndCopy(params);
System.out.println(validatedParams);
}
}
class ParamsValidator extends MapValidator<String, Object> {
public static final String USERNAME = "username";
public static final String ACCOUNT = "account";
public static final String PASSWORD = "password";
public static final String PASSWORD2 = "password2";
public static final String AGE = "age";
public static final String BOOLEAN = "boolean";
public static final String ROLE_LIST = "roleList";
public static final ParamsValidator INSTANCE = new ParamsValidator();
private ParamsValidator() {
super(new String[] { USERNAME, ACCOUNT, PASSWORD, AGE, BOOLEAN, ROLE_LIST });
ruleForString(USERNAME)
.notBlank("用户名不能为空")
.matches(PatternConsts.USERNAME,
username -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", username)));
ruleForString(ACCOUNT)
.notBlank("账号不能为空")
.matchesOne(new Pattern[] { PatternConsts.EMAIL, PatternConsts.MOBILE_PHONE }, "请输入正确的邮箱地址或手机号");
ruleForString(PASSWORD)
.notEmpty("密码不能为空")
.matches(PatternConsts.PASSWORD, "密码不符合规范");
// 校验到多个属性,只能针对 map 本身进行校验
withRule(m -> Objects.equals(m.get(PASSWORD), m.get(PASSWORD2)),
"两次输入的密码不一样!");
ruleForInt(AGE)
.withRule(Objects::nonNull)
.ge(18)
.le(60);
ruleForBool(BOOLEAN)
.notNull("Boolean property could not be null.")
.isTrueValue("Boolean property must be true.");
this.<String>ruleForCollection(ROLE_LIST)
.notEmpty("角色列表不能为空!")
.withRule(l -> l.stream().allMatch(StringTools::isNotBlank),
() -> new IllegalArgumentException("角色标识不能为空!"));
}
}

View File

@@ -1,169 +0,0 @@
package xyz.zhouxy.plusone.validator.test;
import java.time.Year;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Range;
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
import xyz.zhouxy.plusone.commons.function.PredicateTools;
import xyz.zhouxy.plusone.commons.util.RegexTools;
import xyz.zhouxy.plusone.commons.util.StringTools;
import xyz.zhouxy.plusone.validator.BaseValidator;
import xyz.zhouxy.plusone.validator.ValidTools;
class BaseValidatorTest {
@Test
void testValidate() {
RegisterCommand registerCommand = new RegisterCommand("zhouxy108", "luquanlion@outlook.com", "22336",
"A1b2C3d4",
"A1b2C3d4",
Arrays.asList(new String[] { "admin", "editor" }),
2000);
RegisterCommandValidator.INSTANCE.validate(registerCommand);
ValidTools.validate(registerCommand, RegisterCommandValidator.INSTANCE);
System.out.println(registerCommand);
}
static class RegisterCommandValidator extends BaseValidator<RegisterCommand> {
static final RegisterCommandValidator INSTANCE = new RegisterCommandValidator();
private RegisterCommandValidator() {
int thisYear = Year.now().getValue();
ruleForString(RegisterCommand::getUsername)
.must(PredicateTools.<String>from(Objects::nonNull)
.and(StringTools::isNotEmpty)
.and(StringTools::isNotBlank)
.and(username -> RegexTools.matches(username, PatternConsts.USERNAME)),
username -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", username)));
ruleForString(RegisterCommand::getAccount)
.notNull("请输入邮箱地址或手机号")
.matchesOne(Arrays.asList(PatternConsts.EMAIL, PatternConsts.MOBILE_PHONE), "请输入邮箱地址或手机号");
ruleForString(RegisterCommand::getCode)
.notNull("验证码不能为空")
.matches(PatternConsts.CAPTCHA, "验证码不符合规范");
ruleForString(RegisterCommand::getPassword)
.notEmpty("密码不能为空")
.matches(PatternConsts.PASSWORD, "密码不符合规范");
ruleForCollection(RegisterCommand::getRoles)
.notEmpty(() -> new RuntimeException("角色列表不能为空"));
ruleForComparable(RegisterCommand::getYearOfBirth)
.notNull()
.inRange(Range.closed(thisYear - 60, thisYear - 18));
ruleForInt(RegisterCommand::getYearOfBirth)
.notNull()
.inRange(Range.closed(thisYear - 60, thisYear - 18));
withRule(registerCommand -> Objects.equals(registerCommand.getPassword(), registerCommand.getPassword2()),
"两次输入的密码不一致");
}
}
/**
* RegisterCommand
*/
static class RegisterCommand {
private String username;
private String account;
private String code;
private String password;
private String password2;
private List<String> roles;
private Integer yearOfBirth;
public RegisterCommand() {
}
public RegisterCommand(String username, String account, String code, String password, String password2,
List<String> roles, Integer yearOfBirth) {
this.username = username;
this.account = account;
this.code = code;
this.password = password;
this.password2 = password2;
this.roles = roles;
this.yearOfBirth = yearOfBirth;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public Integer getYearOfBirth() {
return yearOfBirth;
}
public void setYearOfBirth(Integer yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
@Override
public String toString() {
return new StringBuilder()
.append("RegisterCommand [")
.append("username=").append(username)
.append(", account=").append(account)
.append(", code=").append(code)
.append(", password=").append(password)
.append(", password2=").append(password2)
.append(", roles=").append(roles)
.append(", yearOfBirth=").append(yearOfBirth)
.append("]")
.toString();
}
}
}