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

相關文章
相關標籤/搜索