Selenium 2 example not working - selenium-webdriver

I havefollowed the example at
http://www.qaautomation.net/?p=263
package net.qaautomation.examples;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
/**
* Search Google example.
*
* #author Rahul
*/
public class GoogleSearch {
static WebDriver driver;
static Wait<WebDriver> wait;
public static void main(String[] args) {
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 30);
driver.get("http://www.google.com/");
boolean result;
try {
result = firstPageContainsQAANet();
} catch(Exception e) {
e.printStackTrace();
result = false;
} finally {
driver.close();
}
System.out.println("Test " + (result? "passed." : "failed."));
if (!result) {
System.exit(1);
}
}
private static boolean firstPageContainsQAANet() {
//type search query
driver.findElement(By.name("q")).sendKeys("qa automation\n");
// click search
driver.findElement(By.name("btnG")).click();
// Wait for search to complete
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver webDriver) {
System.out.println("Searching ...");
return webDriver.findElement(By.id("resultStats")) != null;
}
});
// Look for QAAutomation.net in the results
return driver.findElement(By.tagName("body")).getText().contains("qaautomation.net");
}
}
to the letter but when I run it I get the error
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.http.conn.scheme.Scheme.<init>(Ljava/lang/String;ILorg/apache/http/conn/scheme/SchemeSocketFactory;)V
at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:59)
at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:48)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:120)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:81)
at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:244)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:110)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:190)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:183)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:179)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:92)
at com.google.gwt.sample.contacts.test.GoogleSearch.main(GoogleSearch.java:20)
any ideas on what might be wrong? In fact several other examples I tried all give me a similar NoSuchMethod Error. EG http://thomassundberg.wordpress.com/2011/10/18/testing-a-web-application-with-selenium-2/
If you have any simple working Selenium2 example I would be grateful for a link. Thnx

If you're looking to get started with Selenium webdriver I'd suggest reading through the documentation on seleniumhq.org and perhaps try the example on the following page it's a little bit more simplified.
http://seleniumhq.org/docs/03_webdriver.jsp
I would also suggest using eclipse and staying away from maven and ant until you get a good grasp on webdriver, that's assuming you're new to these applications.

Related

Unable to locate element: {"method":"xpath","selector":"//*[#id='identify_email']"}

I am getting the following error:
Unable to locate element:
{"method":"xpath","selector":"//*[#id='identify_email']"}
Even-though the selector that i have written is correct. I have checked it using console. Any idea how to resolve this?
package lbw;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Locators {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\vicky\\Documents\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.facebook.com");
driver.findElement(By.id("email")).sendKeys("xxxxxxx#gmail.com");
driver.findElement(By.name("pass")).sendKeys("xxxxxxxxxxx");
driver.findElement(By.linkText("Forgotten account?")).click();
driver.findElement(By.xpath("//*[#id=\'identify_email\']")).sendKeys("xxxxxxx#gmail.com");
driver.findElement(By.xpath("//*[#value='Search']")).click();
driver.findElement(By.cssSelector("input[id='send_email']")).click(); /*im getting error in this line. Im try to select a radio. */
System.out.println("Completed");
}
}
You can try with adding implicity wait or WebDriver wait. Here is example of second:
public static void waitForElementPresent(this IWebElement element)
{
try
{
wait.Until(driver => element.Displayed);
}
catch (Exception e)
{
Assert.Fail("The element not found. The exception: \n" + e.GetType());
}
}

Login page in selenium not firing

Team,
I am stuck in one issue.
I have two classes One where i have created a plain login functionality using constructor and in second one i am instantiating the login.
The issue is the test case is terminating immediately.
Please help me out
I am giving the below code.
Is there any problem with initialisation.
public Userlogin(String username, String brand, WebDriver driver) {
WebElement user=driver.findElement(By.id("UserNameInputText"));
user.sendKeys(username);
Select select=new Select(driver.findElement(By.id("Brand")));
select.selectByValue(brand);
WebElement login_button=driver.findElement(By.id("CmdLogin"));
login_button.submit();
String actual_title=driver.getTitle();
String expected_title="VSS 4";
if(!(actual_title.matches(expected_title)))
{
Assert.assertFalse(false);
driver.quit();
}
WebElement cancel=driver.findElement(By.id("Cancel"));
if(!driver.findElements(By.id("Cancel")).isEmpty())
{
cancel.click();
}
}
}
I am calling login in below code
package testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import vsslogin.Userlogin;
public class messageboard extends Userlogin {
public messageboard(String username, String brand, WebDriver driver) {
super(username, brand, driver);
// TODO Auto-generated constructor stub
}
WebDriver driver;
#Test
void messageboard()
{
System.setProperty("webdriver.chrome.driver", "C:/Eclipse/chromedriver.exe");
driver=new ChromeDriver();
driver.get("http://153.112.61.197/vss_connect_testr1/Login/Login.aspx?nextview=Welcome");
driver.manage().window().maximize();
Userlogin login=new Userlogin("TYP40US","Mack",driver);
}
}
Try to add System.out.println() statement in your code mentioned below and RUN.
If you have seen the "Close Browser" Message in Console. Tile of the Page is Not Matched with your expected_title.
Line : driver.quit(); is terminates your browser.
if(!(actual_title.matches(expected_title)))
{
System.out.println("Close Browser");
Assert.assertFalse(false);
driver.quit();
}

how to call function/method form one class to another class in selenium webdriver using java

I want to call login and search method from two different class into the main class. I have written the two diff classes for login and search but when I am calling both method in class containg main method .it gives me an error as below>>
Exception in thread "main" java.lang.NullPointerException
at Test_package_Ted_baker.search.search_1(search.java:14)
at Test_package_Ted_baker.SHopping.main(SHopping.java:16)
Can someone please help me to find out solution about how to call methods from one class to another class. My code is as below>>
Main class
package Test_package_Ted_baker;
import org.openqa.selenium.WebDriver;
public class SHopping {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
login_Ted_Baker obj=new login_Ted_Baker();
obj.login_to_Ted_Baker("ss3777010#gmail.com", "google#123");
System.out.println("Login sucessfully");
search obj1=new search();
obj1.search_1();
obj.user_logout();
System.out.println("User log out sucessfully");
}
}
Login class
package Test_package_Ted_baker;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class login_Ted_Baker {
WebDriver driver;
public static void main (String [] args) throws InterruptedException
{
login_Ted_Baker obj=new login_Ted_Baker();
obj.login_to_Ted_Baker("ss3777010#gmail.com", "google#123");
System.out.println("Login Sucessfully");
obj.user_logout();
}
public void usename( String Username)
{
WebElement Username_TB=driver.findElement(By.name("j_username"));
Username_TB.sendKeys(Username);
}
public void password(String Password)
{
WebElement Password_TB=driver.findElement(By.name("j_password"));
Password_TB.sendKeys(Password);
}
public void submit()
{
driver.findElement(By.xpath(".//*[#id='command']/div/input ")).click();
}
public void login_Ted_Baker(WebDriver driver){
this.driver = driver;
}
public void user_logout() throws InterruptedException
{
Thread.sleep(1000);
WebElement Sign_in_link=driver.findElement(By.xpath(".//*[#id='page']/header/div/nav[1]/ul/li[3]/div/a"));
WebElement Sign_out_button=driver.findElement(By.xpath(".//*[#id='account']/ul/li[2]/a"));
Thread.sleep(1000);
Actions Act1=new Actions(driver);
Act1.moveToElement(Sign_in_link).click();
Act1.moveToElement(Sign_out_button).click().build().perform();
System.out.println("Logout sucessfully");
}
public void login_to_Ted_Baker(String Username,String Password) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver_win32\\chromedriver.exe");
//System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
Thread.sleep(2000);
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
try{
driver.get("http://www.tedbaker.com/");
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")));
if(driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).isDisplayed())
{
driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).click();
}
driver.findElement(By.xpath(".//*[#id='page']/header/div/nav[1]/ul/li[3]/div/a")).click();
Thread.sleep(2000);
this.usename(Username);
this.password(Password);
this.submit();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
searching class
package Test_package_Ted_baker;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class search {
WebDriver driver;
public void search_1() throws InterruptedException
{
WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
Search_Item.click();
WebElement Seacrh_item_message=driver.findElement(By.id("search"));
WebElement Search_textbox=driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[1]/input"));
Search_textbox.sendKeys("Watches");
driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[2]/input")).click();
WebElement SearchResult_pagemessage=driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/h1"));
driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/div/div/span[1]")).click();
WebElement Item_Tobuy = driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[2]/div[1]/article/div[2]/header/div/h4/a"));
JavascriptExecutor jse1= (JavascriptExecutor)driver;
jse1.executeScript("window.scrollBy(0,400)", "");
Item_Tobuy.click();
driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/ol/li[2]/span/span/select")).click();
Select dropdown1=new Select(driver.findElement(By.id("qty")));
dropdown1.selectByVisibleText("1");
driver.findElement(By.id("qty")).click();
// driver.findElement(By.xpath("*[#classname='button add_to_cart major full_mobile colour_dark']/div[2]/div[1]/div/input[1]")).click();
// driver.findElement(By.xpath("//*[#id='add_to_cart_form']/div[2]/div[2]/a/span[1]/span[1]")).click();
driver.findElement(By.xpath("//input[contains(#class,'add_to_cart')]")).click();
Thread.sleep(1000);
Actions act=new Actions(driver);
WebElement My_cart_button=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[3]/a/span[2]"));
//WebElement My_cart_button=driver.findElement(By.xpath("//input[contains(#class,'My bag')]"));
WebElement View_bag_checkout_button=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[3]/div/ul/li/a"));
act.moveToElement(My_cart_button).moveToElement(View_bag_checkout_button).click().build().perform();
driver.findElement(By.xpath("html/body/div[2]/div/div/div/section/table/tbody/tr/td[2]/form/ul/li[2]/a")).click();
String Cart_empty_mesg=driver.findElement(By.xpath("html/body/div[1]/div/div/div/header/h1")).getText();
System.out.println(Cart_empty_mesg);
String Actual_cart_empty_msg="Your shopping bag is empty";
if(Cart_empty_mesg==Actual_cart_empty_msg)
{
System.out.println("Cart is empty, you can add product cart");
}
}
}
This might sound harsh, but first of all you should read about
Null Pointer Exception from this link.
How to debug from a StackTrace from this link.
Why using absolute xpath, or xpaths locators in general is a bad strategy from here.
From your stack trace,
Exception in thread "main" java.lang.NullPointerException at
Test_package_Ted_baker.search.search_1(search.java:14) at
Test_package_Ted_baker.SHopping.main(SHopping.java:16)
I see that your code in Search class
WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
is not correct. I suspect your locator is not correct for this one. The element can easily be identified using an id attribute, as
driver.findElement(By.id("search"));
or , if you're using xpaths, then
driver.findElement(By.xpath("//*[#id="search"]"));
should do away the NPE - but not sure since you've used a lot of absolute xpaths - which is a horrible practise.

FAILED CONFIGURATION: #BeforeClass beforeClass

I am a beginner to Selenium and I am now using #DataProvider in TestNG framework to pass some values in a webpage (learning purpose). Below is my code:
package Framework;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
public class DataProv {
WebDriver d;
#Test(dataProvider = "dp", priority=0)
public void signin(String uname, String pwd) throws InterruptedException {
d.findElement(By.linkText("SIGN-ON")).click();
d.findElement(By.name("userName")).sendKeys(uname);
d.findElement(By.name("password")).sendKeys(pwd);
Thread.sleep(3000);
}
#Test(dataProvider = "dp1", priority=1)
public void reg(String fname) throws InterruptedException {
d.findElement(By.linkText("REGISTER")).click();
d.findElement(By.name("firstName")).sendKeys("fname");
d.findElement(By.name("register")).click();
Thread.sleep(3000);
}
#DataProvider
public Object[][] dp() {
return new Object[][] {
new Object[] { "Rachel", "India123" },
new Object[] { "Rita", "pass123" },
};
}
#DataProvider
public Object[][] dp1() {
return new Object[][] {
new Object[] { "Rachel"},
new Object[] { "Rita"},
};
}
#BeforeClass
public void beforeClass() {
d.manage().window().maximize();
d = new FirefoxDriver();
d.get("http://newtours.demoaut.com/");
}
#AfterClass
public void afterClass() {
d.close();
}
}
No, I am getting the following error
FAILED CONFIGURATION: #BeforeClass beforeClass
java.lang.NullPointerException
Can somebody help me in resolving this issue.
Thanks in advance
What is Null Pointer Exception?
This issue is coming because you are trying to maximise the browser without it being initialized.
You just have to reverse the order of launching the browser and then maximising it in your #BeforeClass method.
So when you say WebDriver d, reference d is NULL, so when you are trying to call the method manage() on d you basically are trying to call this method using null object i.e. null.manage() thats why Null Pointer Exception so you first have to intantiate it using d = new FirefoxDriver();
d = new FirefoxDriver();
d.manage().window().maximize();
Check your browser invoking method. I think your driver (d) is not able to find the driver under test . you need to point the driver path before invoking driver == new driver. below is the chrome driver code for your reference.
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+ "\\src\\test\\resources\\executables\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources