161. Using TestNG Annotations in Selenium WebDriver code






Once after the TestNG software is installed, we have to add TestNG annotations to the Selenium Automated Tests in order to Run them using TestNG.

TestNG Annotations list:

1.   @Test
2.   @BeforeMethod
3.   @AfterMethod
4.   @BeforeClass
5.   @AfterClass
6.   @BeforeGroups
7.   @AfterGroups
8.   @BeforeSuite
9.   @AfterSuite
10. @Parameters
11. @DataProvider
12. @Factory
13. @Listerners

To start with lets use the following TestNG Annotations in our Selenium RC Tests:

  • @Test
  • @BeforeMethod
  • @AfterMethod

@Test

Java Method in the Class that is annotated with this annotation will be marked as a test method.

@BeforeMethod

Java Method in the Class that is annotated with this annotation will run before each test method.

@AfterMethod 

Java Method in the Class that is annotated with this annotation will run after each test method.


Implement the @Test , @BeforeMethod and @AfterMethod annotations in Eclipse IDE by following the below steps:

Test Description:

Please go through the comments on the below screenshot to understand the test description.



Importing TestNG Annotations:

Please follow the below steps for importing the TestNG annotations:

1. After specify TestNG Annotation before a method, observe that the TestNG has thrown an error as shown below:


2. Hover your mouse cursor over the error text and import the BeforeClass annotation from TestNG class instead of from JUnit class as shown below:


3. Ensure that the following import statement got added as shown below:



Lets Implement This:

Pre-requisites:

1. Create a new Project say 'WebDriver-Project78' in Eclipse IDE
2. Configure the Project to work with Selenium WebDriver
3. Create a package say 'package78' under the newly created project.
4. Create a Java Class file say 'Class78' under the newly created package as shown below:



Actual Steps:


1. Lets write the code containing TestNG annotations @BeforeMethod , @Test, @AfterMethod as shown below:



2. Now write the test code into the test method (i.e. The method that is annotated with @Test annotation) as shown below and observe that an error is displayed as shown below:


3. Lets resolve the error first. Click on the Error icon and select Add static import 'org.testng.AssertJUnit.assertTrue' from the list and save as shown below:


4. Ensure that the error got resolved and the import statement got added as shown below:



5. Save the 'Class78.java' file and Run it using the 'TestNG' as shown below:


7. Ensure that our test has run by TestNG and the results shown in the 'TestNG' tab are passed as shown below:



Watch the below video:

Click here to watch the video.

Download this Project:


Click here to download this project and import into Eclipse IDE  on your machine.


Please comment below to feedback or ask questions.

Non-Refactored Selenium Automation Code using TestNG framework  will be explained in the next post.






Followers

Labels