Precodition 用于参数/状态检查,不满足条件时会抛出异常。其实现和用法值得借鉴。
示例:
package org.example.model;
import com.google.common.base.Preconditions;
import org.junit.Test;
import java.util.Objects;
import static org.assertj.core.api.Assertions.*;
public class PreConditionTest {
@Test
public void test() {
String nullStr = null;
// 1. 判断不能为空,使用jdk的Objects.requireNonNull
assertThatNullPointerException().isThrownBy(() -> Preconditions.checkNotNull(nullStr));
assertThatNullPointerException().isThrownBy(() -> Preconditions.checkNotNull(nullStr, "string is empty"))
.withMessage("string is empty");
assertThatNullPointerException().isThrownBy(() -> Preconditions.checkNotNull(nullStr, "%s is empty", "string"))
.withMessage("string is empty");
// 2. 检查参数要满足指定条件
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->Preconditions.checkArgument(nullStr != null, "string is empty"))
.withMessage("string is empty");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() ->Preconditions.checkArgument(nullStr != null, "%s is empty", "string"))
.withMessage("string is empty");
// 3. 检查要满足指定状态, 和检查参数相比,只是抛出的异常不同
String status = "end";
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() ->Preconditions.checkState(status.equals("start"), "status is not start"))
.withMessage("status is not start");
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() ->Preconditions.checkState(status.equals("start"), "%s is not start", "status"))
.withMessage("status is not start");
// 4. JDK Objects支持的相关操作
assertThat(Objects.isNull(nullStr)).isTrue();
assertThat(Objects.nonNull(status)).isTrue();
assertThatNullPointerException().isThrownBy(() -> Objects.requireNonNull(nullStr));
assertThatNullPointerException().isThrownBy(() -> Objects.requireNonNull(nullStr, "string is empty"))
.withMessage("string is empty");
}
}