Selenium WebDriver的TestNG注释完整指南
TestNG是CédricBeust創(chuàng)建的測試框架 ,有助于滿足我們的許多測試需求。 它被廣泛用于硒中。 想知道NG代表什么? 好吧,它指的是“下一代” 。 TestNG與Junit相似,但在控制程序的執(zhí)行流程方面更強(qiáng)大。 作為框架的本質(zhì),我們傾向于使測試更加結(jié)構(gòu)化,并通過使用TestNG提供更好的驗證點。
TestNG的一些值得注意的功能是:
- 功能強(qiáng)大且種類繁多的注釋可支持您的測試用例。
- 幫助執(zhí)行并行測試,相關(guān)方法測試。
- 通過TestNG.xml文件或通過數(shù)據(jù)提供者概念通過多組數(shù)據(jù)運行測試的靈活性。
- 測試用例可以根據(jù)需要進(jìn)行分組并確定優(yōu)先級。
- 提供對HTML報告的訪問,并且可以通過各種插件進(jìn)行自定義。
- 可以跨測試生成測試日志。
- 可以輕松地與eclipse,Maven,Jenkins等集成。
TestNG程序的基本處理流程包括以下步驟:
因此,在轉(zhuǎn)到TestNG for Selenium中的注釋之前,最好先參考設(shè)置TestNG所需的先決條件。
先決條件
- Java開發(fā)套件
- 設(shè)置Eclipse或任何其他IDE。
- 在Eclipse或任何其他IDE中安裝TestNG。
注意:注釋只能與Java 1.5或更高版本一起使用。
如果您不熟悉TestNG框架,請按照我們的指南使用TestNG運行您的第一個自動化腳本 。
在云網(wǎng)格上運行TestNG Selenium腳本
那么,什么是注釋?
注釋是提供有關(guān)類或方法的其他信息的標(biāo)簽。 它由“ @”前綴表示。 TestNG使用這些注釋來幫助創(chuàng)建一個健壯的框架。 讓我們來看看用于用Selenium進(jìn)行自動化測試的TestNG的這些注釋。
@測試
主要業(yè)務(wù)邏輯所在的TestNG框架中最重要的注釋。 所有要自動化的功能都保留在@Test批注方法中。 它具有各種屬性,可以根據(jù)這些屬性來重新構(gòu)造和執(zhí)行該方法。
以下驗證url的代碼段示例:
@Testpublic void testCurrentUrl() throws InterruptedException{driver.findElement(By.xpath("//*[@id='app']/header/aside/ul/li[4]/a")).click();String currentUrl= driver.getCurrentUrl();assertEquals(current_url, "https://automation.lambdatest.com/timeline/?viewType=build&page=1", "url did not matched");}@BeforeTest
該注釋在類中的第一個@Test注釋方法之前運行。 您可以在TestNG for Selenium中使用此注釋來設(shè)置瀏覽器配置文件首選項,例如以最大化模式自動打開瀏覽器,為瀏覽器設(shè)置自己的自定義配置文件等。
下面是確保測試器以最大化模式打開的BeforeTest方法的代碼片段:
@BeforeTestpublic void profileSetup(){driver.manage().window().maximize();}@AfterTest
TestNG中的此批注在您屬于該類的所有測試方法運行后運行。 這是一個有用的注釋,在向您的利益相關(guān)者報告自動化結(jié)果方面非常有用。 您可以使用此批注生成測試報告,并通過電子郵件將其分享給您的涉眾。
下面的代碼段示例:
@AfterTestpublic void reportReady(){System.out.println("Report is ready to be shared, with screenshots of tests");}@BeforeMethod
TestNG中的此注釋在每個@test注釋方法之前運行。 您可以在執(zhí)行測試之前使用它來簽出數(shù)據(jù)庫連接,或者可以說@test帶注釋的方法已經(jīng)測試了不同的功能,該方法要求用戶登錄某個類。 在這種情況下,您也可以將您的登錄代碼放入@BeforeMethod批注方法中。
下面的代碼段是一個示例,顯示了LambdaTest平臺的登錄功能:
@BeforeMethodpublic void checkLogin(){driver.get("https://accounts.lambdatest.com/login");driver.findElement(By.xpath("//input[@name='email']")).sendKeys("sadhvisingh24@gmail.com");driver.findElement(By.xpath("//input[@name='password']")).sendKeys("XXXXX");driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/button")).click();}@AfterMethod
該注釋在每個@test注釋方法之后運行。 此批注可用于截取針對測試運行而運行的每個測試方法的屏幕截圖。
下面的代碼片段指示在Selenium的TestNG中的@AfterTest批注中截取的屏幕截圖:
@AfterMethodpublic void screenShot() throws IOException{TakesScreenshot scr= ((TakesScreenshot)driver);File file1= scr.getScreenshotAs(OutputType.FILE);FileUtils.copyFile(file1, new File("C:\\Users\\navyug\\workspace\\QAPractise\\test-output\\test1.PNG"));}@課前
該注釋在當(dāng)前類的第一個測試方法之前運行。 此注釋可用于設(shè)置瀏覽器屬性,初始化驅(qū)動程序,使用所需的URL打開瀏覽器等。
以下是BeforeClass的代碼段:
@BeforeClasspublic void appSetup(){driver.get(url);}@下課以后
該注釋在當(dāng)前類中的最后一個測試方法之后運行。 TestNG中的此批注可用于在測試過程中執(zhí)行清理活動,例如關(guān)閉驅(qū)動程序等
以下是顯示已執(zhí)行的關(guān)閉活動的代碼片段示例:
@AfterClasspublic void closeUp(){driver.close();}@BeforeSuite
一個套件可以包含多個類,此批注在所有類的所有測試方法之前運行。 該注釋標(biāo)記了執(zhí)行的入口點。 TestNG中的@BeforeSuite批注可用于執(zhí)行所需的通用功能,例如設(shè)置和啟動Selenium驅(qū)動程序或遠(yuǎn)程Web驅(qū)動程序等。
TestNG中@BeforeSuite批注的示例,顯示了設(shè)置驅(qū)動程序的代碼片段:
@BeforeSuitepublic void setUp(){System.setProperty("webdriver.chrome.driver", "path to chrome driver");driver=new ChromeDriver();}@AfterSuite
TestNG運行中的此注釋發(fā)布了所有類的所有測試方法。 當(dāng)您有多個運行中的類(例如,關(guān)閉驅(qū)動程序等)時,此注釋可用于在完成測試之前清理過程。
下面是TestNG for Selenium中@AfterSuite批注的代碼片段:
@AfterSuitepublic void cleanUp(){System.out.println("All close up activities completed");}@BeforeGroups
TestNG通過@Test批注中使用的屬性組幫助測試人員將一組測試按組創(chuàng)建。 例如,如果您希望將與用戶管理相關(guān)的所有相似功能組合在一起,則可以將所有測試(例如儀表板,配置文件,事務(wù)等)標(biāo)記為一個組,稱為“ user_management”。 TestNG中的@BeforeGroups批注有助于在指定的組之前先運行定義的測試。 如果小組專注于單個功能,如上面的示例中所述,則可以使用此注釋。 BeforeGroup批注可以包含登錄功能,該功能必須在用戶儀表板,用戶配置文件等任何其他方法之前運行。
Selenium的TestNG中@BeforeGroups批注的代碼片段示例:
@BeforeGroups("urlValidation")public void setUpSecurity() {System.out.println("url validation test starting");}@AfterGroups
TestNG中的此批注在指定組的所有測試方法執(zhí)行后運行。
Selenium的TestNG中@AfterGroups批注的代碼片段示例:
TestNG報告:
控制臺輸出:
硒中TestNG中注釋的執(zhí)行順序
上述所有注釋均按以下順序在運行時執(zhí)行:
- 之前的套房
- 測試前
- 課前
- 團(tuán)體前
- 方法前
- 測試
- 后方法
- 后組
- 下課以后
- 事后測試
- AfterSuite
這是這些注釋的基本工作流程的圖像:
TestNG中與注釋一起使用的屬性
TestNG中的這些測試注釋具有可用于我們的測試方法的多個屬性。 這些屬性還有助于定義我們的測試,并有助于提供在TestNG類中使用的不同測試方法的執(zhí)行流程方面的清晰度。 在下面列出它們:
- 說明:它定義了測試方法。 可以通過描述定義方法的作用。 例如,@ @Test(description=”this test validates the login functionality”) 。
- alwaysRun:此屬性與測試方法一起使用時,即使該方法所依賴的參數(shù)失敗,也可以確保它始終運行而不管事實。 當(dāng)該值設(shè)置為true時,此方法將始終執(zhí)行。 例如,@Test(alwaysRun = true)。
- dataProvider:此屬性設(shè)置為從帶數(shù)據(jù)提供者注釋的測試向使用此屬性提供的測試提供數(shù)據(jù)。 例如,假設(shè)您打算在多個跨瀏覽器上運行測試,其中編寫了一個帶數(shù)據(jù)提供者注釋的測試,其中包含瀏覽器及其相應(yīng)版本的多個輸入。 在這種情況下,包含此屬性的測試將使用這些數(shù)據(jù)輸入在多個瀏覽器上運行測試。 相同的語法是@Test(dataProvider =“跨瀏覽器測試”)。
- dependsOnMethods:此屬性提供執(zhí)行流程的詳細(xì)信息,其中僅當(dāng)執(zhí)行屬性中提到的依賴方法時,才執(zhí)行測試。 如果該方法所依賴的測試失敗或未執(zhí)行,則從執(zhí)行中跳過該測試。 例如,@Test(dependsOnmethod =“ Login”)。
- 組:此屬性有助于將專注于單個功能的測試方法分組。 例如@Test(groups =“ Payment_Module”)。 當(dāng)一個人可以選擇在執(zhí)行周期中忽略幾個組并選擇其他組時,此屬性還有助于延長運行時間。 所有需要做的就是在include標(biāo)記中提及TestNG.xml文件中的包含組,而可以使用xml文件中的exclude標(biāo)記來定義被排除的組。
- dependsOnGroups:此屬性按排序規(guī)則執(zhí)行上述兩個屬性功能,即,使用屬性“ dependsOn”定義已定義的組來定義測試方法。 一旦運行了那組測試,就只能發(fā)布該帶注釋的方法將要執(zhí)行的信息。 例如,@Test(dependsOnMethods =“ Payment_Module”)。
- 優(yōu)先級:此屬性有助于我們定義測試方法的優(yōu)先級。 當(dāng)TestNG執(zhí)行@Test帶注釋的方法時,它可能以隨機(jī)順序執(zhí)行。 在您希望您的@Test帶注釋的方法按所需順序運行的情況下,可以使用priority屬性。 所有測試方法的默認(rèn)優(yōu)先級均為0。升序排列的優(yōu)先級首先被安排執(zhí)行,例如@Test(priority = 1),@ Test(priority = 2),在這種情況下,將執(zhí)行優(yōu)先級等于1的測試首先,然后是優(yōu)先級為2的測試。
- enabled:當(dāng)您打算忽略特定的測試方法并且不想執(zhí)行它時,此屬性會出現(xiàn)。 您需要做的就是將此屬性設(shè)置為false。 例如,@Test(enabled = false)。
- 超時:此屬性有助于定義特定測試應(yīng)執(zhí)行的時間,如果超出該屬性定義的時間,則測試方法將終止并失敗,并帶有標(biāo)記為org.testng.internal.thread.ThreadTimeoutException的異常。 例如,@ Test(timeOut = 500)。 請注意,指定的時間以毫秒為單位。
- InvocationCount:此屬性的工作原理與循環(huán)類似。 基于測試方法中設(shè)置的屬性,它將多次執(zhí)行該方法。 例如,@Test(invocationCount = 5),它將執(zhí)行5次測試。
- InvocationTimeOut:此屬性與上面的invocationCount屬性一起使用。 基于此屬性的設(shè)置值以及invocationCount,這可以確保測試在由invocationTimeOut屬性設(shè)置的定義時間內(nèi)運行根據(jù)invocationCount指定的次數(shù)。 例如,@Test(invocationCount = 5,invocationTimeOut = 20)。
- ExpectedExceptions:此屬性有助于處理測試方法預(yù)期引發(fā)的異常。 如果屬性中定義的一個被測試方法設(shè)置并拋出,則傳遞該屬性,否則屬性中未聲明并由測試方法拋出的任何其他異常將使測試方法失敗。 例如,@Test(expectedExceptions = {ArithmeticException.class})。
上面定義的是與TestNG for Selenium中的注釋一起使用的屬性。 下面的代碼片段展示了上述屬性的用法:
import static org.testng.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;public class AnnotationsTest {public WebDriver driver;public String url="https://www.lambdatest.com/";@BeforeSuitepublic void setUp(){System.setProperty("webdriver.chrome.driver", "C:\\Users\\navyug\\workspace\\QAPractise\\src\\ChromeDriver\\chromedriver.exe");driver=new ChromeDriver();System.out.println("The setup process is completed");}@BeforeTestpublic void profileSetup(){driver.manage().window().maximize();System.out.println("The profile setup process is completed");}@BeforeClasspublic void appSetup(){driver.get(url);System.out.println("The app setup process is completed");}@Test(priority=2)public void checkLogin(){driver.get("https://accounts.lambdatest.com/login");driver.findElement(By.xpath("//input[@name='email']")).sendKeys("sadhvisingh24@gmail.com");driver.findElement(By.xpath("//input[@name='password']")).sendKeys("xxxxx");driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/button")).click();System.out.println("The login process on lamdatest is completed");}@Test(priority=0 ,description= "this test validates the sign-up test")public void signUp() throws InterruptedException{WebElement link= driver.findElement(By.xpath("//a[text()='Free Sign Up']"));link.click();WebElement organization=driver.findElement(By.xpath("//input[@name='organization_name']"));organization.sendKeys("LambdaTest");WebElement firstName=driver.findElement(By.xpath("//input[@name='name']"));firstName.sendKeys("Test");WebElement email=driver.findElement(By.xpath("//input[@name='email']"));email.sendKeys("User622@gmail.com");WebElement password=driver.findElement(By.xpath("//input[@name='password']"));password.sendKeys("TestUser123");WebElement phoneNumber=driver.findElement(By.xpath("//input[@name='phone']"));phoneNumber.sendKeys("9412262090");WebElement termsOfService=driver.findElement(By.xpath("//input[@name='terms_of_service']"));termsOfService.click();WebElement button=driver.findElement(By.xpath("//button[text()='Signup']"));button.click();}@Test(priority=3, alwaysRun= true, dependsOnMethods="check_login", description="this test validates the URL post logging in" , groups="url_validation")public void testCurrentUrl() throws InterruptedException{driver.findElement(By.xpath("//*[@id='app']/header/aside/ul/li[4]/a")).click();String currentUrl= driver.getCurrentUrl();assertEquals(current_url, "https://automation.lambdatest.com/timeline/?viewType=build&page=1", "url did not matched");System.out.println("The url validation test is completed");}@Test(priority=1, description = "this test validates the logout functionality" ,timeOut= 25000)public void logout() throws InterruptedException{Thread.sleep(6500);driver.findElement(By.xpath("//*[@id='userName']")).click();driver.findElement(By.xpath("//*[@id='navbarSupportedContent']/ul[2]/li/div/a[5]")).click(); }@Test(enabled=false)public void skipMethod(){System.out.println("this method will be skipped from the test run using the attribute enabled=false");}@Test(priority=6,invocationCount =5,invocationTimeOut = 20)public void invocationcountShowCaseMethod(){System.out.println("this method will be executed by 5 times");}@AfterMethod()public void screenshot() throws IOException{TakesScreenshot scr= ((TakesScreenshot)driver);File file1= scr.getScreenshotAs(OutputType.FILE);FileUtils.copyFile(file1, new File("C:\\Users\\navyug\\workspace\\QAPractise\\test-output\\test1.PNG"));System.out.println("Screenshot of the test is taken");}@AfterClasspublic void closeUp(){driver.close();System.out.println("The close_up process is completed");}@AfterTestpublic void reportReady(){System.out.println("Report is ready to be shared, with screenshots of tests");}@AfterSuitepublic void cleanUp(){System.out.println("All close up activities completed");}@BeforeGroups("urlValidation")public void setUpSecurity() {System.out.println("url validation test starting");}@AfterGroups("urlValidation")public void tearDownSecurity() {System.out.println("url validation test finished");}}控制臺輸出:
TestNG報告:
TestNG中用于預(yù)期目的的注釋
除了上面定義的注釋以外,還有更多注釋,這些注釋僅用于所需目的。
@DataProvider
該帶注釋的方法用于向定義了dataProvider屬性的測試方法提供數(shù)據(jù)。 此帶注釋的方法有助于創(chuàng)建一個數(shù)據(jù)驅(qū)動的框架,在該框架中可以提供多組輸入值,這些輸入值將返回2D數(shù)組或?qū)ο蟆?TestNG中的@DataProvider批注帶有兩個屬性。
- 名稱-此屬性用于為數(shù)據(jù)提供者提供名稱。 如果未設(shè)置,則默認(rèn)為所提供方法的名稱。
- 并行-這是一個屬性,可幫助您在不同數(shù)據(jù)變化的情況下并行運行測試。 此屬性是使TestNG對Junit更加強(qiáng)大的原因之一。 其默認(rèn)值為false。
下面的代碼段指示使用@DataProvider批注,并為其設(shè)置了名稱和parallel屬性。
@DataProvider(name="SetEnvironment", parallel=true) public Object[][] getData(){Object[][] browserProperty = new Object[][]{{Platform.WIN8, "chrome", "70.0"}, {Platform.WIN8, "chrome", "71.0"} }; return browserProperty;}@廠
此批注有助于通過單個測試類運行多個測試類。 它基本上可以動態(tài)定義和創(chuàng)建測試。
下面的代碼片段指示使用@Factory批注來幫助調(diào)用測試方法類。
package ChromeDriver;import org.testng.annotations.Test;public class FactorySimplyTest1 {@Testpublic void testMethod1() {System.out.println("This is to test for method 1 for Factor Annotation");}}package ChromeDriver;import org.testng.annotations.Test;public class FactorySimpleTest2 {@Testpublic void testMethod2() {System.out.println("This is to test for method 2 for Factor Annotation");} }package ChromeDriver;import org.testng.annotations.Factory; import org.testng.annotations.Test;public class FactoryAnnotation {@Factory()@Testpublic Object[] getTestFactoryMethod() {Object[] factoryTest = new Object[2];factoryTest[0] = new FactorySimplyTest1();factoryTest[1] = new FactorySimpleTest2();return factoryTest;}}控制臺輸出:
@參數(shù)
此注釋可幫助您直接通過testNG.xml文件將參數(shù)傳遞給測試。 通常,當(dāng)您有有限的數(shù)據(jù)集進(jìn)行測試時,這是首選。 如果數(shù)據(jù)集復(fù)雜而又龐大,則@dataProvider批注為首選或優(yōu)于excel。
下面的代碼片段展示了相同的內(nèi)容:
@Parameters({ "username", "password"})@Test()public void checkLogin(String username, String password){driver.get("https://accounts.lambdatest.com/login");driver.findElement(By.xpath("//input[@name='email']")).sendKeys(username);driver.findElement(By.xpath("//input[@name='password']")).sendKeys(password);driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/button")).click();System.out.println("The login process on lamdatest is completed");}參數(shù)值在TestNG.xml文件中定義,如下所示:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite"><test thread-count="5" name="Annotations"><parameter name="username" value="sadhvisingh24@gmail.com" /><parameter name="password" value="XXXXX" /><classes><class name="Parameter_annotation"/></classes></test> <!-- Annotations --> </suite> <!-- Suite -->@Listener
該注釋有助于記錄和報告。 我們有多個偵聽器,例如:
- IExecutionListener
- IAnnotationTransformer
- ISuiteListener
- ITestListener
但是深入了解這些聽眾及其用途將是另一個博客的話題。 我即將寫一封,敬請期待。
這就是全部了!
使用所有這些注釋和屬性時要注意的關(guān)鍵點是您的系統(tǒng)應(yīng)具有Java 1.5版本或更高版本,因為所有較低版本的Java都不支持這些注釋,并且您可能會收到錯誤消息。
以上所有上述TestNG的注釋和屬性有助于為代碼提供更好的結(jié)構(gòu)和可讀性。 它有助于提供詳細(xì)的報告,從而使?fàn)顟B(tài)報告變得更加輕松和有用。 在TestNG for Selenium中使用這些注釋完全取決于您的業(yè)務(wù)需求。 因此,選擇正確的使用方法很重要。現(xiàn)在就在LambdaTest Selenium Grid的TestNG中試用這些注釋!
翻譯自: https://www.javacodegeeks.com/2019/04/complete-guid-testng-annotations-selenium-webdriver.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Selenium WebDriver的TestNG注释完整指南的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: soap签名_签名SOAP消息–生成封装
- 下一篇: 美国满意度指数报告出炉:苹果蝉联 20