assertNotNull()

2019年2月17日 在一本书上看到这段代码,很好奇是什么意思?

Assert:断言机制:

测试代码或者调试程序时,总会作出一些假设,断言就是用于在代码中捕捉这些假设。当要判断一个方法传入的参数时,咱们就可使用断言。java

例如:函数

public Order create(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod, 
BoxMethod boxMethod, CouponCode couponCode, boolean isInvoice) {
    Assert.notNull(cart);
    Assert.notEmpty(cart.getCartItems());
    Assert.isTrue(cart.checkedSize()>0, "购物项选择必须大于0");
    Assert.notNull(receiver);
    Assert.notNull(paymentMethod);
    Assert.notNull(shippingMethod);

}

这样能够检测传入的参数是否符合要求,当这些断言方法在入参不知足要求时就会抛出 IllegalArgumentException。测试

Assert.notNULL()

断言经常使用的方法

notNull(Object object)

notNull(Object object, String message) 该函数的意思是传入的object必须不能为空。若是为空就抛出异常。spa

与 notNull() 方法断言规则相反的方法是 isNull(Object object)/isNull(Object object, String message),它要求入参必定是 null。调试

若是不是,则会报错。
图片描述code

相关文章
相关标签/搜索