[JAVA #17] [Web Automation #17] Selenium With TestNG #6 Soft Assert [CN]

image source: pixabay
上次简单介绍过 TestNG 的 Asserting。但它有一个缺点,看下列例子。
@Test(description = "获取文章列表")
public void CASE_02_GetPosts() {
List<WebElement> list = driver.findElements(By.xpath("//div[@id='posts_list']/ul/li"));
assertTrue(!list.isEmpty(), "确认是否显示列表");
for (WebElement post : list) {
String title = post.findElement(By.xpath("descendant::h2/a")).getText();
assertNotNull(title,"验证标题 >> " + title);
String author = post.findElement(By.xpath("descendant::span[@class='user__name']")).getText();
assertNotNull(author, "验证作者名 >> " + author);
System.out.println(author + "的文章: " + title);
}
}
👆 分析如下
- 获取文章列表并验证list不为空
- 循环验证每个帖子的标题是否显示
- 验证作者名是否显示
如果这三个验证点都正常的话没有问题,但是因某些原由在第二个验证点出现失败则抛出 Exception 并且停止该@Test执行下一句用例。也就是说第三个验证点被忽略了。 👇

这点在QA自动化很致命。幸好业界有研究相关问题,有很多解决方法,其中我介绍下 TestNG 的 Soft Assert。Soft Assert用于多个验证点的时候即使有抛出 Exception 也会把它catch到并且留日志。把上述例子中的 Asserting 都改成 Soft Asserting试试吧。
@Test(description = "获取文章列表")
public void CASE_02_GetPosts() {
SoftAssert sa = new SoftAssert();
List<WebElement> list = driver.findElements(By.xpath("//div[@id='posts_list']/ul/li"));
sa.assertTrue(!list.isEmpty(), "确认是否显示列表");
for (WebElement post : list) {
String title = post.findElement(By.xpath("descendant::h2/a")).getText();
sa.assertNull(title,"验证标题 >> " + title);
String author = post.findElement(By.xpath("descendant::span[@class='user__name']")).getText();
sa.assertNotNull(author, "验证作者名 >> " + author);
System.out.println(author + "的文章: " + title);
}
}
看控制台列出了全部用户的信息,说明成功了。 👇
cryptopie (77)님의 글: Markets Had Gone Wild Again But It Is A Good Thing
bji1203 (73)님의 글: SPT) The Wealthy Gambit 토너먼트 후기
goodreader (61)님의 글: steem-hive中文区[以文会友]20200328(like赞赏公民拍)
rivalhw (75)님의 글: 好文天天赞榜上有名 一起推荐好文章活动将重新启动
freegon (74)님의 글: 엄마에 음식 "쥐고기"
skymin (70)님의 글: 다시 주목 받을 수 있게...
sindoja (69)님의 글: 중국에서 '폭동'이 발발하는 가운데 (부제 : 첫잔속 태풍으로 그칠지 아니면...)
xiaoshancun (67)님의 글: 在幸福里遥望
sean2masaaki (69)님의 글: 석갈비가 끝내주는 황학동 맛집, "나루"
himapan (67)님의 글: [PHOTOGRAPH]Temple & Giant Swing
cryptopie (77)님의 글: I Am Glad That My Vitamin C That I Ordered Will Get Delivered But It Will Take Much Time
jungjunghoon (70)님의 글: 숙성된 돼지고기의 깊은 맛 - 숙달 돼지
gghite (73)제주도 탐험가님의 글: (제주라이프) #6 집밥 릴레이 - 독특한 반찬 고수 넣은 무생채
lnakuma (59)님의 글: 周五了,喘口气
sonki999 (76)님의 글: 바이낸스 VISA 제휴 암호화화폐 직불카드 출시
bluengel (70)님의 글: [ZZAN] 악의 축 처단에 포기란 없다~! <졸업> 짠~! 💙
jhy2246 (70)님의 글: 시골집 매실나무가 너무 예뻐요
ericet (72)ADMIN님의 글: ionomy上交易留点心
honoru (71)님의 글: 構想回饋支持 Patreon月費支持者
virus707 (76)님의 글: 물속의 황금 열쇠
👇 但是还存在一个问题,把所有的Exception都忽略导致报告显示成绿色,有失败应显示红色。

在呼叫函数的结尾部分加上 assertAll() 函数可以解决问题。 搞定。👇

这两个 Asserting 如果用的恰到好处可以提升不少效率。
如上述例子中的第一个验证点用 Hard Assert 验证,第二,第三验证点用 Soft Assert 验证即可。
package com.steem.webatuo;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Steemit {
WebDriver driver;
String baseUrl = "https://steemit.com";
@Parameters({"browser"})
@BeforeClass
public void SetUp(String browserName) {
if(browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
else {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
driver.get(baseUrl + "/@june0620/feed");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
}
@Test(timeOut = 60000, description = "登录")
public void CASE_01_Login() throws InterruptedException {
// Click the login button
driver.findElement(By.linkText("login")).click();
// type id
driver.findElement(By.name("username")).sendKeys("june0620");
// type pw and submit
WebElement pw = driver.findElement(By.name("password"));
assertNotNull(pw, "验证密码标签是否显示");
pw.sendKeys(Password.getPw());
pw.submit();
Thread.sleep(5000);
}
@Test(description = "获取帖子列表")
public void CASE_02_GetPosts() {
SoftAssert sa = new SoftAssert();
List<WebElement> list = driver.findElements(By.xpath("//div[@id='posts_list']/ul/li"));
assertTrue(!list.isEmpty(), "验证文章列表不为空");
for (WebElement post : list) {
String title = post.findElement(By.xpath("descendant::h2/a")).getText();
sa.assertNotNull(title,"验证标题타이틀 확인 >> " + title);
String author = post.findElement(By.xpath("descendant::span[@class='user__name']")).getText();
sa.assertNotNull(author, "验证作者名 >> " + author);
System.out.println(author + "的文章: " + title);
}
sa.assertAll();
}
@Test(description = "撰写文章")
public void CASE_03_Write() throws InterruptedException {
// Click the write Button
List<WebElement> writeBtns = driver.findElements(By.xpath("//a[@href='/submit.html']"));
assertEquals(writeBtns.size(), 1, "验证撰写按钮是否显示");
for (WebElement writeBtn : writeBtns) {
if (writeBtn.isDisplayed()) {
writeBtn.click();
Thread.sleep(2000);
// type Text and Keys
WebElement editor = driver.findElement(By.xpath("//textarea[@name='body']"));
String keys = Keys.chord(Keys.LEFT_SHIFT, Keys.ENTER);
editor.sendKeys("hello!! world", keys, "hello!!! STEEMIT", Keys.ENTER, "안녕, 스팀잇", Keys.ENTER, "你好!似提姆");
break;
}
}
Thread.sleep(5000);
}
@Test(description = "搜索用户", dataProvider = "steemians")
public void CASE_04_Search(String name) {
driver.get(baseUrl + "/@" + name);
/*
* Some actions
*/
}
@DataProvider(name = "steemians")
public Object[][] members() {
return new Object[][] {
{"annepink"},
{"gghite"},
{"lucky2015"},
{"honoru"},
};
}
@AfterClass
public void tearDownClass() {
driver.quit();
}
}
.
.
.
.
[Cookie 😅]
Seleniun java lib version: 3.141.59
java version: 13.0.1
참고사이트: https://www.softwaretestingmaterial.com/soft-assert/
早上好俊🍏😊👏5⃣
早上好,萍萍 😀