An annotation is a label that provides additional information about a class or method ( Translator's Note: in java, annotations can be used not only for classes and methods, but also for other elements ). For annotations use the prefix "@". TestNG uses annotations to help create a robust test structure. Let's look at TestNG annotations used to automate testing with Selenium.
@Test
@Test
. It has various attributes with which the start method can be configured. @Test public void testCurrentUrl() throws InterruptedException { driver.findElement(By.xpath("//*[@id='app']/header/aside/ul/li[4]/a")) .click(); String currentUrl = driver.getCurrentUrl(); assertEquals( currentUrl, "https://automation.lambdatest.com/timeline/?viewType=build&page=1", "url did not matched"); }
@BeforeTest
@Test
. (Translator’s note: as part of a test defined in the test
section of the xml configuration file) . You can use this annotation in TestNG with Selenium to configure your browser. For example, launch a browser and expand it to full screen, set specific browser settings, etc. @BeforeTest public void profileSetup() { driver.manage().window().maximize(); }
@AfterTest
@Test
methods of your test. ( Translator's note: in the framework of the test defined in the test
section in the xml configuration file, the “current class” is not quite correctly written in the original ). This is a useful summary that is useful for providing test results. You can use this annotation to create a report on your tests and send it to interested parties by email. @AfterTest public void reportReady() { System.out.println("Report is ready to be shared, with screenshots of tests"); }
@BeforeMethod
@Test
method . You can use it to test the connection to the database before running the test. Or, for example, when testing functionality that is dependent on the user's login, put the login code here. @BeforeMethod 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("activa9049"); driver.findElement(By.xpath("//*[@id='app']/section/form/div/div/button")).click(); }
@AfterMethod
@Test
method . This annotation can be used to create screenshots each time a test is run. @AfterMethod public void screenShot() throws IOException { TakesScreenshot scr = ((TakesScreenshot) driver); File file1 = scr.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(file1, new File(":\\test-output\\test1.PNG")); }
@BeforeClass
@BeforeClass public void appSetup() { driver.get(url); }
@AfterClass
@AfterClass public void closeUp() { driver.close(); }
@BeforeSuite
@BeforeSuite
can use the @BeforeSuite
in TestNG to perform common functions, such as setting up and running Selenium or remote web drivers, etc.@BeforeSuite
annotation in TestNG, demonstrating driver setup: @BeforeSuite public void setUp() { System.setProperty( "webdriver.chrome.driver", ":\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); }
@AfterSuite
@AfterSuite
annotation in TestNG for Selenium: @AfterSuite public void cleanUp() { System.out.println("All close up activities completed"); }
@BeforeGroups
@Test
annotation. For example, if you want all similar user-related functions to be combined together, you can mark tests, such as the dashboard (user panel), profile (profile), transactions (transactions) and the like, into one group, such as user_management. The @BeforeGroups
in TestNG helps to run certain actions in front of a specified group of tests. This annotation can be used if the group focuses on the same functionality, as indicated in the example above. The @BeforeGroup
may contain a login function that is required to run tests in a group, for example, testing a user panel, user profile, etc.@BeforeGroups
: @BeforeGroups("urlValidation") public void setUpSecurity() { System.out.println("url validation test starting"); }
@AfterGroups
@AfterGroups
annotation in TestNG for Selenium: @AfterGroups("urlValidation") public void tearDownSecurity() { System.out.println("url validation test finished"); }
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.*; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; public class AnnotationsTestNG { private WebDriver driver; private String url = "https://www.lambdatest.com/"; @BeforeSuite public void setUp() { System.setProperty( "webdriver.chrome.driver", ":\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); System.out.println("The setup process is completed"); } @BeforeTest public void profileSetup() { driver.manage().window().maximize(); System.out.println("The profile setup process is completed"); } @BeforeClass public void appSetup() { driver.get(url); System.out.println("The app setup process is completed"); } @BeforeMethod 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("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"); } @AfterMethod public void screenShot() throws IOException { TakesScreenshot scr = ((TakesScreenshot) driver); File file1 = scr.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(file1, new File(":\\test-output\\test1.PNG")); System.out.println("Screenshot of the test is taken"); } @AfterClass public void closeUp() { driver.close(); System.out.println("The close_up process is completed"); } @AfterTest public void reportReady() { System.out.println("Report is ready to be shared, with screenshots of tests"); } @AfterSuite public 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"); } }
Translator's Note:TestNG annotation execution sequence for Selenium
- To run the test, change the path to chromedriver.exe in the setUp () method and the path to the folder with the screenShot () method. Also for successful test execution in the checkLogin () method there must be a valid login and password.
- Used maven dependencies:
<dependencies> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.14.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-chrome-driver</artifactId> <version>3.141.59</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> <scope>test</scope> </dependency> </dependencies>
@Test
(description = ”this test checks the login”).@Test
(alwaysRun = true).@Test
(dataProvider = "cross-browser-testing").@Test
(depenOnmethod = “login”).@Test
(groups = ”Payment_Module”).include
tag, specify the groups that need to be run, and in the exclude
tag, which should be ignored.@Test
(depenOnMethods = "Payment_Module").@Test
(priority = 1), @Test
(priority = 2). In this case, the test will first be performed with a priority equal to one, and then a test with a priority of two.@Test
(enabled = false).@Test
(timeOut = 500). Note that the time is in milliseconds .@Test
(invocationCount = 5) will run 5 times.@Test
(invocationCount = 5, invocationTimeOut = 20).@Test
(expectedExceptions = {ArithmeticException.class}). import static org.testng.Assert.assertEquals; import java.io.File; import java.io.IOException; 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.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class AnnotationsTest { private WebDriver driver; private String url = "https://www.lambdatest.com/"; @BeforeSuite public void setUp() { System.setProperty( "webdriver.chrome.driver", ":\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); System.out.println("The setup process is completed"); } @BeforeTest public void profileSetup() { driver.manage().window().maximize(); System.out.println("The profile setup process is completed"); } @BeforeClass public 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( currentUrl, "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(":\\test-output\\test1.PNG")); System.out.println("Screenshot of the test is taken"); } @AfterClass public void closeUp() { driver.close(); System.out.println("The close_up process is completed"); } @AfterTest public void reportReady() { System.out.println("Report is ready to be shared, with screenshots of tests"); } @AfterSuite public 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"); } }
@DataProvider
@DataProvider
annotation has two attributes:@DataProvider
annotation with the given name and parallel attributes. @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
@Factory
annotation, which helps to invoke test class methods. import org.testng.annotations.Test; import org.testng.annotations.Factory; class FactorySimplyTest1 { @Test public void testMethod1() { System.out.println("This is to test for method 1 for Factor Annotation"); } } class FactorySimpleTest2 { @Test public void testMethod2() { System.out.println("This is to test for method 2 for Factor Annotation"); } } public class FactoryAnnotation { @Factory() @Test public Object[] getTestFactoryMethod() { Object[] factoryTest = new Object[2]; factoryTest[0] = new FactorySimplyTest1(); factoryTest[1] = new FactorySimpleTest2(); return factoryTest; } }
@Parameters
@DataProvider
or Excel annotation. @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"); }
<?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
Source: https://habr.com/ru/post/450872/
All Articles