TestNG中的Assertion,也是斷言。
斷言是測試中最難寫的部分。
- Assert類(硬斷言)
斷言類是Assert.java,里面有多個靜態(tài)方法被稱為硬斷言,硬斷言就是,如果運(yùn)行到折行斷言失敗,即使該用例,后面還有其他代碼行,也不會繼續(xù)執(zhí)行下去
Assert.assertEquals( expected,actual)

TestNG中提供了多個33個assertEquals()方法,主要是匹配不同的數(shù)據(jù)類型和集合類操作。
舉例:
package com.example.lenovo.myapplication;
import org.testng.annotations.Test;
import static junit.framework.TestCase.assertEquals;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a >Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
assertEquals(5,1+9);
}
}

上面可以看出assertEquals中Expected和Actual不相等,如果現(xiàn)實(shí)結(jié)果和期待結(jié)果不相等,拋出斷言異常并顯示內(nèi)容,這樣拋出錯誤,更能快速讀懂錯誤的原因和錯誤的具體業(yè)務(wù)邏輯
(1) assertTrue:判斷是否為True。
(2) assertFalse:判斷是否為false。
(3) assertSame:判斷引用地址是否相同。
(4) assertNotSame:判斷引用地址是否不相同。
(5) assertNull:判斷是否為null。
(6) assertNotNull:判斷是否不為null。
(7) assertEquals:判斷是否相等,Object類型的對象需要實(shí)現(xiàn)haseCode及equals方法。
(8) assertNotEquals:判斷是否不相等。
(9) assertEqualsNoOrder:判斷忽略順序是否相等
- SoftAssert(軟斷言)
SoftAssert的特點(diǎn)
1) 如果一個斷言失敗,會繼續(xù)執(zhí)行這個斷言下的其他語句或者斷言
2) 也就是一個用例有多個斷言,失敗了其中一個,不影響其他斷言的運(yùn)行
3) 不要忘記調(diào)用assertAll()在該用例的最后一個斷言后面
4) 軟斷言的類,叫SoftAssert.java,這個類是需要創(chuàng)建實(shí)例對象,才能調(diào)用相關(guān)實(shí)例方法進(jìn)行軟斷言
package testng;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class AssertTestDemo {
@Test
public void testSoftAssert(){
System.out.println("Test start");
SoftAssert assertion = new SoftAssert();
assertion.assertEquals(12, 13,"兩者不相等");
System.out.println("Test complete");
System.out.println(3+8);
assertion.assertAll();
}
}
運(yùn)行結(jié)果:

通過運(yùn)行結(jié)果截圖,可以看到在斷言12和13相等的這行代碼后面還有其他的語句,如果這里采用的是硬斷言,那么Test complete 和 11是不會輸出,也就是代碼沒有被執(zhí)行。這個就是SoftAssert的優(yōu)點(diǎn),再強(qiáng)調(diào)一次,最后一定要調(diào)用assertAll()方法