日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Selenium WebDriver的TestNG注释完整指南

發布時間:2023/12/3 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Selenium WebDriver的TestNG注释完整指南 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

TestNG是CédricBeust創建的測試框架 ,有助于滿足我們的許多測試需求。 它被廣泛用于硒中。 想知道NG代表什么? 好吧,它指的是“下一代” 。 TestNG與Junit相似,但在控制程序的執行流程方面更強大。 作為框架的本質,我們傾向于使測試更加結構化,并通過使用TestNG提供更好的驗證點。

TestNG的一些值得注意的功能是:

  • 功能強大且種類繁多的注釋可支持您的測試用例。
  • 幫助執行并行測試,相關方法測試。
  • 通過TestNG.xml文件或通過數據提供者概念通過多組數據運行測試的靈活性。
  • 測試用例可以根據需要進行分組并確定優先級。
  • 提供對HTML報告的訪問,并且可以通過各種插件進行自定義。
  • 可以跨測試生成測試日志。
  • 可以輕松地與eclipse,Maven,Jenkins等集成。

TestNG程序的基本處理流程包括以下步驟:

因此,在轉到TestNG for Selenium中的注釋之前,最好先參考設置TestNG所需的先決條件。

先決條件

  • Java開發套件
  • 設置Eclipse或任何其他IDE。
  • 在Eclipse或任何其他IDE中安裝TestNG。

注意:注釋只能與Java 1.5或更高版本一起使用。

如果您不熟悉TestNG框架,請按照我們的指南使用TestNG運行您的第一個自動化腳本 。

在云網格上運行TestNG Selenium腳本

那么,什么是注釋?

注釋是提供有關類或方法的其他信息的標簽。 它由“ @”前綴表示。 TestNG使用這些注釋來幫助創建一個健壯的框架。 讓我們來看看用于用Selenium進行自動化測試的TestNG的這些注釋。

@測試

主要業務邏輯所在的TestNG框架中最重要的注釋。 所有要自動化的功能都保留在@Test批注方法中。 它具有各種屬性,可以根據這些屬性來重新構造和執行該方法。

以下驗證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中使用此注釋來設置瀏覽器配置文件首選項,例如以最大化模式自動打開瀏覽器,為瀏覽器設置自己的自定義配置文件等。

下面是確保測試器以最大化模式打開的BeforeTest方法的代碼片段:

@BeforeTestpublic void profileSetup(){driver.manage().window().maximize();}

@AfterTest

TestNG中的此批注在您屬于該類的所有測試方法運行后運行。 這是一個有用的注釋,在向您的利益相關者報告自動化結果方面非常有用。 您可以使用此批注生成測試報告,并通過電子郵件將其分享給您的涉眾。

下面的代碼段示例:

@AfterTestpublic void reportReady(){System.out.println("Report is ready to be shared, with screenshots of tests");}

@BeforeMethod

TestNG中的此注釋在每個@test注釋方法之前運行。 您可以在執行測試之前使用它來簽出數據庫連接,或者可以說@test帶注釋的方法已經測試了不同的功能,該方法要求用戶登錄某個類。 在這種情況下,您也可以將您的登錄代碼放入@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"));}

@課前

該注釋在當前類的第一個測試方法之前運行。 此注釋可用于設置瀏覽器屬性,初始化驅動程序,使用所需的URL打開瀏覽器等。

以下是BeforeClass的代碼段:

@BeforeClasspublic void appSetup(){driver.get(url);}

@下課以后

該注釋在當前類中的最后一個測試方法之后運行。 TestNG中的此批注可用于在測試過程中執行清理活動,例如關閉驅動程序等

以下是顯示已執行的關閉活動的代碼片段示例:

@AfterClasspublic void closeUp(){driver.close();}

@BeforeSuite

一個套件可以包含多個類,此批注在所有類的所有測試方法之前運行。 該注釋標記了執行的入口點。 TestNG中的@BeforeSuite批注可用于執行所需的通用功能,例如設置和啟動Selenium驅動程序或遠程Web驅動程序等。

TestNG中@BeforeSuite批注的示例,顯示了設置驅動程序的代碼片段:

@BeforeSuitepublic void setUp(){System.setProperty("webdriver.chrome.driver", "path to chrome driver");driver=new ChromeDriver();}

@AfterSuite

TestNG運行中的此注釋發布了所有類的所有測試方法。 當您有多個運行中的類(例如,關閉驅動程序等)時,此注釋可用于在完成測試之前清理過程。

下面是TestNG for Selenium中@AfterSuite批注的代碼片段:

@AfterSuitepublic void cleanUp(){System.out.println("All close up activities completed");}

@BeforeGroups

TestNG通過@Test批注中使用的屬性組幫助測試人員將一組測試按組創建。 例如,如果您希望將與用戶管理相關的所有相似功能組合在一起,則可以將所有測試(例如儀表板,配置文件,事務等)標記為一個組,稱為“ user_management”。 TestNG中的@BeforeGroups批注有助于在指定的組之前先運行定義的測試。 如果小組專注于單個功能,如上面的示例中所述,則可以使用此注釋。 BeforeGroup批注可以包含登錄功能,該功能必須在用戶儀表板,用戶配置文件等任何其他方法之前運行。

Selenium的TestNG中@BeforeGroups批注的代碼片段示例:

@BeforeGroups("urlValidation")public void setUpSecurity() {System.out.println("url validation test starting");}

@AfterGroups

TestNG中的此批注在指定組的所有測試方法執行后運行。
Selenium的TestNG中@AfterGroups批注的代碼片段示例:

@AfterGroups("urlValidation")public void tearDownSecurity() {System.out.println("url validation test finished");}The below code displays an example of all annotations used along with TestNG report respectively: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.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 AnnotationsTestNG {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();driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);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");}@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("activa9049");driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/button")).click();System.out.println("The login process on lamdatest is completed");}@Test(groups="urlValidation")public void testCurrentUrl() throws InterruptedException{driver.findElement(By.xpath("//*[@id='app']/header/aside/ul/li[4]/a")).click();Thread.sleep(6000);String currentUrl= driver.getCurrentUrl();assertEquals(currentUrl, "https://automation.lambdatest.com/timeline/?viewType=build&page=1", "url did not matched");System.out.println("The url validation test is completed");}@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"));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中注釋的執行順序

上述所有注釋均按以下順序在運行時執行:

  • 之前的套房
  • 測試前
  • 課前
  • 團體前
  • 方法前
  • 測試
  • 后方法
  • 后組
  • 下課以后
  • 事后測試
  • AfterSuite

這是這些注釋的基本工作流程的圖像:

TestNG中與注釋一起使用的屬性

TestNG中的這些測試注釋具有可用于我們的測試方法的多個屬性。 這些屬性還有助于定義我們的測試,并有助于提供在TestNG類中使用的不同測試方法的執行流程方面的清晰度。 在下面列出它們:

  • 說明:它定義了測試方法。 可以通過描述定義方法的作用。 例如,@ @Test(description=”this test validates the login functionality”) 。
  • alwaysRun:此屬性與測試方法一起使用時,即使該方法所依賴的參數失敗,也可以確保它始終運行而不管事實。 當該值設置為true時,此方法將始終執行。 例如,@Test(alwaysRun = true)。
  • dataProvider:此屬性設置為從帶數據提供者注釋的測試向使用此屬性提供的測試提供數據。 例如,假設您打算在多個跨瀏覽器上運行測試,其中編寫了一個帶數據提供者注釋的測試,其中包含瀏覽器及其相應版本的多個輸入。 在這種情況下,包含此屬性的測試將使用這些數據輸入在多個瀏覽器上運行測試。 相同的語法是@Test(dataProvider =“跨瀏覽器測試”)。
  • dependsOnMethods:此屬性提供執行流程的詳細信息,其中僅當執行屬性中提到的依賴方法時,才執行測試。 如果該方法所依賴的測試失敗或未執行,則從執行中跳過該測試。 例如,@Test(dependsOnmethod =“ Login”)。
  • 組:此屬性有助于將專注于單個功能的測試方法分組。 例如@Test(groups =“ Payment_Module”)。 當一個人可以選擇在執行周期中忽略幾個組并選擇其他組時,此屬性還有助于延長運行時間。 所有需要做的就是在include標記中提及TestNG.xml文件中的包含組,而可以使用xml文件中的exclude標記來定義被排除的組。
  • dependsOnGroups:此屬性按排序規則執行上述兩個屬性功能,即,使用屬性“ dependsOn”定義已定義的組來定義測試方法。 一旦運行了那組測試,就只能發布該帶注釋的方法將要執行的信息。 例如,@Test(dependsOnMethods =“ Payment_Module”)。
  • 優先級:此屬性有助于我們定義測試方法的優先級。 當TestNG執行@Test帶注釋的方法時,它可能以隨機順序執行。 在您希望您的@Test帶注釋的方法按所需順序運行的情況下,可以使用priority屬性。 所有測試方法的默認優先級均為0。升序排列的優先級首先被安排執行,例如@Test(priority = 1),@ Test(priority = 2),在這種情況下,將執行優先級等于1的測試首先,然后是優先級為2的測試。
  • enabled:當您打算忽略特定的測試方法并且不想執行它時,此屬性會出現。 您需要做的就是將此屬性設置為false。 例如,@Test(enabled = false)。
  • 超時:此屬性有助于定義特定測試應執行的時間,如果超出該屬性定義的時間,則測試方法將終止并失敗,并帶有標記為org.testng.internal.thread.ThreadTimeoutException的異常。 例如,@ Test(timeOut = 500)。 請注意,指定的時間以毫秒為單位。
  • InvocationCount:此屬性的工作原理與循環類似。 基于測試方法中設置的屬性,它將多次執行該方法。 例如,@Test(invocationCount = 5),它將執行5次測試。
  • InvocationTimeOut:此屬性與上面的invocationCount屬性一起使用。 基于此屬性的設置值以及invocationCount,這可以確保測試在由invocationTimeOut屬性設置的定義時間內運行根據invocationCount指定的次數。 例如,@Test(invocationCount = 5,invocationTimeOut = 20)。
  • ExpectedExceptions:此屬性有助于處理測試方法預期引發的異常。 如果屬性中定義的一個被測試方法設置并拋出,則傳遞該屬性,否則屬性中未聲明并由測試方法拋出的任何其他異常將使測試方法失敗。 例如,@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中用于預期目的的注釋

除了上面定義的注釋以外,還有更多注釋,這些注釋僅用于所需目的。

@DataProvider

該帶注釋的方法用于向定義了dataProvider屬性的測試方法提供數據。 此帶注釋的方法有助于創建一個數據驅動的框架,在該框架中可以提供多組輸入值,這些輸入值將返回2D數組或對象。 TestNG中的@DataProvider批注帶有兩個屬性。

  • 名稱-此屬性用于為數據提供者提供名稱。 如果未設置,則默認為所提供方法的名稱。
  • 并行-這是一個屬性,可幫助您在不同數據變化的情況下并行運行測試。 此屬性是使TestNG對Junit更加強大的原因之一。 其默認值為false。

下面的代碼段指示使用@DataProvider批注,并為其設置了名稱和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;}

@廠

此批注有助于通過單個測試類運行多個測試類。 它基本上可以動態定義和創建測試。

下面的代碼片段指示使用@Factory批注來幫助調用測試方法類。

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;}}

控制臺輸出:

@參數

此注釋可幫助您直接通過testNG.xml文件將參數傳遞給測試。 通常,當您有有限的數據集進行測試時,這是首選。 如果數據集復雜而又龐大,則@dataProvider批注為首選或優于excel。

下面的代碼片段展示了相同的內容:

@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");}

參數值在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

但是深入了解這些聽眾及其用途將是另一個博客的話題。 我即將寫一封,敬請期待。

這就是全部了!

使用所有這些注釋和屬性時要注意的關鍵點是您的系統應具有Java 1.5版本或更高版本,因為所有較低版本的Java都不支持這些注釋,并且您可能會收到錯誤消息。

以上所有上述TestNG的注釋和屬性有助于為代碼提供更好的結構和可讀性。 它有助于提供詳細的報告,從而使狀態報告變得更加輕松和有用。 在TestNG for Selenium中使用這些注釋完全取決于您的業務需求。 因此,選擇正確的使用方法很重要。現在就在LambdaTest Selenium Grid的TestNG中試用這些注釋!


翻譯自: https://www.javacodegeeks.com/2019/04/complete-guid-testng-annotations-selenium-webdriver.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Selenium WebDriver的TestNG注释完整指南的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。