selenium自动化测试由浅入深--之TestNg常用断言方法
断言,几乎是TestNg中最重要的一个环节。他可以判断测试用例执行的成功还是失败。
下面介绍TestNg常用的断言方法:
-
assertTrue: 判断是否为true。
-
assertFalse:判断是否为false。
-
assertNull: 判断是否为null。
-
assertNotNull:判断是否不为null。
-
assertEquals:判断是否相等。
-
assertNotEquals:判断是否不相等。
-
assertEqualNoOrder: 判断忽略顺序是否相等。
光说不练不行,老规矩,撸代码讲。不要偷懒,也跟着写起来吧。我们就做一下如下的例子。判断百度检索框,是否包含“新闻”关键字。代码如下:
package cn.autotest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AssertTest {
public WebDriver wd;
static String actual = null;
String baiduurl="http://www.baidu.com";//要访问的网站
@Test
public void baidu() throws InterruptedException{
//打开百度
wd.get(baiduurl + "/");
//定位新闻按钮
Thread.sleep(2000);
WebElement text = wd.findElement(By.xpath("//*[@id='u1']/a[1]"));
//转换为string
Thread.sleep(2000);
actual =text.getText();
//输出看看
System.out.print(actual + "\n");
Assert.assertEquals(actual,"新闻");//想试试不通过,可以把新闻换成别的字眼
}
@BeforeMethod //在方法开始之前进行如下操作
public void beforeMethod(){
//启动火狐浏览器
System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
wd = new FirefoxDriver();
}
@AfterMethod //在方法之后操作如下
public void afterMethod(){
//关闭浏览器
wd.close();
}
}
运行结果如下:
[TestNG] Running:
C:\Users\Administrator\AppData\Local\Temp\testng-eclipse-1894000645\testng-customsuite.xml
新闻
PASSED: baidu
=============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
当然你把这段代码Assert.assertEquals(actual,"新闻"),中的“新闻”换成其他的。就是fail的例子了。
今天断言就讲到这里,从代码可以清楚的看到,与断言不符合,测试用例就会失败。
老规矩,喜欢的请分享给爱自动化测试的同学哟。你只要跟我一点点敲代码,会对自动化慢慢熟悉的。
请关注免费非机构 公 众 号 扫 马