I am learning TestNG for selenium. I want to pass three different usernames and passwords to the #Test, which is the login scenario. The scenario is:
go to the login page
click on the username input field and enter the username
click on the password input field and enter the password
click on the login button
click on the logout button
click on "ok" on the alert.
The first test is getting passed. The other two are getting failed with UnhandledAlertException.
package testNG;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class testData {
WebDriver driver;
#Test(dataProvider="data")
public void login(String userName, String password) {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/V1/index.php");
WebElement userID = driver.findElement(By.xpath("//input[#name='uid']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(userID));
userID.sendKeys(userName);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password);
driver.findElement(By.xpath("//input[#name='btnLogin']")).click();
driver.findElement(By.xpath("//a[#href='Logout.php']")).click();
driver.switchTo().alert().accept();
driver.quit();
}
#DataProvider(name="data")
public Object[][] getUserData(){
return new Object[][] {
{"mngr137366", "jUgyjAn"},
{"mngr137370", "uvetahA"},
{"mngr137371", "utYmEqY"},
};
}
}
Update:
With the handling of the alert and the removing of the hardcoded username, the code is working fine now.
But the browser is being opened for three times for three logins.
I want it to open one time and perform three logins.
For that I have added the below code:
#BeforeClass
public void setUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/V1/index.php");
}
and the same is removed from the login() function. Now the first login is only successful. The other two logins are left.
The total code:
public class testData {
//public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver;
#BeforeClass
public void setUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/V1/index.php");
}
#Test(dataProvider="data")
public void login(String userName, String password) {
WebElement userID = driver.findElement(By.xpath("//input[#name='uid']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(userID));
userID.sendKeys(userName);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password);
driver.findElement(By.xpath("//input[#name='btnLogin']")).click();
driver.findElement(By.xpath("//a[#href='Logout.php']")).click();
WebDriverWait waitAlert = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
WebDriverWait wait1 = new WebDriverWait(driver, 20);
wait1.until(ExpectedConditions.elementToBeClickable(userID));
}
#DataProvider(name="data")
public Object[][] getUserData(){
return new Object[][] {
{"mngr137366", "jUgyjAn"},
{"mngr137370", "uvetahA"},
{"mngr137371", "utYmEqY"},
};
}
}
Try this,
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
It will wait until it will not find alert.
It looks, you have hard coded the username in your login test method.hence test is getting failed for rest of the two input (Valid Login Authentication error is throwing for the invalid user id to password mapping)
All the test is getting passed after assigning the username to the Userid element field.
Modified Login Code:
#Test(dataProvider="data")
public void login(String userName, String password) {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/V1/index.php");
WebElement userID = driver.findElement(By.xpath("//input[#name='uid']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(userID));
userID.sendKeys(userName);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password);
driver.findElement(By.xpath("//input[#name='btnLogin']")).click();
driver.findElement(By.xpath("//a[#href='Logout.php']")).click();
driver.switchTo().alert().accept();
driver.quit();
}
Related
enter image description here
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\Desktop\\Selenium\\chromedriver.exe" );
WebDriver driver=new ChromeDriver();
driver.get("https://www.amazon.in"); //url in the browser
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//div[#id='nav-xshop']/a[1]/following-sibling::a[2]")).click();
}
}
Need to hit mobiles but it is hitting fashion , Please help in correcting
Instead of
driver.findElement(By.xpath("//div[#id='nav-xshop']/a[1]/following-sibling::a[2]")).click();
Use this locator:
driver.findElement(By.xpath("//a[contains(#href,'mobile-phones')]")).click();
You should also add an explicit wait there so your code should be something like this:
public class Demo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\5558\\Desktop\\Selenium\\chromedriver.exe" );
WebDriver driver=new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://www.amazon.in"); //url in the browser
System.out.println(driver.getTitle());
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(#href,'mobile-phones')]")));
driver.findElement(By.xpath("//a[contains(#href,'mobile-phones')]")).click();
}
}
use this css_selector :
a[href^='/mobile-phones/b/']
use it like below :
driver.findElement(By.cssSelector("a[href^='/mobile-phones/b/']")).click();
xpath would be :
//a[contains(#href, '/mobile-phones/b/')]
use it like this :
driver.findElement(By.xpath("//a[contains(#href, '/mobile-phones/b/')]")).click();
My webdriver is the last version, my code have Thread.sleep also, but I can't login to the page.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
WebDriver driver;
#BeforeTest
public void navegador() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\chromedriver.exe");
Thread.sleep(1000);
driver = new ChromeDriver();
Thread.sleep(2000);
driver.manage().window().maximize();
Thread.sleep(3000);
}
#Test
public void f() throws InterruptedException {
driver.get("somewebpage");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Thread.sleep(3000);
driver.findElement(By.partialLinkText("LOGIN")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/div[1]/div[2]/form/div[1]/input")).sendKeys("myemail");
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/div[1]/div[2]/form/div[2]/input")).sendKeys("mypassword");
Thread.sleep(2000);
driver.findElement(By.xpath("/html/body/div[1]/div[2]/form/div[3]/div[2]/button")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
}
#AfterTest
public void cierre() {
driver.quit();
}
}
The webpage send me this message "These credentials do not match our records."
But when I do it manually, the page give me access to home.
I can't pass from the login page, Suggestions?
may be you can give try this check whether test works in debug mode.
If test is still not working in debug mode. then try to fetch values of both username and password field after sent by script and check whether its going correctly as manually.
Still its failing please share html code.
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.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class NewGmail {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
String url = "https://accounts.google.com/signin";
driver.get(url);
driver.findElement(By.id("identifierId")).sendKeys("cp8805");
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver, 20);
driver.findElement(By.xpath("//span[#class='RveJvd snByac']")).click();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#class='whsOnd zHQkBf']")).sendKeys("xxxxxx");
driver.findElement(By.xpath("//span[#class='RveJvd snByac']")).click();
}
}
after mail id my password also get written in the id box option & the server redirect to to next password page. i want to ask what i will do so that my password would be entered only in password page.
Here is the working code block to login into your Gmail account through a valid set of credentials-
System.setProperty("webdriver.gecko.driver","C:\\your_directory\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
String url = "https://accounts.google.com/signin";
driver.get(url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement email_phone = driver.findElement(By.xpath("//input[#id='identifierId']"));
email_phone.sendKeys("your_email_phone");
driver.findElement(By.id("identifierNext")).click();
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(password));
password.sendKeys("your_password");
driver.findElement(By.id("passwordNext")).click();
Update(5-Jan-2020)
Optimizing the above code block and adding a couple of arguments you can use:
public class browserAppDemo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setExperimentalOption("useAutomationExtension", false);
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
WebDriver driver = new ChromeDriver(options);
driver.get("https://accounts.google.com/signin")
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='identifierId']"))).sendKeys("emailID");
driver.findElement(By.id("identifierNext")).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#name='password']"))).sendKeys("password");
driver.findElement(By.id("passwordNext")).click();
}
}
I'm getting a NullPointerException as follows:
Feature: Login action
Scenario:
Successful Login with Valid Credentials # C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:3
Given User is on Home Page # StepDefinitions.User_is_on_Home_Page()
When User enters UserName and Password # StepDefinitions.User_enters_UserName_and_Password()
java.lang.NullPointerException
at feature.StepDefinitions.User_enters_UserName_and_Password(StepDefinitions.java:25)
at ?.When User enters UserName and Password(C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:5)
Then Message displayed Login Successfully # StepDefinitions.Message_displayed_Login_Successfully()
Code:
package feature;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinitions {
public static WebDriver driver;
#Given("^User is on Home Page$")
public void User_is_on_Home_Page() throws Throwable {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://opensource.demo.orangehrmlive.com/");
}
#When("^User enters UserName and Password$")
public void User_enters_UserName_and_Password() throws Throwable {
driver.findElement(By.name("txtUsername")).sendKeys("admin");
driver.findElement(By.xpath("//input[#id='txtPassword']")).sendKeys("admin");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
}
#Then("^Message displayed Login Successfully$")
public void Message_displayed_Login_Successfully() throws Throwable {
System.out.println("login completed");
}
}
In User_is_on_Home_Page() you're using a local variable named driver within that method. You're not setting the static driver that your other methods are using. As a result, when they reference driver it is still null.
The solution is to change:
public static WebDriver driver;
to:
public static final WebDriver driver = new FirefoxDriver();
and remove the WebDriver driver = new FirefoxDriver(); line from User_is_on_Home_Page() so that it likewise refers to the static instance.
Alternatively, instantiate the static driver instance lazily. Replace:
WebDriver driver = new FirefoxDriver();
in User_is_on_Home_Page() with:
if (driver == null) {
driver = new FirefoxDriver();
}
This is what i am trying do on Gmail.
www.gmail.com
Login using a valid user (if does not exist create a dummy user)
Click on Inbox
Click on first email
Click on Compose Email.
Send the mail to the same email account.
Click on options icon on the top right corner
Got to vacation responder on the General settings tab
Select vacation responder to on.
I am able to click on 1st email and pick the email Address and then click on compose email button, also able to send the email.
The problem i am facing is unable to click on settings icon. The element is hidden, i am not able to click it. I tried it with customized-Xpath and also tried to click it with coordinates.
But it not working for me. Please can anyone help me on this.
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Gmail1 {
public static void main(String[] args) throws InterruptedException {
// Login to browser
WebDriver driver= new FirefoxDriver();
driver.get("https://www.gmail.com");
driver.manage().window().maximize();
System.out.println("Browser opned");
driver.findElement(By.xpath("//*[#id='Email']")).sendKeys("Use your UserId");
System.out.println("Entered Email id");
driver.findElement(By.xpath("//*[#id='next']")).click();
System.out.println("Clicked on Next");
Thread.sleep(3000);
driver.findElement(By.xpath("//*[#id='Passwd']")).sendKeys("Use your password");
System.out.println("Entered the Password");
driver.findElement(By.xpath("//*[#id='signIn']")).click();
System.out.println("Welcome to gmail");
Thread.sleep(5000);
driver.findElement(By.xpath("//*[#id=':3d']")).click();
System.out.println("Clicked on email");
Thread.sleep(3000);
String emailid = driver.findElement(By.xpath("//span[#class='go']")).getText();
emailid=emailid.substring(emailid.indexOf("<")+1, emailid.indexOf(">"));
System.out.println(emailid);
driver.findElement(By.xpath("//*[#id=':it']/div/div")).click();
System.out.println("Clicked on Compose mail");
driver.findElement(By.xpath("//*[#name='to']")).sendKeys(emailid);
System.out.println("Entered the TO Email Address");
driver.findElement(By.xpath("//*[#name='subjectbox']")).sendKeys("My Mail");
System.out.println("Entered Subject of the email");
driver.findElement(By.xpath("//*[#role='button' and .='Send']")).click();
System.out.println("Clicked on send button");
clickSetting(driver);
}
public static void clickSetting(WebDriver driver){
//Tried with Coordinates (doesn't work)
Point point = driver.findElement(By.xpath("//div[#class='G-Ni J-J5-Ji'] [#gh ='s']/*[1]")).getLocation();
System.out.println(point.x + "-" + point.y);
Actions builder = new Actions(driver);
builder.moveByOffset(point.x, point.y).click().build().perform(); //Getting Error.
//Tried with Action Class (doesn't work)
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement SettingWheel=driver.findElement(By.xpath("//*[#data-tooltip='Settings' and #role='button']"));
WebElement SettingsLink=driver.findElement(By.xpath("//*[#role='menuitem']/div[.='Settings']"));
wait.until(ExpectedConditions.elementToBeClickable(SettingWheel));
Actions actions = new Actions(driver);
actions.moveToElement(SettingWheel).moveToElement(SettingsLink).click().build().perform();//Getting Error.
Thread.sleep(2000);
System.out.println("Clicked On Setting");
}
Error message:- "Element is not currently visible and so may not be interacted with (WARNING: The server did not provide any stacktrace information)"
Thanks in Advance.
Try this:-
public static void clickSetting(WebDriver driver){
List<WebElement> elements=driver.findElements(By.xpath("//div[#gh='s']/*[#role='button']"));
for(WebElement element:elements){
if(element.isDisplayed()){
element.click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[#id='ms']")).click();
Thread.sleep(5000);
}
}
The problem is with your xpath. I tried with id ad it worked. Thread.sleep is bad idea. Don't go with that and instead use WebDriverWait
Anyhow the following snippet will click on settings gear then settings and wait till the Settings panel is loaded completely
Also go through this Gmail Selenium and see how I've handled Gmail login without Thread.sleep
public static void clickSetting(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id=':3d']"))).click();
System.out.println("Clicked On Settings Gear");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#role='menuitem']/div[.='Settings']"))).click();
System.out.println("Clicked On Setting");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#class='dt']")));
System.out.println("Settings Visible");
}
Try this:
package yourPackageName;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestClass2 {
static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "c:/chromedriver.exe");
driver = new ChromeDriver();
Step_1_LaunchApp();
Step_2_LoginUsingCredentials();
Step_3_ClickOnInbox();
Step_4_ClickOnFirstEmail();
Step_5_ClickOnComposeEmail();
Step_6_ClickOnSettingsIcon();
}
private static void Step_6_ClickOnSettingsIcon() {
try{
driver.findElement(By.xpath("//*[#class='aos T-I-J3 J-J5-Ji']")).click();
}catch(Exception e){
e.printStackTrace();
}
}
private static void Step_5_ClickOnComposeEmail() {
try{
driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
}catch(Exception e){
e.printStackTrace();
}
}
private static void Step_4_ClickOnFirstEmail() {
try{
driver.findElement(By.xpath("//div[#role='tabpanel'][1]//table//tr[1]")).click();
}catch(Exception e){
e.printStackTrace();
}
waitTimeInSecond(2);
}
private static void Step_3_ClickOnInbox() {
driver.findElement(By.xpath("//span/a[contains(text(),'Inbox')]")).click();
waitTimeInSecond(2);
}
private static void Step_2_LoginUsingCredentials() {
driver.findElement(By.id("Email")).sendKeys("email#gmail.com");
driver.findElement(By.id("next")).click();
waitTimeInSecond(2);
driver.findElement(By.id("Passwd")).sendKeys("Password");
driver.findElement(By.id("signIn")).click();
waitTimeInSecond(5);
}
private static void Step_1_LaunchApp() {
driver.get("http://gmail.com");
}
public static void waitTimeInSecond(int waitTime){
try{Thread.sleep(waitTime*1000);}catch(Exception e){}
}
}
.
Put your credentials first and run the script, it will click on settings gear.