Assert斷言機制


Assert.IsTrue方法:

 Assert.IsTrue(jsonData.IsArray);

 Assert.IsTrue(jsonData.IsArray,“its not a array”);

 

Assert:斷言機制:

測試代碼或者調試程序時,總會做出一些假設,斷言就是用於在代碼中捕捉這些假設。當要判斷一個方法傳入的參數時,我們就可以使用斷言。

例如:

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。

斷言常用的方法 
1. notNull(Object object) 
當 object 不為 null 時拋出異常,notNull(Object object, String message) 方法允許您通過 message 定制異常信息。和 notNull() 方法斷言規則相反的方法是 isNull(Object object)/isNull(Object object, String message),它要求入參一定是 null;

 

2. isTrue(boolean expression) / isTrue(boolean expression, String message) 
當 expression 不為 true 拋出異常;


3. notEmpty(Collection collection) / notEmpty(Collection collection, String message) 
當集合未包含元素時拋出異常。

notEmpty(Map map) / notEmpty(Map map, String message) 和 notEmpty(Object[] array, String message) / notEmpty(Object[] array, String message) 分別對 Map 和 Object[] 類型的入參進行判斷;


4. hasLength(String text) / hasLength(String text, String message)  當 text 為 null 或長度為 0 時拋出異常;
5. hasText(String text) / hasText(String text, String message)  text 不能為 null 且必須至少包含一個非空格的字符,否則拋出異常;
6. isInstanceOf(Class clazz, Object obj) / isInstanceOf(Class type, Object obj, String message)  如果 obj 不能被正確造型為 clazz 指定的類將拋出異常;
7. isAssignable(Class superType, Class subType) / isAssignable(Class superType, Class subType, String message)  subType 必須可以按類型匹配於 superType,否則將拋出異常;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM