java 自定义断言工具类

本文介绍了在Java开发中如何使用全局统一的断言工具类进行对象空值和非空校验,以及如何通过该工具类抛出异常,提升代码可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

java 开发过程中,应使用全局统一的断言工具类,使系统的断言处理一致,便于维护。

什么时候使用?

当对象空值或非空校验,并需要抛出异常时,就必须调用统一断言工具类。

断言工具类

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.Objects;

/**
 * 断言类
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class BusinessAsserts {

	/**
	 * 是否为true,false抛出异常
	 *
	 * @param expression bool
	 * @param message    提示信息
	 */
	public static void isTrue(boolean expression, String message) {
		isTrue(expression, message, StrUtil.EMPTY);
	}

	public static void isTrue(boolean expression, String message, Object... args) {
		if (!expression) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否为false,true抛出异常
	 *
	 * @param expression bool
	 * @param message    提示信息
	 */
	public static void isFalse(boolean expression, String message) {
		isTrue(!expression, message);
	}

	public static void isFalse(boolean expression, String message, Object... args) {
		isTrue(!expression, message, StrUtil.format(message, args));
	}
	
	/**
	 * 是否为null,不为null抛出异常
	 *
	 * @param object  obj
	 * @param message 提示信息
	 */
	public static void isNull(Object object, String message) {
		isNull(object, message, StrUtil.EMPTY);
	}

	public static void isNull(Object object, String message, Object... args) {
		if (Objects.nonNull(object)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否不为null,null抛出异常
	 *
	 * @param object  obj
	 * @param message 提示信息
	 */
	public static void isNotNull(Object object, String message) {
		isNotNull(object, message, StrUtil.EMPTY);
	}

	public static void isNotNull(Object object, String message, Object... args) {
		if (Objects.isNull(object)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否allNotNull,hasNull抛出异常
	 *
	 * @param col     集合
	 * @param message 提示信息
	 */
	public static void isAllNotNull(Collection<?> col, String message) {
		isAllNotNull(col, message, StrUtil.EMPTY);
	}

	public static void isAllNotNull(Collection<?> col, String message, Object... args) {
		Objects.requireNonNull(col);

		if (ObjectUtil.hasNull(col)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否为blank,notBlank抛出异常
	 *
	 * @param string  str
	 * @param message 提示信息
	 */
	public static void isBlank(String string, String message) {
		isBlank(string, message, StrUtil.EMPTY);
	}

	public static void isBlank(String string, String message, Object... args) {
		if (StrUtil.isNotBlank(string)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否notBlank,blank抛出异常
	 *
	 * @param string  str
	 * @param message 提示信息
	 */
	public static void isNotBlank(String string, String message) {
		isNotBlank(string, message, StrUtil.EMPTY);
	}

	public static void isNotBlank(String string, String message, Object... args) {
		if (StrUtil.isBlank(string)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否allBlank,hasNotBlank抛出异常
	 *
	 * @param col     集合
	 * @param message 提示信息
	 */
	public static void isAllBlank(Collection<String> col, String message) {
		isAllBlank(col, message, StrUtil.EMPTY);
	}

	public static void isAllBlank(Collection<String> col, String message, Object... args) {
		Objects.requireNonNull(col);

		String[] strings = col.stream().toArray(String[]::new);
		if (!StrUtil.hasBlank(strings)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否allNotBlank,hasBlank抛出异常
	 *
	 * @param col     集合
	 * @param message 提示信息
	 */
	public static void isAllNotBlank(Collection<String> col, String message) {
		isAllNotBlank(col, message, StrUtil.EMPTY);
	}

	public static void isAllNotBlank(Collection<String> col, String message, Object... args) {
		Objects.requireNonNull(col);
		String[] strings = col.stream().toArray(String[]::new);
		if (StrUtil.hasBlank(strings)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否equal,notEqual抛出异常
	 *
	 * @param object1 obj1
	 * @param object2 obj2
	 * @param message 提示信息
	 */
	public static void equal(Object object1, Object object2, String message) {
		equal(object1, object2, message, StrUtil.EMPTY);
	}

	public static void equal(Object object1, Object object2, String message, Object... args) {
		if (!Objects.equals(object1, object2)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否notEqual,equal抛出异常
	 *
	 * @param object1 obj1
	 * @param object2 obj2
	 * @param message 提示信息
	 */
	public static void notEqual(Object object1, Object object2, String message) {
		notEqual(object1, object2, message, StrUtil.EMPTY);
	}

	public static void notEqual(Object object1, Object object2, String message, Object... args) {
		if (Objects.equals(object1, object2)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否empty,notEmpty抛出异常
	 *
	 * @param col     集合
	 * @param message 提示信息
	 */
	public static void isEmpty(Collection<?> col, String message) {
		isEmpty(col, message, StrUtil.EMPTY);
	}

	public static void isEmpty(Collection<?> col, String message, Object... args) {
		if (CollectionUtil.isNotEmpty(col)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否notEmpty,empty抛出异常
	 *
	 * @param col     集合
	 * @param message 提示信息
	 */
	public static void isNotEmpty(Collection<?> col, String message) {
		isNotEmpty(col, message, StrUtil.EMPTY);
	}

	public static void isNotEmpty(Collection<?> col, String message, Object... args) {
		if (CollectionUtil.isEmpty(col)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

	/**
	 * 是否allNotEmpty,hasEmpty抛出异常
	 *
	 * @param col     集合
	 * @param message 提示信息
	 */
	public static void isAllNotEmpty(Collection<?> col, String message) {
		isAllNotEmpty(col, message, StrUtil.EMPTY);
	}

	public static void isAllNotEmpty(Collection<?> col, String message, Object... args) {
		Objects.requireNonNull(col);

		if (ObjectUtil.hasEmpty(col)) {
			throw new ServiceException(StrUtil.format(message, args));
		}
	}

}

### 创建自定义 Assert 工具类Java 的测试框架中,创建一个自定义的 `Assert` 工具类可以通过多种方式实现。以下是基于常见测试库(如 JUnit 和 AssertJ)的具体实现方案。 #### 使用 AssertJ 实现自定义断言 为了创建自定义断言工具类,通常建议扩展 AssertJ 提供的基础类 `AbstractAssert` 或其子类之一。这种方式能够充分利用 AssertJ 的强大功能并保持一致性[^1]。 下面是一个具体的例子: ```java import org.assertj.core.api.AbstractAssert; import java.util.List; public class RangeAssert extends AbstractAssert<RangeAssert, List<Integer>> { protected RangeAssert(List<Integer> actual) { super(actual, RangeAssert.class); } public static RangeAssert assertThat(List<Integer> actual) { return new RangeAssert(actual); } public RangeAssert hasValidRanges() { isNotNull(); for (Integer value : actual) { if (value < 0 || value > 100) { failWithMessage("Expected all values to be between 0 and 100 but found %s", value); } } return this; } } ``` 上述代码展示了如何通过继承 `AbstractAssert` 来构建一个新的断言工具类 `RangeAssert`,用于验证整数列表中的值是否位于指定范围内。 --- #### 结合 TestNG 自定义断言 如果使用的是 TestNG,则可以直接利用静态导入的方式调用内置的断言方法,并在此基础上进一步增强逻辑[^2]。 示例代码如下: ```java import static org.testng.Assert.*; public class CustomAssertions { public static void assertInRange(int number, int lowerBound, int upperBound) { assertTrue(number >= lowerBound && number <= upperBound, String.format("Number %d is not within range [%d, %d]", number, lowerBound, upperBound)); } } // 测试案例 @Test public void testCustomAssertion() { CustomAssertions.assertInRange(50, 0, 100); // 成功 CustomAssertions.assertInRange(-10, 0, 100); // 失败 } ``` 此片段说明了如何编写独立于任何特定框架的通用断言函数。 --- #### 利用 Spring Framework 中的 Assertion 功能 对于依赖 Spring 生态系统的项目而言,直接采用已有的工具类可能是更优的选择[^4]。例如,`org.springframework.util.Assert` 类提供了丰富的校验手段而无需额外配置。 实例演示: ```java import org.springframework.util.Assert; public class SpringBasedAssertions { public static void assertNotNull(Object object, String message) { Assert.notNull(object, message); } public static void assertNotEmpty(String string, String message) { Assert.hasText(string, message); } } // 应用场景 public void validateInput(String input) { SpringBasedAssertions.assertNotNull(input, "Input cannot be null"); SpringBasedAssertions.assertNotEmpty(input, "Input must have text content"); } ``` 这里强调了复用成熟框架的重要性以及减少重复造轮子的价值所在。 --- #### 总结注意事项 当决定开发新的断言机制时,请考虑以下几点: - 是否已有满足需求的标准库? - 新增组件是否会增加维护成本? 只有在确实无法找到合适的解决方案或者现有选项不符合业务特性的情况下才应着手设计专属版本[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Whitemeen太白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值