testng断言分为硬断言或或者软断言,类似于pytest里面的断言和多重断言
1、硬断言
常用硬断言如下:
Assert.assertTrue:判断是否为True。
Assert.assertFalse:判断是否为False。
Assert.assertSame:判断引用地址是否相同。
Assert.assertNotSame:判断引用地址是否不相同。
Assert.assertNull:判断是否为null。
Assert.assertNotNull:判断是否不为null。
Assert.assertEquals:判断是否相等。
Assert.assertNotEquals:判断是否不相等。
Assert.assertEqualsNoOrder:判断忽略顺序是否相等。
示例:
package org.example;
//import static org.junit.Assert.assertTrue;
import org.testng.Assert;
import org.testng.annotations.*;
public class AppTest
{
@Test
public void test01(){
Assert.assertEquals(1, 2, "test01断言错误");
}
@Test
public void test02() {
Assert.assertTrue(true);
}
}
如上,断言错误后,会输出错误描述,这里可以自己定义
2、软断言
SoftAssert类:org.testng.asserts.SoftAssert,这个类是需要创建实例对象,才能调用相关实例方法进行软断言。
软断言就是,如果一个断言失败,会继续执行这个断言下的其他语句或者断言。
在该用例的最后一个断言后面一定要调用assertAll()方法。
在使用软断言之前我们来个对比,硬断言写多个,断言失败一个后后续断言不再执行
软断言则会把所有断言走完,如下会显示两个断言的错误信息
package org.example;
//import static org.junit.Assert.assertTrue;
import org.testng.Assert;
import org.testng.annotations.*;
import org.testng.asserts.SoftAssert;
public class AppTest
{
@Test
public void test01(){
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(1, 2, "test01断言错误");
softAssert.assertEquals(3, 4, "test01断言又失败了");
softAssert.assertEquals(1, 1);
softAssert.assertAll();
}
}