Writing First Program with TestNG

In the previous post, we have learnt about TestNG annotations. In this Post, we will be writing First Program with TestNG.

Prerequisite: TestNG should be installed with Eclipse as shown in this post.

Let’s understand this step by step.

TestNG Program

Step#1 In Eclipse, go to the your package –> TestNG –> Create TestNG Class.

Create TestNG class

 

Step#2 Next window will come with annotations where you can select required annotations. We have selected @BeforeMethod, @AfterMethod and given a class name as “FirstTest”.

Select annotations in testNG

 

Step#3 Click Finish. The class will be created with the selected annotation. Look at the code below. One good point to observe here is that, there is one annotation @Test, which is added automatically with the method name as f().

You can change the method names according to your requirements.

Step#4 We have changed the method names as given below. These method will perform according to the annotations set for them. As an example @BeforeMethod will be executed before all the methods in the class. @AfterMethod will be executed after all the methods in the class. @Test will be executed as part of test case.

For better understanding, we have given simple print statement. So, It will be easy for you to understand their working.

How to run TestNg class?

Right Click on the Class –> Run As –> TestNG Test.

Run As TestNG

Output:

Start the car
Drive the car
Stop the car

As you can observe the output, first @BeforeMethod is executed, then @Test method, and in last @AfterMethod. So, in this way you can use the annotations.


Now, let’s see some practical implementation with an example. We will take Gmail Application as our demo AUT and perform Login functionality.

  • @BeforeMethod: Method will contain driver initialization code.
  • @AfterMethod: Clean up code like closing the driver after execution.
  • @Test: Gmail Login code.

Gmail login

Program for Gmail Login using TestNG:

Output: 

Intializing FirefoxDriver
Login into Gmail
Close the browser
PASSED: Login
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
=============================================== ===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0 ===============================================

Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Annotations in TestNG
Building a Test Suite in TestNG
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...