1、原理:对测试程序变量的中间状态进行断言(Assert)判断,从而辅助判断测试用例的执行是成功还是失败。
2、TestNG中常用的断言方法有:
(1) assertTrue:判断是否为True。
(2) assertFalse:判断是否为false。
(3) assertSame:判断引用地址是否相同。
(4) assertNotSame:判断引用地址是否不相同。
(5) assertNull:判断是否为null。
(6) assertNotNull:判断是否不为null。
(7) assertEquals:判断是否相等,Object类型的对象需要实现haseCode及equals方法。
(8) assertNotEquals:判断是否不相等。
(9) assertEqualsNoOrder:判断忽略顺序是否相等。
3、下面使用WebDriver测试实例体现断言的使用方法。测试用例:
(1) 打开Firefox浏览器,访问sogou首页。
(2) 查找首页上的输入框元素。
(3) 断言输入框是否存在。
(4) 输入搜索关键字,点击搜索按钮。
测试程序:
package cn.testng; 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 driver; String baseUrl="http://www.sogou.com";//设定访问网站的地址 @Test public void testSearch() { //打开sogou首页 driver.get(baseUrl+"/"); WebElement inputBox=driver.findElement(By.id("query")); /*使用Assert类的assertTrue方法断言搜索输入框是否在页面显示 * isDisplayed方法根据页面元素的显示状态返回判断值,在页面显示则返回true,不显示则返回false */ Assert.assertTrue(inputBox.isDisplayed()); inputBox.sendKeys("自动化测试"); //点击搜索按钮 driver.findElement(By.id("stb")).click(); } @BeforeMethod public void beforeMethod() { //若无法打开Firefox浏览器,可设定Firefox浏览器的安装路径 System.setProperty("webdriver.firefox.bin", "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"); //打开Firefox浏览器 driver=new FirefoxDriver(); } @AfterMethod public void afterMethod() { //关闭打开的浏览器 driver.quit(); } } empty
测试结果:
[TestNG] Running:
C:\Windows\Temp\testng-eclipse–\testng-customsuite.xml
PASSED: testSearch
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231808.html原文链接:https://javaforall.net
