LambdaTest Community

Find answers, support, and inspiration from other users

Questions
LambdaTest Community
Answered

How do I begin with the TestNG by knowing selenium a little?

Can anyone tell me how do I begin with the TestNG by knowing selenium a little?

Up Vote Down Vote 0 Votes
Posted 3 months ago

Answers


This is not going to be a short response.

I won’t bother with theory since you probably are interested in practical stuff.

So here we go.

Be patient as there is a lot coming :)

…………………………………………………………………..

Lets say that we have a long Selenium test that does the following

  • open the site (http://www.vpl.ca)
  • checks that the home page is displayed
  • executes a search
  • checks that the results page is displayed
  • selects the first result
  • checks that the details page is displayed
  • go back to results page
  • check that results page is displayed
  • select page 2
  • check that page 2 is displayed

This is the full code.

Feel free to try it out as it should work.

import http://org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WithoutTestNG {
	public static void main(String[] args) {
		
		By searchTextBoxId     = Domain Premium: By.id("edit-search");	
		By searchButtonLocator = Domain Premium: By.id("edit-submit");
		By resultTitleLocator  = By.xpath(
									"(//a[@testid = 'bib_link'])[1]");
		By page2Locator        = By.xpath("//a[@testid = 'link_page2']");
		
		String url = "Vancouver Public Library |";
		
		String homeTitle    = "Vancouver Public Library |";
		String resultsTitle = 
				"Search | Vancouver Public Library | BiblioCommons";
		String detailsUrl   = 
			"Recent Activity | Vancouver Public Library | BiblioCommons";
		
		System.setProperty("webdriver.chrome.driver", 
						"c:/selenium/browserdrivers/chromedriver.exe");
		WebDriver driver = new ChromeDriver(); 
				
		//open home page
		driver.get(url);						
		
		//verify that home page is displayed
		if (driver.getTitle().equalsIgnoreCase(homeTitle) == false) {
			System.out.println("incorrect home page title! stop ...");
			System.exit(0);
		}		
		
		//search for java
		WebElement searchTextBox = driver.findElement(searchTextBoxId);
		searchTextBox.sendKeys("java");
		
		WebElement searchButton = driver.findElement(searchButtonLocator);
		searchButton.click();
		
		//verify that results page is displayed
		if (driver.getTitle().equalsIgnoreCase(resultsTitle) == false) {
			System.out.println("incorrect results page title! stop ...");
			System.exit(0);
		}
		
		//select the 1st result
		WebElement resultTitle = driver.findElement(resultTitleLocator);
		resultTitle.click();
		
		//verify that details page is displayed
		if (driver.getCurrentUrl().contains(detailsUrl) == false) {
			System.out.println("incorrect details page url! stop ...");
			System.exit(0);
		}
		
		System.out.println("details page is displayed.");
			
		//go back to results page
		driver.navigate().back();
		
		//verify that results page is displayed
		if (driver.getTitle().equalsIgnoreCase(resultsTitle) == false) {
			System.out.println("incorrect results page title! stop ...");
			System.exit(0);
		}
		
		//go to page 2
		WebElement page2 = driver.findElement(page2Locator);
		page2.click();
		
		//verify that page 2 is displayed
		if (driver.getCurrentUrl().contains("page=2") == false) {
			System.out.println("page 2 is not displayed! stop ...");
			System.exit(0);
		}
		
		System.out.println("page 2 is displayed.");
		
		driver.quit();
	}
}

Long piece of code, dont you think?

This code does not use TestNg.

It tries to automate everything in the main() method of the project.

The test is actually automating 2 different test cases:

  • checking that a search works and
  • checking that paging on results page works There are many problems with this type of code:
  1. it automates 2 test cases
  2. it logs information to the console; you have to check the console to see if everything passed or not; this is not a problem for 2 test cases but what if you have 50?
  3. every time a check is needed, the code uses an if statement that verifies if a condition is true, then it logs the error message and stops; this code is repeated over and over
  4. if the code has a problem for the 1st test case, the code for the 2nd test case is not executed

TestNG (and JUNIT) help getting rid of all these issues.

This is how the code looks when using TestNG.

I will explain later the different parts of it:

import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class WithTestNG {
		
	By searchTextBoxId     = Domain Premium: By.id("edit-search");	
	By searchButtonLocator = Domain Premium: By.id("edit-submit");
	By resultTitleLocator  = By.xpath("(//a[@testid = 'bib_link'])[1]");
	By page2Locator        = By.xpath("//a[@testid = 'link_page2']");
		
	String url = "Vancouver Public Library |";
			
	String homeTitle    = "Vancouver Public Library |";
	String resultsTitle = 
			"Search | Vancouver Public Library | BiblioCommons";
	String detailsUrl   = 
			"Recent Activity | Vancouver Public Library | BiblioCommons";
			
	WebDriver driver;
	
	@BeforeMethod
	public void setUp() {
		System.setProperty("webdriver.chrome.driver", 
					"c:/selenium/browserdrivers/chromedriver.exe");
		driver = new ChromeDriver();
	}
	
	@AfterMethod
	public void tearDown() {
		driver.quit();
	}
	
	@Test
	public void searchWorks() {
		
		//open home page
		driver.get(url);						
			
		//verify that home page is displayed
		assertEquals(driver.getTitle(), homeTitle);
			
		//search for java
		WebElement searchTextBox = driver.findElement(searchTextBoxId);
		searchTextBox.sendKeys("java");
			
		WebElement searchButton = driver.findElement(searchButtonLocator);
		searchButton.click();
			
		//verify that results page is displayed
		assertEquals(driver.getTitle(), resultsTitle);
				
		//select the 1st result
		WebElement resultTitle = driver.findElement(resultTitleLocator);
		resultTitle.click();
			
		//verify that details page is displayed
		assertTrue(driver.getCurrentUrl().contains(detailsUrl) == true);
				
	}
	
	@Test
	public void pagingWorks() {
		
		//open home page
		driver.get(url);						
					
		//verify that home page is displayed
		assertEquals(driver.getTitle(), homeTitle);
					
		//search for java
		WebElement searchTextBox = driver.findElement(searchTextBoxId);
		searchTextBox.sendKeys("java");
					
		WebElement searchButton = driver.findElement(searchButtonLocator);
		searchButton.click();
					
		//verify that results page is displayed
		assertEquals(driver.getTitle(), resultsTitle);
						
		//go to page 2
		WebElement page2 = driver.findElement(page2Locator);
		page2.click();
			
		assertTrue(driver.getCurrentUrl().contains("page=2"));
	}
}

There are many changes compared with the initial code:

1.there is no main() method

instead we have 2 methods, one for each test case.

each method uses the @Test annotation which makes the method a unit test:

@Test
public void searchWorks() {
........................
}
@Test
public void pagingWorks() {
.............
}    

you will notice that the unit tests have common code up to getting to results page.

both open the site, do a keyword search, etc.

this is fine because unit tests should be independent.

if the 1st one fails, the second one should not fail as well.

2.there is no code in the methods for starting or stopping the driver

TestNG allows code to be executed before and after each unit test.

The code to be executed before the unit test goes in a method with the @BeforeMethod annotation.

The code to be executed after the unit test is in a method with the @AfterMethod annotation.

So the driver is started in the @BeforeMethod method and closed in the @AfterMethod method:

@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", 
			"c:/selenium/browserdrivers/chromedriver.exe");
driver = new ChromeDriver();
}

@AfterMethod
public void tearDown() {
driver.quit();
}

Notice that the driver is declared in the class but outside of all methods.

This is so that all methods can use it.

3.all checks are done with assertions

each assertion works similar with the IF statements from the initial code.

the new code uses 2 types of assertions:

  • assertEquals() - has 2 parameters; if the parameters have equal values, the assertion passes, otherwise, it fails assertEquals(driver.getTitle(), homeTitle);
  • assertTrue() - has 1 parameter for a condition; if the condition is true, the assertion passes, otherwise, it fails assertTrue(driver.getCurrentUrl().contains("page=2")); If an assertion passes, the code of the method continues.

If the assertion fails, the remaining code of the method does not execute and the method fails.

The other methods are not impacted.

4. all variables used by the methods are declared at the beginning of the class

this is so all methods can use them:

public class WithTestNG {
		
	By searchTextBoxId     = Domain Premium: By.id("edit-search");	
	By searchButtonLocator = Domain Premium: By.id("edit-submit");
	By resultTitleLocator  = By.xpath("(//a[@testid = 'bib_link'])[1]");
	By page2Locator        = By.xpath("//a[@testid = 'link_page2']");
		
	String url = "Vancouver Public Library |";
			
	String homeTitle    = "Vancouver Public Library |";
	String resultsTitle = 
			"Search | Vancouver Public Library | BiblioCommons";
	String detailsUrl   = 
			"Recent Activity | Vancouver Public Library | BiblioCommons";
			
	WebDriver driver;

5. because of the assertions and unit tests, after executing the unit tests, you get a visual report

there is no need to use the console.

This is what you get after running the unit tests:

In summary, this is what TestNG brings you:

  • unit tests (methods with the @Test annotation)
  • setUp() and tearDown() methods (with the @BeforeMethod and @AfterMethod)
  • annotations (@Test, @BeforeMethod, @AfterMethod)
  • assertions

Of course, this is just a beginning and there are many other things to say.

But it should get you started.

Feel free to try the new code as well.

Oh, and you will need to know how to add TestNG to the project.

In Eclipse, you do the following

  • right click on the project name
  • select properties
  • select Java Build Path
  • select Libraries
  • click Add Library
  • select TestNG
  • click Finish
Up Vote Down Vote 0 Votes
Posted 2 months ago
171 Views
1 Answer
3 months ago