Where we learn technology

Tag: TestNG

API/WebServices – BackEnd Manual & Automation Testing – Regular Batch – 11th July 2024 – 8 PM IST / 10:30 AM EST / 7:30 AM PST)

WebServices – Back End API Manual & Automation Training Course Content

Starting Date: July 11th, 2024

API Testing Training/Boot Camp:

The API testing batch/boot camp training for API/WebServices – Back End Manual & Automation Testing is a crucial training for individuals who want to enhance their skills in API testing. This training will cover essential topics related to API testing such as HTTP methods, RESTful APIs, JSON/XML, authentication, authorization, error handling, and much more. Candidates will learn both manual and automated testing methods for APIs.

Who can attend this training?

This training is perfect for software testers, quality assurance engineers, developers, and anyone interested in gaining knowledge and skills in API testing. Candidates will learn how to test APIs effectively, identify defects, and ensure that APIs are functioning as expected.

Additionally, this training will help individuals gain a competitive advantage in their careers by acquiring new skills and knowledge.

Why should I join this?

By attending this training, individuals will be better prepared for API testing interviews as they will have a solid understanding of API testing concepts, methods, and tools. They will be able to apply their knowledge to real-world scenarios and will have hands-on experience with various testing tools used in the industry. Overall, this API testing batch/boot camp training is an excellent investment for individuals looking to enhance their career opportunities and take their skills to the next level.

Next Batch Starting from: 11th July, 2024

Duration: 9-10 Weeks

Location: Online (zoom meeting) 

Duration: 3 days in a week (1.5 hrs) – Mon – Wed – Thursday

Timings

    • 8:00 PM IST (Indian Time)

    • 10:30 AM EST (USA Eastern Time)

    • 7:30 AM PST (USA Pacific Time)

    • 9:30 AM CST (USA Central Time)

    • 3:30 PM UK TIME

Registration Fee: For Candidates in India : 3000 INR

For Candidates in USA/UK/NZ/AUS/Europe : 55 USD

Remaining Course Fee

    • 12000 INR (For Candidates in India)

    • 200 USD (For Candidates in US/UK/NZ/AUS/Europe)

Note:

    • There will be 2 demo sessions. If you don’t want to proceed with the training, full Registration amount will be refunded back to you.

    • After 2 demo sessions, remaining amount (12000 INR/200 USD) must be paid accordingly.

    • For any query, whats app at: +91-9902233400.

 
Here I’m sharing the payment details. Please send me the screenshot of receipt once you make the payment without fail. 
You need to mail me at : naveenanimation20@gmail.com

 Payment Options:

CANDIDATES IN INDIA:
1. Pay by Credit/Debit Card:
If you want to use credit card/debit card, please use this secured stripe payment link:

REGISTRATION FEE (3000 INR):
https://buy.stripe.com/28obL2bjD6Ww5RC4hC

REMAINING FEE(12000 INR):
https://buy.stripe.com/4gwcP60EZ4Oocg015j

Or you can pay total fee (15000 INR):  
https://buy.stripe.com/00g16o3Rb3Kk93O9BR
2. BANK TRANSFER:

Bank Details:
Full Name: NAVEEN KHUNTETA

Payee name: NAVEEN KHUNTETA

Name of the Bank: ICICI bank

Address of the Bank: Bhandarkar Road, Pune

Bank Account Number: 624001553272

IFSC Code(11 Digit Code): ICIC0006240

3. Pay by GPay/PhonePe/Paytm/UPI:

ph: 9902233400 / 9828866542
======================================
CANDIDATES IN USA/CANADA/UK/EUROPE/AUS/OTHERS:
1. If you want to use credit card/debit card, please use this secured stripe payment link:
REGISTRATION Fee (55 USD):
https://buy.stripe.com/5kA5mEgDX4Oodk44hD
Remaining Fee(200 USD): 
https://buy.stripe.com/fZe5mEfzTeoY6VGdSe
You can pay full amount (255 USD):
https://buy.stripe.com/3cscP63Rb0y84Ny15t
2. Bank Transfer:

Please find below bank details. You can make the transaction directly to the given account or make it via Western Union (only via bank transfer) / Xoom/ Remitly or any other remittance.


Bank Details:

Name: Naveen Khunteta

Bank Account Number:  1015794367401

IBAN Number:  AE520260001015794367401

City/Country: Dubai, UAE

Swift Code: EBILAEAD

Address: Naveen automation labs FZCO, Scaltiy, building 9W, DAFZA, Dubai, UAE - 000001
3.  Paypal:
Total payment: 265 USD
Use this PayPal id: https://paypal.me/naveenautomation
Check out with PayPal
Note: If you are paying through PayPal, You need to pay 265 USD (10 USD will be the PayPal Fee).
 
 

Syllabus Course Content:

Course Content:

 Testing of WebServices/API:

  1. Introduction of API and WebServices:
    1. What is API
    2. What is WebService
    3. What is Backend Architecture
    4. Rest vs SOAP APIs
    5. What is CRUD operation with different examples
    6. What are different HTTP Calls – GET/POST/PUT/Delete/PATCH/HEAD/OPTIONS
    7. Different Live Projects Examples
  2. Postman:
    1. Introduction
    2. How to call Rest API in Postman
    3. How to pass path parameter in Request
    4. How to pass query parameter in Request
    5. How to set Headers in Postman
    6. How to pass JSON/XML Payload
    7. How to check response status code
    8. How to check JSON/XML response messages
    9. What is response header
    10. Cookies manipulation
    11. Header Presets
    12. API History in Postman
    13. Postman Environment Variables
    14. Postman Test Scripts using Javascript and  Chai Assertions
    15. Run Automated Test Cases in Postman and generate the results
  3. Advance Postman/Newman:
    1. Introduction of Newman
    2. Newman installation/setup
    3. How to run collections from Newman
    4. Newman command line options
    5. Generate HTML Test Report
    6. Create a collection and folders
    7. Create a collection from API Specification or API Schema
    8. maintenance of API collections
    9. Postman Console and logs
    10. Test Script in postman
    11. Pre Request Script in postman
    12. Test Code snippet in postman
    13. Monitoring of APIs
    14. API Documentation
    15. API Documentation/CODES in different programming languages
    16. Publish Documentation
    17. Setup Environment – Local and Global
    18. Collection Runner
    19. Collection Test Summary
    20. Creating a Mock Server for APIs
    21. How to create a team workspace
    22. How to create individual workspace
    23. Import in Postman
    24. Basic and Advanced Settings in Rest Client
    25. Running postman collection with Docker
    26. Running postman collection with Jenkins
  4. How to check APIs at the network layer using developer tools of browser:
    1. How to check Backend services – APIs running behind
    2. What is developer tool in Chrome
    3. How to check request/response of any API in Firefox/Chrome browsers
  5. What are different HTTP Status Response Codes:
    1. 1xx series
    2. 2xx series
    3. 3xx series
    4. 4xx series
    5. 5xx series

Automation Testing of Back End/APIs:

  1. Learn various HTTP Client libraries :
    1. Tools/Library: JDK 11 – HTTP Client
    2. All CRUD – GET/POST/PUT/Delete Calls
    3. How to send Request with Payloads
    4. How to send Query Parameters and Path Parameters
  1. Learn Rest Assured DSL Java Client API:
    1. Introduction of Rest Assured
    2. Rest Assured methods: GET/POST/PUT/Delete/Patch
    3. Handle different payloads using POJO and JSON/XMLs:
    4. Request with Simple JSON format
    5. Request with Complex JSON format
    6. Handle Authentication using Basic Auth, Preemptive Auth, Digest Auth, Bearer Token, Authorization Token, Client ID, Client Secret, API Key, API Secret, OAuth1 and OAuth2
    1. All core features of Rest Assured Library:
      1. GET/POST/PUT/DELETE – Inbuilt BDD Approaches
        1. What is GIVEN/WHEN/THEN/AND methods
        2. What is LOG and ALL methods
        3. How to ASSERT in Rest Assured
        4. How to verify Status Code, Response Body and Headers
        5. How to use QUERY PARAMETERS and PATH PARAMETERS
        6. What is ResponseBuilderSpec and RequestSpecification Concept
        7. What is JSON PATH/XML Path
        8. What is EXTRACT method
        9. How to send a POST CALL with JSON String, JSON File and using Java (POJO) Class.
        10. What is Serialization and De-Serialization
        11. How to use HAMCREST – Assertion Library
      2. GET/POST/PUT/DELETE – NON-BDD Approaches
    2. New End to End Framework using Rest Assured using different real time APIs:
      1. How to setup a Maven Project for APIs
      2. Folder Structure
      3. API Test Automation Design and components
      4. Rest Client Libraries
      5. Write API Automated Tests with TestNG
      6. Data Providers with Parameterization
      7. Data Driven Testing with Excel Files – using Apache POI API
      8. Test Runners with testng.xml
      9. Various Constants Files for Errors, Status Codes, Validation, and Success Messages
      10. Create a GIT Repo for Test Automation project:
        • Create a New Repo
        • Clone a Repo
        • GIT PUSH
        • GIT PULL
        • GIT Check OUT
      11. Integration with Jenkins – CI CD Pipeline and Automation Job
      12. Create the docker Image of API Test Automation
      13. Host/Register docker image to Docker HUB
      14. Download the docker image and Run it on any machines
      15. Advanced Reporting : Extent Report/TestNG Report/Allure Report
      16.  Maven: Build Automation Tool: Run your API Automation Framework from Maven
      17. TestNG Framework for API test cases

8. Mocking APIs using Wiremock library:

  1. Define the dummy APIs
  2. Define API Mock Behaviour for GET/POST Calls
  3. Call Mocking APIs 
  4. Integrate it in your Test Automation

9. Real Time API Examples:

  1. GORest APIs with Authentication
  2. ReqRes.in
  3. Booker APIs
  4. Weather APIs
  5. IMDB APIs
  6. Weather/Forecast Real Time APIs
  7. OAuth APIs
  8. GIT HUB APIs
  9. Twitter APIs
  10. API with Swagger

10 . Life Time Free Access on all the Videos/Recordings/Codes/Notes/PDFs/Cheat Sheets.

 
Cheers!
Naveen AutomationLabs
 

3. How to write Selenium WebDriver Test with TestNG – Maven Project

You might be wondering when Selenium WebDriver itself is such a powerful web automation tool, why do we need TestNG. Well, the fact is that it is indeed a powerful automation tool, however it lacks various capabilities such as ability to group, parameterize, sequence and generate reports. This is where tools like TestNG and JUnit come into play. These tools have inherent capabilities to organize and execute scripts as per the need of different test phases, arrange and execute them in a logical sequence as needed per the business requirements.

In the previous section, we have seen how to use TestNG with simple Java project. In this section let us see with Selenium WebDriver project in Eclipse IDE.

Step1. Go to Eclipse IDE, right click on the Package Explorer, select New and Click on Project option.

Step 2. You will see New Project window, select Maven Project and click on Next button

Step3. Select ” Create a simple project (skip archetype selection)” and click on next button.

Step 4: Provide Group ID, Artifact ID, Name and Description as shown in the below screenshot

Step 5. Click on Finish button.

Maven creates the Project structure as shown in the below screenshot

Step 6. Maven reads pom.xml file and executes the project. Pom.xml is the file which contains project and configuration details such as dependencies, build directory, plugins, goals etc. to build the maven project. So we need to add TestNG and Selenium WebDriver jar files’ details in the dependency section as shown below.

You might notice that we have added one more dependency i.e, webdrivermanager. Let’s quickly see what is the WebDriverManager.

You probably know that in Selenium Webdriver, to use browsers such as Chrome, Firefox, Safari etc., first we need to download the driver i.e, a binary file that allows WebDriver to handle browsers. And we should set the path of these files in the code as shown below

System.setProperty(“webdriver.chrome.driver”,”/path/to/chromedriver”);

System.setProperty(“webdriver.gecko.driver”,”/path/to/firefoxdriver”);

In addition to this, we need to check manually when the new version of the driver binaries released. WebDriver manger has automated this process for us to overcome this manual process. We just have to add the dependency and include the code as shown below.

WebDriverManager.chromeDriver().setup();

WebDriverManager.firefoxDriver().setup();

Step 6. We also need to add TestNG library in the Java build path. Let’s do it.In the Package Explorer, select the project, right click on it. Then go to Properties->Java Build Path->Add Library-> Select TestNG-> Next->Finish.

Note : All dependency jar files are downloaded in “Maven Dependencies” folder in the Project directory.

Step7. Now we are good to write the code. Remember all our TestNG, test related code goes in the src/test/java folder. We can either create a new Java class or a TestNG Class.

To create Java class, right click on the folder-> new ->Java class->Give a class name and click on Finish.

To Create TestNG class,right click on the folder->Others->select TestNG class as shown below

Provide the details and select the required annotations in the New TestNG class window as shown below and click on Finish button.

If you have created Java project, you need to write the required annotation along with Selenium Webdriver methods. If you have created the TestNG class along with required annotations, you might have to rearrange the annotations as per your testing needs. In additon to this, you can also include other annotations if needed. Let’s see a sample code.

Step 1. Create two class files called SeleniumTestNGDemoTest.java and BaseTest.java files .Write codes to verify “Sign in” link and “Google Search “button in the Google webpage.

Step2: Go to BaseTest.java, write Selenium WebDrivercode code to initialize the WebDriver, launch the browser and navigate to the Google Website. These are pre-test condition to execute the test cases. Also write one post-test condition, i’e, to close the browser as shown below.

Step 3: Go to SeleniumTestNGDemoTest.java, write the selenium code for the above mentioned test cases. Refer the below screenshot for the same.

Step 4. Create a testng.xml file as shown below and run the testng.xml file. If you don’t know how to execute the TestNG projects, please refer my earlier article.

In the Console, you can see that it is executed successfully.

Also, you can check status of the test cases that are passed, failed or skipped in the Results tab as shown below.

The report generated will be saved in the index.html under test-output folder. You can refresh and check this folder. In the next article, we will see how to prioritize the test cases and then understand the TestNG reports in detail.

1. What is TestNG and How to install it

TestNG is an open source Java testing framework which is distributed under the Apache Software License and is readily available for download. TestNG is inspired by JUnit which was the most widely used testing framework for Java applications. Despite being an easy to use and straightforward framework, JUnit has its own limitations which gave rise to TestNG. It was created by Cedric Beust to simplify a broad range of testing needs.

TestNG takes care of needs across testing lifecycle including unit testing, functional testing and Integration testing etc. The “NG” in TestNG stands for ‘Next Generation” implying that, is a next generation testing framework and it is more powerful than JUnit when it comes to parallel testing, reporting and managing dependencies. This article makes an effort to elaborate the above said aspects in further details.

TestNG Features

Some of the key features include

  • Control over test execution with powerful annotations
  • Help achieve parallel testing
  • Ability to set dependencies on methods
  • Support for parameterize
  • Support for Data Driven Testing using data providers
  • Generate test logs across tests
  • Excellent reporting ability
  • Can be integrated with Eclipse, Maven, Jenkins etc

How to get started with TestNG

Before learning TestNG, you should have the basic knowledge of automation testing and any automation tools that supports Java. Here we are going to learn TestNG framework with Selenium WebDriver hence knowledge of the same is essential.

TestNG can be integrated with Simple Java project or Maven Integrated Java Project. Before we start writing the automation test scripts, let’s see the steps involved to automate the testcases and its execution.

Step 1: Write the business logic of your test

Step 2: Insert TestNG Annotations in your test code to control the flow of test cases to follow the business logic

Step 3: Validate test cases with TestNG assertion

Step 4: Add details of testcases in the testNG.xml file

Step 5: Run your Tests

Step 6: View the results in HTML reports

We are going to create Java project and integrate TestNG, hence make sure Jdk1.8 and Eclipse IDE is installed in your machine. Note:The example shown are written and executed in Windows 10, 64 bit system.

How to install TestNG

Generally, TestNG comes as jar files. There are two ways of installing TestNG in Eclipse.

  1. Directly from the Eclipse Marketplace
  2. Through Help -> Install New Software option

How to Install TestNG through Market place

This option is available in new versions of Eclipse. This is the recommended method as it is the easiest method to install TestNG compared to the other installation method.

Step 1: Launch Eclipse IDE, click on the Help menu, select the “Eclipse Market place…” option in the dropdown

Step 2:  In Eclipse Marketplace dialog box, you see “Find” input field, enter “TestNG” and hit the enter key to search.

Step3: Now, you’ll see “Install” button for all search results. Click on “Install” button of TestNG for Eclipse as shown in the above screenshot and proceed with the installation . It will take some time ..so be patient ;).

Step 4: Click on “I accept the terms of the license agreement” and then click Finish.

Step 5: If you see a security warning, ignore it by clicking the OK button. 

Now, wait for the installation to finish.

Step 6: After the installation, Eclipse will prompt you to restart, just click Yes.

How to verify TestNG Installation

There are multiple ways to verify the successful installation of TestNG.

One way is to launch the Eclipse, navigate to “Preferences” from “Window” option in the menu bar, see TestNG listed. Refer the below screenshot for the same.

Another way to verify is to right click on the project in Project Explorer section, you will see TestNG listed as shown below.

How to install TestNG Plugin in Eclipse using the “Install New Software…” feature.

Step1. Launch the Eclipse IDE, Go to Help menu and click on “Install New Software”..

Step2. It will launch an Install window as shown below.

Step 3: You need to copy the build path url from the site https://github.com/cbeust/testng-eclipse. So, go to the site and copy the stable release url from Update sites’ section as shown below

Step 4: Come back to the Eclipse IDE and paste it in “Work With” input box. You will see that the TestNG option listed as shown below. Select the TestNG option and click on Next button and continue the installation process, accept the licence agreement and click on Finish button. If you see a security warning, just ignore and accept it by clicking the OK button. Once the installation is complete, Eclipse will prompt you to restart it. Click on Yes to restart.

Step 5: After the restart, to verify the successful installation of TestNG plugin follow the same procedures mentioned in the First method of installation.

 In the next section, we will see how to write TestNG code to build Test framework with simple Java and Selenium WebDriver project with Eclipse IDE.

2. How to Create TestNG Class with Different Annotations

As mentioned in earlier section, TestNG can be integrated with Simple Java project or Maven Integrated Java Project. First, we will see with a simple Java project.

  1. Go to the Eclipse IDE, create a new Java project. Right click on the Package Explorer panel, Select New option and then click on Project. You will see a New Project Wizard, select Java Project listed under Java Section, click on Next button, now you will be asked to provide the project name. Write the project name in Project Name input box and click on Finish Button.
  2. You will see that project is created in the Package Explorer along with default “src” folder in it.
  3. At this stage, we need to Integrate TestNG plug-in to the current project. So right click on the Project Name, go to Properties-> Java Build path-> Click on Add Library option, select TestNG and click on “Next” button and “Finish”. Finally click on “Apply and Close” button to close the Properties window.
  4. Create a new package under src folder. Then create a new Java class without the Main method.
  5. Write the below code in it.
TestNG Annotations

After writing the codes, you will notice that TestNG annotations are underlined with red, it means that the Eclipse IDE doesn’t know which library to refer for, just place the cursor over it, and select import from “org.testng.annotations” as show in the below screenshot to import.

How to use TestNG Annotations

An annotation is a tag that provides additional information about the class or method. It is represented by ‘@’ prefix. TestNG uses these annotations to help create a framework. Below listed are some of the most widely used annotations in test framework.

@Test

The test scripts (test methods) where the main business logic resides, should be tagged with @Test annotation. It has various attributes based on which the method can be reformed and executed which we will see later. By default, these @Test methods are executed in alphabetical order.

@BeforeSuite

A Test suite consists of multiple classes, this annotated method will be run before all the tests methods of all the classes implemented in the test suite. This annotation marks the entry point of execution. @BeforeSuite annotation in TestNG can be used to perform the needed generic functions like setting properties in configuration files and starting Selenium driver or initializing the logging procedure which are necessary. It is executed only once in the test execution hierarchy

Example:

@BeforeTest

This annotated method will be run before your first @Test annotated method in your class (and after @BeforeSuite if used  in the code) You can use this annotation to launch the browser, setting up your own customized profile for your browser etc. that are must to run the test scripts. This annotated method is executed once for every tests defined in the <test> tag in testng.xml file. (We will see what Testng.xml file in further section)

Example:

@BeforeClass

This annotated method will be run before any @Test method of that class is executed but after @BeforeTest method. We can use this to go to the application website or anything that you would like perform/ set before executing the test scripts.

Example:

@BeforeMethod

This annotated method will be run before every @test annotated method. You can use it to login to the application before executing your tests.

@AfterMethod

This annotated method will be run after every @test annotated method. You can use it to logout from the application after executing your tests. It can also be used to take screenshot of every method execution

Example:

@AfterClass

This annotated method will be run after all @Test methods of the class is executed but before @BeforeTest annotated method is run. This annotation can be used to delete cookies or some that you want to do at class level

Example

@AfterTest

This annotated method will be run after all test method belonging to the classes inside the <test> tag in testNG.xml file is run. It can be used to close the browser or anything that you want to do after the execution of all test methods.

@AfterSuite

This annotated method will be run after all tests in this suite have run. This annotation can be used to clean up the processes before completing off your tests when you have multiple classes in functioning.

Example:

You can customize all the above annotated methods as per you testing needs. To summarize these, @Before annotated method behave as pre-test conditions, @After annotated methods behave as post-test conditions and @Test annotated method is where the business logic resides and it is executed in the alphabetical order by default

When you run the above code, the output will be as shown in the below screenshot

Example:

As explained in the above section, first all pre-test conditions are executed.

@BeforeSuite annotated method is executed only once before all other annotated methods’ execution.  

@BeforeTest:  It is executed only once since we have created only one   <test > tag defined. It is explained in the further section.

 @BeforeClass:  It is executed before any @Test annotated method execution of the current class. In the above example there is only one class so only once it is executed, next

@BeforeMethod, before every @Test annotated method. In our example we have two @Test annotated methods so twice it is executed.

Next, @Test annotated methods are executed.

Finally, post-test conditions are executed in the below order

@AfterMethod: It is executed after every @Test annotated method. In our example there are two @Test annotated methods so twice it is executed after each testcases

@AfterClass: After all the @Test annotated methods of the current classes are executed. In the above example only one class is defined so only once it is executed

@AfterTest: It is executed after all @Test annotated method from all classes have been executed

@AfterSuite is executed in the end.

Let’s see how  to execute this project in the next section.

5. How to Run TestNG Class from Command Line and Eclipse

Let’s understand how the TestNG project can be executed. Since it doesn’t contain Java main method, it can’t be run as Java Application. We can run in the below two ways.

1. Through Eclipse IDE

2. Through Command line.

How to run TestNG project from Eclipse IDE

We can use one of the below mentioned methods.

  • Run as TestNG Test
  • Create Testng.xml and execute it

Run as TestNG Test:

  1. From the editor’s area: Right click on the editor’s area where the TestNG code is written, select Run As-> TestNG Test.
  2. From the Package Explorer: This method can be used to run single or multiple classes.

Go to Package Explorer in the Eclipse IDE ->select single/ multiple classes/ test package, right click on it -> Choose Run As->TestNG Test

3. From the Menu bar, Click on Run button .

Refer below screenshot for the above-mentioned methods.

Different ways to run TestNG project

When TestNG file/files are run in the above-mentioned ways, TestNG creates a default Testng.xml file and executes the test.  This default testng.xml can be located in two places.

  1. In the index.html file
  2. Under test-Ouput folder

1. TestNG will generate a default report that can be viewed in index.html file present under test-Output folder. Right click on the Project in the Package explorer and Refresh after TestNG project is executed. Copy the path of the index.html file and open it in the browser. [Note: We will go through index.html file in detail in the further section]

2. Right click on the Project in the Package explorer and click on Refresh after TestNG project is executed. Go to test-Output folder under Project directory. Expand it, then go to old-Default suite. You will see textng.xm.html file. Open it and check the code.

How to run TestNG project through command line.

In order to run Testng.xml file through command line, we need testng.jar and jcommander.jar files.  These jar files can be searched and downloaded from https://mvnrepository.com/.

Once it is downloaded, place it in “libs” folder under your Eclipse project directory. Before we run it, we need to compile our project. The compiled code can be found in “bin” folder under the project directory. We can execute the TestNG project in two ways. Either you set the class path first for lib and bin folder and then execute or combine both the commands in one step. Both the ways are shown below. So go to command prompt,

Step 1.  set classpath=[Project Folder]\bin;[Project Folder]\libs\*   

Step 2. java org.testng.TestNG testng.xml

Or

Step 1. java -cp “.\bin;.\libs\*” org.testng.TestNG testng.xml

For example:  Navigate to project folder and type the below command

or navigate to project folder and the type the below command

Text Box: java -cp “.\bin;.\libs\*” org.testng.TestNG testng.xml

We can execute multiple testng.xml files just by appending it.

Example:

Please refer below screenshot for command line execution

In the next section, we will see how to create Testng.xml and execute it through Eclipse IDE .

4. How to create and run TestNG project through Testng.xml

TestNG.xml file is a configuration file that helps organizing our tests. It allows testers to create and handle multiple test classes, define test suites and tests. Also, we can achieve parallel testing and parameterize test cases through Testng.xml which we will see later sections. Let’s see how to create tesng.xml file.

Go to project folder, right click on it, select TestNG option listed and click on Convert to TestNG as shown in the below screenshot.

On clicking “Convert to TestNG” option, you will see the below dialog box as shown in the below screenshot. Click on Finish button to finish .

Here is the sample of testng.xml file

Example 1:

Let us understand the different components of testng.xml file.

Suite: A Suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag. Example:

verbose: It is used to log the execution details in the console. The value should be 1-10. As you increase the value of verbose attribute, you will get more detailed log in the console window.

Test: A Test is represented by <test> and can contain one or more TestNG classes.Example:

Class : TestNG class is a Java class that contains at least one TestNG annotation. It is represented by the <class> tag and can contain one or more test methods.Example :

Test Method: A Test method is a Java method annotated by @Test methods in the source file. Example:

Example 2

We can specify package names instead of class names: In this example, TestNG will look at all the classes in the package “test.sample” and will run only classes that have TestNG annotations.

How to Run Testng.xml in the Eclipse IDE

Select the testng. xml file in the package explorer, right-click on it, move to Run As option and then select TestNG suite option.

How to create multiple classes, packages and execute TestNG suite

  1. Launch the Eclipse IDE, create a Java project, create two packages under src folder. Say Basic Features and TestUtility.
  2. Create three classes in Basic Features package say LoginPageTest.java, HomePageTest.java and SearchPageTest.java
  3. Create one class in TestUtility package, say BaseTest.java
  4. Write the below codes in the classes
  5. Create Testng.xml and execute it.

Refer below folder structure in the Package Explorer

Now, write the below codes in the respective class files as shown below

Next, create testng.xml file as shown below

Now, execute the testng.xml file and you will see the below output

Let’s have a look at the execution order in the above project.

First, all pre-test Conditions are executed . In the above example, it is defined in BasePageTest.java and is executed in the below mentioned order

  1. @BeforeSuite: It is executed before executing any of the @Test annotated methods and any @Before annotated methods. It is executed only once.
  2. @BeforeTest: It is executed before all the classes included in the test included in  <test> tag. In the above case it is <test thread-count=“5” name=“Test”>. Thread count is used in parallel testing, it can be excluded.
  3. @BeforeMethod: It is executed before every @Test annotated method in all the classes that have extended BasePageTest class.

Next, @Test annotated method where the business requirement resides are executed. That is after pre-test annotated methods,

  • @Test: @Test annotated methods are executed as per the classes organized in Testng.xml. In the above case, it will execute first all @Test annotated methods in SearchPageTest.java, then from LoginPageTest.java and finally HomePageTest.java. And within the class, it is executed in alphabetical order.

Then, all post-test conditions are executed

  • @AfterMethod: It is executed after every @Test annotated method. In our example there are four @Test annotated methods so it is executed after each @Test methods.
  • @AfterTest: It is executed after all @Test annotated method from all classes have been executed

 It is not necessary to use all the annotations, So based on testing needs these annotations, classes and tests should be defined.

View the test execution results in the Results of running suite tab

We can create multiple testng.xml files for different test phases and create test suite as per the testing needs. Example: RegressionSuite.xml, SmokeTestSuite.xml etc.

In the next section, we will see how to create Maven project and integrate TestNG with Selenium Webdriver code.

Steps to Configure Maven Profile with Maven Project

Let us see how to configure Maven Profile for a Maven Project.

What is a Maven Profile..??                                                               

It is a feature that can be defined in a pom.xml file which allows developers and testers to configure and customize builds based on requirement. 

What is the advantage of implementing Maven Profile in our Automation Projects..??                                                                 

As shown below, In real time we generally maintain different testng.xml files in frameworks that are designed either for Web Applications, Backend APIs or Mobile Applications like Smoke Suite, Regression Suite, Sanity Suite etc. for executing test cases based on requirement.             

Based on business requirement, we will be required to execute testng.xml files from Eclipse IDE, Command Prompt or from Jenkins etc.

In general, if we do not use Maven Profiling. Each time when we need to execute testng.xml file. We need to go to pom.xml file and change the name of testng.xml inside Maven Surefire Plugin which needs to be executed and that is a very tedious task to do every time.  Now the question is, how can we avoid changing testng.xml file name in pom.xml every time. when we need to execute test suite.

Now let us see configuring Maven Profile with Maven Project.

1. Project should be a Maven Project. 

2. Maven Jar files should be downloaded and path must be set for the same in Environment Variables and ensure that you are able to execute Maven Project from Command Line prompt before implementing Maven Profile. 

Refer below blog with respect to above points to Install Maven Jars and to execute Maven Project from Command Prompt:  http://naveenautomationlabs.com/executing-maven-project-in-windows-from-command-prompt/

Below is Maven Surefire Plugin where we mention which testng.xml file needs to be executed from project.

Code for Maven Surefire Plugin:                                                     

<build>
 <pluginManagement>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>2.18.1</version>
 <configuration>
 <suiteXmlFiles>
 <suiteXmlFile>src/main/resources/testng_smoke.xml</suiteXmlFile>
 </suiteXmlFiles>
 </configuration>
 </plugin>
 </plugins>
 </pluginManagement>
 </build>

Now, let us see how can we build Maven Profile using Maven Surefire Plugin.

We can build Maven Profile for each testng.xml file in pom.xml as shown below, for each Maven Profile we can give Id/Name as highlighted in below screenshot.

All we need to add is followed tags with Maven Surefire Plugin <profiles> </profiles>, <profile> </profile> and <id> </id>.

All we need to do is that providing Id/Name for each Profile. For example, if we have multiple testng.xml files like Smoke, Sanity and Regression then we can build 3 Maven Profiles.       

One-One Profile for each suite, so that we can avoid changing testng.xml file name inside Maven Surefire Plugin whenever we need to execute test suite.

In my case, I have 2 testng.xml files. One is for Smoke and other one is for Regression.

You can refer below screenshots for giving Maven Profile Names for Test Suites.

Note: Profile Name should always be written inside <id> tag.

Refer below pom.xml to build Maven Profile for each testng.xml file.    https://github.com/PavanReddy77/MavenSurefirePlugin/blob/master/pom.xml

Once Maven Profiles are built for all testng.xml files then we are good to execute from Command Prompt or from Jenkins.

Maven Commands to be followed when executing testng.xml files. 

mvn test –P followed by Maven Profile Id like below:

mvn test –PSmoke     

mvn test –PRegression

Well, we are now good to execute our testng.xml file based on our requirement.

Refer below repository for implementing Maven Surefire Plugin and Maven Profile.  

https://github.com/PavanReddy77/MavenSurefirePlugin

Conclusion: In this blog, we have seen implementing Maven Surefire Plugin and Maven Profile in a Maven Project.

Blog Contributors:

Author:  Pavan K

Pavan, having good knowledge in Selenium Web UI and API Automation frameworks. Also, he is helping QA community with his knowledge along with Naveen AutomationLabs!!

LinkedIn

Reviewer: Naveen Khunteta 

https://www.linkedin.com/in/naveenkhunteta

TestNG Interview Questions

TestNG Interview Questions
 

1. What is TestNG?
TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration testing. For more information.
 

2. What are the advantages of TestNG?
·      TestNG provides parallel execution of test methods
·      It allows to define dependency of one test method over other method
·      It allows to assign priority to test methods @Test(priority=1, groups = “Login”)
·      It allows grouping of test methods into test groups
·      It has support for parameterizing test cases using @Parameters annotation
·      It allows data driven testing using @DataProvider annotation
·      It has different assertions that helps in checking the expected and actual results
·      Detailed (HTML) reports
·      Testng Listeners
 

 
3. What are the annotations available in TestNG?
@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test
@DataProvider
@Parameters
 

 
4. Can you arrange the below testng.xml tags from parent to child? 

 
5. How to create and run testng.xml ? 
In TestNG framework, we need to create testng.xml file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the xml file.
View Complete Post
 

 
 
 
6. What is the importance of testng.xml file?
In a Selenium TestNG project, we use testng.xml file to configure the complete test suite in a single file. Some of the features are as follows.
   testng.xml file allows to include or exclude the execution of test methods and test groups
   It allows to pass parameters to the test cases
   Allows to add group dependencies
   Allows to add priorities to the test cases
   Allows to configure parallel execution of test cases
   Allows to parameterize the test cases
 

 
 
7. How to pass parameter through testng.xml file to a test case?
We could define the parameters in the testng.xml file and then reference those parameters in the source files.
x

Create a java test class, say, ParameterizedTest.java and add a test method say parameterizedTest() to the test class. This method takes a string as input parameter. Add the annotation @Parameters(“browser”) to this method.
// TestNG Interview Questions

public class ParameterizedTest {
            @Test
            @Parameters(“browser”)
            public void parameterizedTest(String browser){
                        if(browser.equals(“firefox”)){
                                    System.out.println(“Open Firefox Driver”);
                        }else if(browser.equals(“chrome”)){
                                    System.out.println(“Open Chrome Driver”);
                        }
            }          
}
The parameter would be passed a value from testng.xml, which we will see in the next step.
We could set the parameter using the below syntax in the testng.xml file. 

Here, name attribute represents the parameter name and value represents the value of that parameter.
Practical Example
 

 
8. What is TestNG Assert and list out common TestNG Assertions?
TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any exception.
Some of the common assertions supported by TestNG are
 

   assertEqual(String actual,String expected)
   assertEqual(String actual,String expected, String message)
   assertEquals(boolean actual,boolean expected)
   assertTrue(condition)
   assertTrue(condition, message)
   assertFalse(condition)
   assertFalse(condition, message)
For Complete Post
 

 
9. What is Soft Assert in TestNG?
Soft Assert collects errors during @Test. Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.
If there is any exception and you want to throw it then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.
Practical Example
 

 
T1(){
1 sendkeys()
2 HA –passed à 3 else à terminate test case / failed
3 SA — passed
4 SA  — failed à 5
5 SA – passed à 6
6 SA – Failed
 

softAssert.assertAll();
 

 
 
}
 

 
 
 
10. What is Hard Assert in TestNG?
Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test
 

 
11. What is exception test in TestNG?
TestNG gives an option for tracing the Exception handling of code. You can verify whether a code throws the expected exception or not. The expected exception to validate while running the test case is mentioned using the expectedExceptions attribute value along with @Test annotation.
 

@Test
t1(expectedExceptions = ElementNotFoundException){
 

}
 

 
 
 
12. How to set test case priority in TestNG?
We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical order.
// TestNG Interview Questions

package TestNG;
import org.testng.annotations.*;
public class PriorityTestCase{
           
@Test(priority=0)
            public void testCase1() { 
                        system.out.println(“Test Case 1”);
            }
           
@Test(priority=1)
            public void testCase2() {          
                        system.out.println(“Test Case 2”);
            }
}
Output:
Test Case 1

Test Case 2
 
 
13. What is Parameterized testing in TestNG?
Parameterized tests allow developers to run the same test over and over again using different values.
There are two ways to set these parameters:
   using testng.xml – 
   using Data Providers – 
 

 
14. How can we create data driven framework using TestNG?
By using @DataProvider annotation,  we can create a Data Driven Framework.
 

 
// TestNG Interview Questions
@DataProvider(name=”getData”)
            public Object[][] getData(){
                        //Object [][] data = new Object [rowCount][colCount];
                        Object [][] data = new Object [2][2];
                       
                        data [0][0] = “FirstUid”;
                        data [0][1] = “FirstPWD”;
                       
                        data[1][0] = “SecondUid”;
                        data[1][1] = “SecondPWD”;
                       
                        return data;
                       
            }
Practical Example
 

 
 
 
 
15. How to run a group of test cases using TestNG?
TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set.  This gives you maximum flexibility in how you partition your tests and doesn’t require you to recompile anything if you want to run two different sets of tests back to back.
Groups are specified in your testng.xml file and can be found either under the or tag. Groups specified in the tag apply to all the tags underneath.
 

@Test (groups = { “smokeTest”, “functionalTest” })
public void loginTest(){
System.out.println(“Logged in successfully”);
}
 
 
 
16. How to create Group of Groups in TestNG?
Groups can also include other groups. These groups are called MetaGroups. For example, you might want to define a group all that includes smokeTest and functionalTest. Let’s modify our testng.xml file as follows:
 

  
             
             
  
  
        
          

 
 
17. How to run test cases in parallel using TestNG?
we can use “parallel” attribute in testng.xml to accomplish parallel test execution in TestNG
The parallel attribute of suite tag can accept four values:
 

tests – All the test cases inside tag of testng.xml file will run parallel
classes – All the test cases inside a java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in same instance will execute parallel but two methods of two different instances will run in different thread.

 
 
 
18. How to exclude a particular test method from a test case execution? 
By adding the exclude tag in the testng.xml

 
    
      
    
       

 
19. How to exclude a particular test group from a test case execution? 
By adding the exclude tag in the testng.xml

   
             
         

 
 
20. How to disable a test case in TestNG ?
To disable the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)

 
 
21. How to skip a @Test method from execution in TestNG?
By using throw new SkipException()

 
Once SkipException() thrown, remaining part of that test method will not be executed and control will goes directly to next test method execution.
throw new SkipException(“Skipping – This is not ready for testing “);

 
 
22. How to Ignore a test case in TestNG?
To ignore the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)

 
 
 
 
23. How TestNG allows to state dependencies?
TestNG allows two ways to declare the dependencies.
Using attributes dependsOnMethods in @Test annotations –Using attributes dependsOnGroups in @Test annotations –
 

 
 
 
24. What are the different ways to produce reports for TestNG results?
TestNG offers two ways to produce a report.
Listeners implement the interface org.testng.ITestListener and are notified in real time of when a test starts, passes, fails, etc…
Reporters implement the interface org.testng.IReporter and are notified when all the suites have been run by TestNG. The IReporter instance receives a list of objects that describe the entire test run.
 

 
 
25. What is the use of @Listener annotation in TestNG?
TestNG listeners are used to configure reports and logging. One of the most widely used listeners in testNG is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We should implement this interface creating a listener class of our own. Next we should add the listeners annotation (@Listeners) in the Class which was created.
 

 
 
26. How to write regular expression In testng.xml file to search @Test methods containing “smoke” keyword.
 

Regular expression to find @Test methods containing keyword “smoke” is as mentioned below.
 
27. What is the time unit we specify in test suites and test cases? 
 

We specify the time unit in test suites and test cases is in milliseconds.
 

 
 
28. List out various ways in which TestNG can be invoked?
TestNG can be invoked in the following ways
   Using Eclipse IDE
   Using maven/ant build tool
   From the command line
   Using IntelliJ’s IDEA
 

 
29. How To Run TestNG Using Command Prompt?
 

C: test
Java c://testing.jar test.java
 

 
30. What is the use of @Test(invocationCount=x)?
The invocationcount attribute tells how many times TestNG should run a test method
@Test(invocationCount = 10)

public void testCase1(){
In this example, the method testCase1 will be invoked ten times
 

 
 
31. What is the use of @Test(threadPoolSize=x)?
The threadPoolSize attribute tells to form a thread pool to run the test method through multiple threads.
Note: This attribute is ignored if invocationCount is not specified
@Test(threadPoolSize = 3, invocationCount = 10) public void testCase1(){

In this example, the method testCase1 will be invoked from three different threads
 

 
32. What does the test timeout mean in TestNG?
The maximum number of milliseconds a test case should take.
@Test(threadPoolSize = 3, invocationCount = 10,  timeOut = 10000)

public void testCase1(){
In this example, the function testCase1 will be invoked ten times from three different threads. Additionally, a time-out of ten seconds guarantees that none of the threads will block on this thread forever.
 

 
 
33. What are @Factory and @DataProvider annotation?
@Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective class with different set of data.
@DataProvider: A test method that uses DataProvider will be executed the specific methods multiple number of times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.

For any feedback, feel free to reach me. You can write to me at naveenanimation20@gmail.com