Selenium WebDriver Test with Java and TestNG | Code Example

What is Selenium?

Selenium automates browsers. That’s it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) be automated as well.

Selenium has the support of some of the largest browser vendors who have taken (or are taking) steps to make Selenium a native part of their browser. It is also the core technology in countless other browser automation tools, APIs and frameworks.

Code Example | Java

Here is a sample code example of Selenium test with Java and TestNG.

package com.softwaretestingblog.selenium;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

public class Problem1 {
	WebDriver driver= new FirefoxDriver();
	  
	  @BeforeTest
	  public void beforeTest() {
		driver.get("https://www.ups.com/one-to-one/login");
		driver.manage().timeouts().implicitlyWait(20,  TimeUnit.SECONDS);
	  }

	  @AfterTest
	  public void afterTest() {
		driver.close();
		driver.quit();
	  }
	  
	  @Test
	  public void SampleTest() {
		  
		  WebElement pgLogin = driver.findElement(By.xpath("//*[@id='main']/form/div[1]/div[1]/div[1]"));
		  String msgAct1 = pgLogin.getText();
		  String msgExp1 = "Log In";
		  Assert.assertEquals(msgAct1, msgExp1);
		  
		  WebElement editId = driver.findElement(By.xpath("//*[@id='repl_id1']"));
		  editId.clear();
		  editId.sendKeys("InvalidID");
		  
		  WebElement btnLogin = driver.findElement(By.xpath("//*[@id='submitBtn']"));
		  btnLogin.click();
		  
		  Actions hoverAction = new Actions (driver);
		  WebElement movetoMyups = driver.findElement(By.xpath("//*[@id='navImg0']"));
		  hoverAction.moveToElement(movetoMyups);
		  hoverAction.perform();
		  
		  Actions buttonclick = new Actions (driver);
		  WebElement buttonhere = driver.findElement(By.xpath(".//*[@id='ui-id-4']/form/div/fieldset/div[3]/div/input"));
		  buttonclick.moveToElement(buttonhere).click().perform();
	  }
}
Advertisements

Leave a Reply