Issue: I'm trying to close my webdriver and and used both driver.close and driver.quit in my code and no luck. Is it required to have the #Before parameter in order to use the #After?
Code:
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Automate {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Test
public void LaunchChrome_Method1() {`
System.setProperty("webdriver.chrome.driver","C:\\Users\\HASANK\\Desktop\\tEST\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.google.com");
driver.get("https://www.google.com/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys("cnn");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("CNN - Breaking News, Latest News and Videos")).click();
}
#After
public void tearDown() throws Exception {
driver.close();
driver.quit();
}
Even i have faced the same issue earlier, try updating both the chrome and chromedriver and try one more time. If it is still not working try an alternate by creating a method
public static void killDriverInstance() {
try {
String basePath = System.getProperty("user.dir");
String finalPath = basePath + "\\src\\utils\\killDriver.bat";
Process process = Runtime.getRuntime().exec(finalPath);
process.waitFor();
} catch (Exception ex) {
System.out.println("Exception in killDriverInstance method:" + ex.toString());
}
}
and in killdriver.bat file write this
REM Kill Chrome Driver
taskkill /im chromedriver.exe /f
REM Kill Chrome browser
REM taskkill /im chrome.exe /f
Using this kind of method for this in C# language:
private void CloseChromeDriverProcesses()
{
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "chromedriver");
if (chromeDriverProcesses.Count() == 0)
{
return;
}
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
}
I think that some minutes, and you can rewrite this, using Java language.
Related
The setValue method putting value in the field too fast and losing some chars during a process.
sendKeys method doesn't work correctly too.
[https://pp.userapi.com/c849532/v849532534/1d4fe6/BEVb5_C3O8E.jpg][]
Appium Server 1.13.0
package appiumtests2;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.net.URL;
import static java.lang.Thread.sleep;
public class Stoloto {
/*
* static WebDriver driver;
* AndroidDriver driver;
*/
static AppiumDriver<MobileElement> driver;
public static void main(String[] args) {
try {
Stoloto stoloto = new Stoloto();
stoloto.openStoloto();
} catch (Exception exp) {
System.out.println(exp.getCause());
System.out.println(exp.getMessage());
exp.printStackTrace();
}
}
#Test
public void openStoloto() throws Exception {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "Pixel XL");
cap.setCapability("udid", "HT6B70200690");
cap.setCapability("platformName", "Android");
cap.setCapability("platformVersion", "9");
cap.setCapability("appPackage", "ru.stoloto.mobile");
cap.setCapability("appActivity", "ru.stoloto.mobile.ca.presentation.ui.activity.MainActivity");
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AppiumDriver<MobileElement>(url, cap);
System.out.println("Application Started...");
MobileElement onBoardContinue = driver.findElement(By.id("ru.stoloto.mobile:id/confirm"));
onBoardContinue.click();
onBoardContinue.click();
MobileElement onBoardLogin = driver.findElement(By.id("ru.stoloto.mobile:id/login"));
onBoardLogin.click();
MobileElement loginField = driver.findElement(By.id("ru.stoloto.mobile:id/user"));
String login = "testtesttest#gmail.com";
sleep(1000);
loginField.setValue(login);
MobileElement passwordField = driver.findElement(By.id("ru.stoloto.mobile:id/passwordInputEdit"));
String password = "qwertyqwerty";
sleep(1000);
passwordField.setValue(password);
driver.hideKeyboard();
MobileElement log_in = driver.findElement(By.id("ru.stoloto.mobile:id/buttonSubmit"));
log_in.click();
System.out.println("Test Completed");
}
}
I need to find a way to set value with a little delay or the other way, which help me to solve this problem.
You can use mobile:shell command for sending text to the device via adb shell
Map<String, Object> argv = new HashMap<>();
argv.put("command", "input");
argv.put("args", Lists.newArrayList("text", "your_text_here"));
driver.executeScript("mobile: shell", argv);
Alternatively you can consider using elementSendText function avaiable via Appium SeeTest Extension
driver.executeScript("seetest:client.elementSendText(\"NATIVE\", \"id=your_element_id\", \"0\", \"your_text_here\")");
try to use WebDriverWait in order to set the value
Recently, bump into this issues with selenium firefox driver.
Thanks in advance
Set UP
os.name: 'Mac OS X',
os.arch: 'x86_64',
os.version: '10.12.6',
java.version: '1.8.0_131'
Firefox version 56.0.1 (64-bit)
Gecko Driver Latest 0.19.0
The error shows failed:
org.openqa.selenium.SessionNotCreatedException: Tried to run command
without establishing a connection
I tried different ways to tackle it but always come with the same error.
1. update all the selenium test driver to the latest
2. specify the directory export PATH = $PATH driverDir
My code
package automationFramework;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class GeckoDriver {
private static WebDriver driver;
public static int random = 0;
private String baseURL;
// #BeforeClass : Executes only once for the Test-Class.
#BeforeClass
public static void setting_SystemProperties(){
System.out.println("System Properties seting Key value.");
}
// #Before : To execute once before ever Test.
#Before
public void test_Setup(){
System.out.println("Launching Browser");
if (random == 0) {
System.out.println("Start Chrome Browser Testing ");
System.setProperty("webdriver.gecko.driver", "/Users/Fannity/Desktop/Drivers/geckodriver"); // Chrome Driver Location.
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println("Session ID : " + ((RemoteWebDriver) driver).getSessionId() );
}
#Test
public void selenium_ScreenShot() throws IOException {
baseURL = "https://www.google.com/";
driver.get(baseURL);
System.out.println("Selenium Screen shot.");
File screenshotFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("/Users/Fannity/Desktop/JUNIT-Selenium.jpg"));
random += 1;
}
// #After : To execute once after ever Test.
#After
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.close();
driver.quit();
}
// #AfterClass : Executes only once before Terminating the Test-Class.
#AfterClass
public static void clearing_SystemProperties(){
System.out.println("System Property Removing Key value.");
System.clearProperty("webdriver.gecko.driver");
}
}
ERROR
https://gist.github.com/Fenici/f82f885486de37ae110fda8d7430df6e
Your problem is here:
#After
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.close();
driver.quit();
}
Try only with close().
Explanation here.
We generally get this , if we use driver.close() and driver.quit() together so it would be better if you remove driver.close();
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.quit();
}
There is problem I cant resolve for 2 days. I need to login in many browsers in many machines on same sites. Its time-consuming task so I decide to do it with Selenium. I think problem is that while running test selenium does not save cookies. I find that its real to save cookies in file and then open them in next selenium tests but i need all browsers are logged in for manual testing. Here is my code
package automationFramework;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class FirstTestCase {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
File profileDirectory = new File(
"C:\\Users\\User\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\n8a2y7sp.default");//path to firefox profile
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
driver = new FirefoxDriver(profile);
baseUrl = "http://facebook.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testVk() throws Exception {
driver.get(baseUrl);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(""); // login
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(""); //password
driver.findElement(By.id("loginbutton")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
What exactly do you mean? Do you try to achieve multiple browsers that access the same site simultaneously? If so, you will need to set up more than one driver instance.
If you'd like to achieve it sequentially, just use a loop where you open the driver and get the URL, do your thing, then kill the driver instance, repeat.
The question above covers what I need I have created successful test scripts using eclipse on windows, but now i need to be able to run it in a linux vm through SSH and I have tried many things online and not had any success I know some changes may need to be done to the code also but I havnt managed to do that successfully either so please see the code below.
I have copied the src(test scripts) and libs(jars) files from the eclipse workspace to the linux vm and understood that to execute the selenium standalone server i use java -jar but that is about it. If you could walk me through the steps that need to be taken to run a test on firefox in the vm.
I have java and firefox installed.
Test Script
package test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class CorrectTestBackLink {
public BrowserList.DriverToUse used_driver = BrowserList.DriverToUse.IEXPLORER;
private BrowserSelector selectedDriver = new BrowserSelector(used_driver);
private WebDriver driver = selectedDriver.getDriver();
private StringBuffer verificationErrors = new StringBuffer();
private String baseUrl;
private static String resulterValue = "110";
private String valuecheck1;
#Before
public void setUp() throws Exception {
baseUrl = "http://url/";
//Set the column number and datatype of column by using either StringColumnNumber"Letter" or IntColumnNumber"Letter.
// Add aditional columns to database class where necessary.
}
public void calcResultChecker(){
driver.findElement(By.id("resulter")).getAttribute("value");
String valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
if (valuecheck1.equals(resulterValue)){
System.out.println("The Resulting value ("+valuecheck1+") is CORRRECT!");
}else{
System.err.println("The Resulting value is ("+valuecheck1+") is INCORRRECT!");
}
}
#Test
public void test2() throws Exception {
//calc page
driver.get(baseUrl + "calc.php");
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Entering 10 into 'firstnumber' field!");
driver.findElement(By.name("firstnumber")).sendKeys("10");
Thread.sleep(200);
driver.findElement(By.name("secondnumber")).sendKeys("11");
System.out.println("Entering 11 into 'secondnumber' field!");
Thread.sleep(200);
System.out.println("Clicking calculate button!");
driver.findElement(By.name("Calculate")).click();
Thread.sleep(200);
//calc results page
assertEquals(baseUrl + "calcresult.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
assertEquals(valuecheck1, resulterValue);
Thread.sleep(200);
System.out.println("Clicking back Link!");
driver.findElement(By.linkText("Back")).click();
Thread.sleep(200);
//calc page check
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Test Complete");
Thread.sleep(200);
driver.quit();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
Browser Selector
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class BrowserSelector {
private WebDriver driver;
public BrowserSelector(BrowserList.DriverToUse used_driver){
switch (used_driver){
case CHROME:{
System.setProperty("webdriver.chrome.driver", "C:/path/chromedriver.exe");
driver = new ChromeDriver();
break;
}
case FIREFOX:{
driver = new FirefoxDriver();
break;
}
case IEXPLORER:{
System.setProperty("webdriver.ie.driver","C:/path/IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capabilities);
break;
}
}
}
public WebDriver getDriver(){
return driver;
}
}
People usually use either PhantomJS or "Headless Chrome" to run in a headless environment. Also, some people run regular browsers from a XVFB framebuffer. Here is a blog article that I found that explains how to install XVFB.
xvfb-run --server-args='-screen 0, 1024x768x16' google-chrome
-start-maximized http://example.com > /dev/null &
Using XVFB and VNC, you could probably login remotely and watch your tests run on the headless box but I haven't tried this. You would have to experiment with it.
I know very similar questions are already there, however I am a beginner to Java/Selenium WebDriver, and had originally created this in Selenium IDE, and then exported it as Java / JUnit4 / WebDriver and was hoping to get specific help, as I wasn't sure of exactly where I was going wrong. When I run as Java Application I get the error Selection does not contain a main type and when I run as Java Applet I get the error Selection does not contain an applet. Here is my code:
package com.exports.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Login {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.example.co.uk/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLogin() throws Exception {
driver.get(baseUrl + "/123example/index.jsp");
// ERROR: Caught exception [ERROR: Unsupported command [getEval | prompt("Username: ") | ]]
driver.findElement(By.name("LoginText1")).clear();
element.sendKeys(user input);
//driver.findElement(By.name("LoginText1")).clear();
//driver.findElement(By.name("LoginText1")).sendKeys(_username);
// ERROR: Caught exception [ERROR: Unsupported command [getEval | prompt("Password: ") | ]]
driver.findElement(By.name("password1")).clear();
element.sendKeys(user input);
//driver.findElement(By.name("password1")).clear();
//driver.findElement(By.name("password1")).sendKeys(_password);
driver.findElement(By.cssSelector("img[alt=\"Login\"]")).click();
// ERROR: Caught exception [ERROR: Unsupported command [windowFocus | | ]]
driver.switchTo().window("CarrierNet Desktop");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
Any help is greatly appreciated.
Insted of running it as a java application.
Run it as a JUNIT Test.
To expand on HemChe's answer (which set me on the right track):
Add the JUnit and Selenium .jar file locations to your classpath, then set the path to your webdriver (so Selenium knows how to control a browser), then call the JUnit runner with your class as the parameter. This is how it looks on my linux commandline
cd /path/to/my/compiled/class
java -classpath .:/path/to/junit/classes/*:/path/to/selenium/classes/* -Dwebdriver.gecko.driver=/path/to/geckodriver org.junit.runner.JUnitCore MyTestClass
and like magic, a Firefox window opens up and runs your test, with errors in the console.
The Selenium classpath should have the file client-combined-x.x.x-nodeps.jar
The JUnit classpath should have lots of files, including junit-x.xx.jar