I have to files out of which the first file contains login details. First file is loginDetailsClass.java and below is the code in the file.
public class loginDetailsClass {
#SuppressWarnings("deprecation")
public static void browserLaunch() {
WebDriver driver;
String baseurl = "https://www.facebook.com/";
System.setProperty("webdriver.chrome.driver","D:\\eclipse-workspace\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
options.addArguments("--disable-infobars");
capabilities.setCapability("chrome.binary","D:\\eclipse-workspace\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
//Login section
try {
Thread.sleep(7000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement usnfield = driver.findElement(By.id("email"));
usnfield.sendKeys("alex");
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement pwdfield = driver.findElement(By.id("pass"));
pwdfield.sendKeys("alex42");
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement lgn_btn = driver.findElement(By.id("u_0_8"));
lgn_btn.click();
}
}
And the second file is facebookClass.java and below is the code in the file.
public class facebookClass {
static WebDriver driver;
#Test(priority = 0)
public static void main(String[] args) {
loginDetailsClass.browserLaunch(); //function called from loginDetailsClass.java page
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
#Test(priority = 1)
public static void searchfriends() {
//Switching to iFrame for locating elements
driver.switchTo().frame(driver.findElement(By.id("contentFrame")));
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
//Searching a friend using friend name field
WebDriverWait wait = new WebDriverWait (driver, 20);
WebElement friendName = wait.until(ExpectedConditions.elementToBeClickable(By.id("txtFriendName")));
friendName.sendKeys("James");
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement clck_Search = driver.findElement(By.id("btnSearch"));
clck_Search.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement select_friend = driver.findElement(By.xpath("//*[#id=\"trFriend_3\"]"));
select_friend.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
//Switching back to main frame from iFrame
driver.switchTo().defaultContent();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
#Test(priority = 2)
public static void logout() {
//Logout
WebElement logout = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[1]/td/div/div[8]/table/tbody/tr/td[2]"));
logout.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
driver.close();
}
}
While executing facebookClass.java, login method is called properly and login is successful. But from public static void searchfriends() method, execution doesn't works further. At the very first days all methods got executed successfully. But from the next day it now working.
Related
There is an application am working on where the process of logging in takes far too long, am looking for a way of executing all scenarios and multiple features with one chrome driver instance.
Here is my hooks code
#Before(order = 0)
public void launchbrowser() {
reader = new ConfigFileReader();
pro = reader.ConfigFile();
try {
BaseClass.setUp();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#After
public void tearDown(Scenario scenario) {
File destPath;
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy_hh.mm.ss");
Date curDate = new Date(); String strDate = sdf.format(curDate);
File screenshot_with_scenario_name = (((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));
if(scenario.isFailed())
{
destPath=new File("./test-output/Screenshots/Failed/" + scenario.getName()+ strDate + ".png");
}
else{
destPath=new File("./test-output/Screenshots/Passed/" + scenario.getName()+ strDate + ".png");
}
try {
FileUtils.copyFile(screenshot_with_scenario_name,destPath);
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
BaseClass.Closebrowser();
}
And here is Baseclass where driver is setup
public static void setUp() throws Exception {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
jse = (JavascriptExecutor) driver;
}
#Maxwell Maragia you can try using global hooks #BeforeAll and #AfterAll. You can find the details here https://cucumber.io/docs/cucumber/api/?lang=java
I am using this code to capture screenshot in selenium webdriver with JAVA:
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshot, new File("C:\\projectScreenshots\\homePageScreenshot.png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
But when I wrap this code into function like below, then it throws me NullpointerException.
public static void TakesScreenshot()
{
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshot, new File("C:\\projectScreenshots\\homePageScreenshot.png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
I solved NullpointerException by using this below function:
public static void takeScreenshot(String file, WebDriver driver) {
try{
File scrFile=((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\Users\\"+file+".png"));
} catch(IOException ioe) {
ioe.getStackTrace();
}
}
To call the above function, we need to use this line in the script:
takeScreenshot("Screenshot", driver);
There are multiple files which should be uploaded and waiting for output. It opens up an AJAX like window during processing. If processing takes too much time, Close button should be clicked on this window and file should be submitted again.
I try to use code below, but doesn't click Close button in 10 seconds.
public void clickOnSendButton() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement webElement;
try {
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
driver.findElement(sendButton).click();
log.info("Processing in progress!");
webElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("button-download")));
} catch (TimeoutException ex) {
webElement = null;
} finally {
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
if (webElement == null) {
driver.findElement(popUpClose).click();
TimeUnit.SECONDS.sleep(1);
driver.findElement(sendButton).click();
}
}
Try using 'visibilityOfElementLocated' condition instead of 'presenceOfElementLocated' as below:
webElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("button-download")));
Using the loop:
try {
driver.findElement(By.id("button-submit")).click();
Thread.sleep(3000);//3 seconds
log.info("Processing in progress!");
for(int i=0; i<10;i++){
try{
webElement = driver.findElement(By.className("button-download"));
} catch (Exception e){e.printStackTrace();}
if(webElement.isDisplayed())
break;
else
Thread.sleep(1000);
}
} catch (TimeoutException ex) {ex.printStackTrace();} finally {
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
if (!webElement.isDisplayed() ) {
driver.findElement(By.xpath("/html/body/div[4]/div[1]/button/span[1]")).click();
Thread.sleep(2000);
driver.findElement(By.id("button-submit")).click();
}
This is the snapshot of Login popup :
I'm newbie in Selenium webdriver. I wrote this code to figure out navigate commands but once the browser opens, there is a login popup that is displayed. I tried to close it using classname or xpath but timeout exception occurs.
Do I need to use explicit wait in this case? Could you help me to figure out what the problem is?
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser(){
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
ChromeOptions options=new ChromeOptions();
options.addArguments("start-fullscreen");
driver=new ChromeDriver(options);
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
navigateCommands();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void navigateCommands(){
try {
driver.navigate().to("https://www.flipkart.com/");
Thread.sleep(4000);
driver.findElement(By.className("2AkmmA _29YdH8")).click();
//driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
driver.findElement(By.xpath("//span[starts-with(text(),'Applicances')]")).click();
driver.findElement(By.xpath("//span[contains(text(),'Microwave Ovens')]")).click();
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(2000);
driver.navigate().forward();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TestNavigateCommands test1= new TestNavigateCommands();
test1.invokeBrowser();
}
}
Exception :
[43.366][SEVERE]: Timed out receiving message from renderer: 37.150
[43.373][SEVERE]: Timed out receiving message from renderer: -0.007
org.openqa.selenium.TimeoutException: timeout
Try this code it may help:
public class TestNavigateCommands {
public static void main(String[] args) throws InterruptedException {
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver,50 );
driver.manage().window().maximize();
driver.navigate().to("https://www.flipkart.com/");
driver.findElement(By.xpath("//button[contains(#class,'YdH8')]")).click();
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[#title='Appliances']//span"))));
driver.findElement(By.xpath("//a[#title='Appliances']//span")).click();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
driver = new ChromeDriver(options);
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
navigateCommands();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void navigateCommands() {
try {
driver.navigate().to("https://www.flipkart.com/");
driver.findElement(By.xpath("//div[#class='_3Njdz7']//button[#class='_2AkmmA _29YdH8']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[#title='Appliances']//span"))));
driver.findElement(By.xpath("//a[#title='Appliances']//span")).click();
Thread.sleep(2000);
driver.navigate().back();
driver.navigate().forward();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am trying to run TestNG testcases which are InterDependent say in a Travel site Test cases are 1st) Login 2nd) Booking 3rd) Cancellation etc.
I am facing 'NullPointer exception' on When Webdriver is Called on 2nd Test..
Any Idea as I have also declared Driver as public static.
I am reading the Locators from a Properties File.
Is It a TestNG bug ?
Here's my Code, Please Scroll Down to see the Pointer exception..
public class LoginTest {
public static WebDriver driver;
public static Properties p;
public static FileInputStream f ;
#Test
public void loginTest() {
System.out.println("Enter LoginTest");
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebDriver driver = new FirefoxDriver();
driver.get("https://in3.seatseller.travel/");
driver.manage().window().maximize();
// Login Process Starts here ..
try{
driver.findElement(By.name(p.getProperty("login.username.textfield"))).sendKeys("user");
driver.findElement(By.name(p.getProperty("login.password.textfield"))).sendKeys("password");
WebElement ele =driver.findElement(By.id(p.getProperty("login.signin.button")));
ele.click();
/*String classValue = ele.getAttribute("class");*/
}
catch (Exception e) {
}
}
#Test (dependsOnMethods={"loginTest"})
public void booking() throws InterruptedException{
System.out.println("Enter Booking");
// Type Bangalore on Source Field..
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*Null Pointer is on Below Line*/
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.source.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys("Bangalore");
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys(Keys.TAB);
Thread.sleep(900L);
The issue is that you're declaring WebDriver driver in loginTest(), then trying to reference the loginTest() instance of driver in booking().
If you modify loginTest() as follows, it should work:
driver = new FirefoxDriver();