Appium - Unable to instantiate AndroidDriver - java

When I am trying to instantiate AndroidDriver class it is giving an error. Please help.
Code
import io.appium.java_client.android.AndroidDriver;
public class Testing {
#Test
public void testMethod() {
AndroidDriver driver;
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "samsung-sm_g530h-5554c610");
cap.setCapability("platformVersion", "4.4.4");
cap.setCapability("platformName", "Android");
cap.setCapability(CapabilityType.BROWSER_NAME, "");
cap.setCapability("appPackage", "com.whatsapp");
cap.setCapability("appActivity", "com.whatsapp.HomeActivity");
driver = new AndroidDriver(new URL("127.0.0.1:4723"), cap);
}
}
// Here is the error

It is giving an error: AndroidDriver is Raw type. You can initialize driver as below:
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
...
public class Testing()
{
public AppiumDriver driver;
...
#BeforeTest
public void testMethod()
{
driver = new AndroidDriver(new URL(Node), capabilities);
...
}
}

I also met this problem before, but I now have solved, and the reasons for this problem is because Java - client-(version number). jar is not compatible,So I will Java - client-(version number). jar replacement into Java - the client - 3.1.0. Jar.Hope to be able to help you!

Try replacing:
driver = new AndroidDriver(new URL("127.0.0.1:4723"), cap);
With:
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);

You are getting this error as AppiumDriver is now Generic, so it can be set to return elements of class MobileElement or IOSElement or AndroidElement without casting.
This change is introduced in Java client version 3.0 and above. Details can be found here
Also, app package, app activity and device name is sufficient enough to run tests. So, you can modify your code as:
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
public class Testing {
AndroidDriver<MobileElement> driver;
#Test
public void testMethod() {
DesiredCapabilities caps = new DesiredCapabilities() ;
caps.setCapability(MobileCapabilityType.DEVICE_NAME,"samsung-sm_g530h-5554c610");
caps.setCapability(MobileCapabilityType.APP_PACKAGE, "com.whatsapp");
caps.setCapability(MobileCapabilityType.APP_ACTIVITY, "com.whatsapp.HomeActivity");
driver = new AndroidDriver<MobileElement>(new URL ("http://127.0.0.1:4723/wd/hub"),caps);
}
}

Following is the correct way to initialize Androidriver:
public class AppiumController{
public static void main(String[] args) throws MalformedURLException{
AppiumDriver<?> driver;
final String URL_STRING = "http://127.0.0.1:4723/wd/hub";
URL url = new URL(URL_STRING);
File appDirAndroid = new File("src/main/resources/app/");
File appAndroid = new File(appDirAndroid, "in.amazon.mShop.android.shopping_2018-02-22.apk");
DesiredCapabilities androidCapabilities = new DesiredCapabilities();
androidCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
androidCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
androidCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator-5554");
androidCapabilities.setCapability("appPackage", "in.amazon.mShop.android.shopping");
androidCapabilities.setCapability("appActivity", "com.amazon.mShop.home.HomeActivity");
androidCapabilities.setCapability(MobileCapabilityType.APP, appAndroid.getAbsolutePath());
driver = new AndroidDriver<MobileElement>(url, androidCapabilities);
driver.closeApp();
}
}
The above piece of code will successfully launch the amazon app on emulator.

Related

Intellij Idea cannot resolve constructor

My problem is Firefox. I installed a different location. But I tried this solution isn't working for me.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxProfile;
import java.io.File;
public class firefoxDriver
{
public static void main(String[] args)
{
File pathBinary = new File("D:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathBinary);
FirefoxProfile ffProfile = new FirefoxProfile();
// Add .exe file
System.setProperty("webdriver.gecko.driver", "D:\\Docs\\Drivers\\geckodriver.exe");
// Create Firefox object driver.
WebDriver ffDriver = new FirefoxDriver(ffBinary, ffProfile);
ffDriver.get("https://google.com");
System.out.println(ffDriver.getTitle());
}
}
The error I get:
N.B - In your particular example you do not need to create a profile. New profile is created automatically by default. You use profiles when you have some pre-configured profiles persisted before you run your driver.
You can do this:
FirefoxOptions options = new FirefoxOptions();
options.setBinary(new FirefoxBinary(new File("...")));
options.setProfile(new FirefoxProfile(new File("...")));
WebDriver = new FirefoxDriver(options);
Another way to specify browser binary isto use system property:
System.setProperty(
FirefoxDriver
.SystemProperty.BROWSER_BINARY, "PATH_TO_YOUR_BINARY");
If you have a named profile set up for your instance of firefox browser, then you should do the following (like in previous case before you create a driver):
System.setProperty(
FirefoxDriver
.SystemProperty.BROWSER_PROFILE, "NAME_OF_PROFILE");
There is not constructor that is overloaded to have binary and profile together. You should use options.
Code :
System.setProperty("webdriver.gecko.driver", "D:\\Docs\\Drivers\\geckodriver.exe");
String pathBinary = "D:\\Program Files\\Mozilla Firefox\\firefox.exe";
FirefoxOptions ffOptions = new FirefoxOptions();
FirefoxProfile ffProfile = new FirefoxProfile(pathBinary);
ffOptions.setProfile(ffProfile);
ffOptions.setBinary("C:\\Program Files\\Mozilla Firefox 52\\firefox.exe");
// Create Firefox object driver.
WebDriver ffDriver = new FirefoxDriver(ffOptions);
ffDriver.get("https://google.com");
System.out.println(ffDriver.getTitle());
public static void main(String[] args)
{
// Add .exe file
System.setProperty("webdriver.gecko.driver", "D:\\Docs\\Drivers\\geckodriver.exe");
File pathBinary = new File("D:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathBinary);
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions ffOptions = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, ffOptions.setBinary(ffBinary));
// Create Firefox object driver.
WebDriver ffDriver = new FirefoxDriver(ffOptions);
ffDriver.get("https://google.com");
System.out.println(ffDriver.getTitle());
}
I solved my problem with this method. I don't know there is a much more simple solution.

I received this message and failed: java.lang.NullPointerException at org.openqa.selenium.support.pagefactory.DefaultElementLocator.find

I am creating Page Object Model for the first time using selenium and I came across the below error, while executing the code give below. Need help in figuring out what am I missing...
java.lang.NullPointerException at org.openqa.selenium.support.pagefactory.DefaultElementLocator.find
My Code for reference:
package Pages;
import org.openqa.selenium.*;
public class BaseClass {
public static WebDriver driver;
public static String URL1 = "https://math-dad.com";
public void setupWebDriver(String drivername)
{
if (drivername.equalsIgnoreCase("Chrome"))
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver =new ChromeDriver(options);
}
else if (drivername.equalsIgnoreCase("Fire Fox"))
{
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
driver =new FirefoxDriver(options);
}
}
public BaseClass()
{
System.out.println("Base Class Initiate");
}
}
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HeaderPage extends BaseClass{
#CacheLookup
#FindBy(xpath = "//div[#class='navbar-header']")
public static WebElement LOGO;
public displayHeader()
{
System.out.println(driver.findElement(By.xpath("//div[#class='navbar-header']")).getText());
}
public HeaderPage()
{
PageFactory.initElements(driver,this);
}
}
public class testHeaderPage extends HeaderPage{
#BeforeTest
public void beforeTest()
{
System.out.println("Before Test");
setupWebDriver("Chrome");
driver.get(URL1);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
}
#Test
public void test1HeaderLOGO()
{
displayHeader(); // this is succesful
String Actual = LOGO.getText(); // Fails from this statement
System.out.println("Header LOGO: "+Actual);
String expected = "Math Dad";
Assert.assertEquals(Actual, expected, "Invalid Header");
}
#AfterTest
public void afterTest() {
drive.close();
}
}
In HeaderPage Classs, I am able to use 'driver' directly, but declaration of Page Factory element is failing. Any help on this please?
Use #BeforeClass annotation with this method so that Before Test driver can be initialized. This method will then execute Before every test.
#BeforeClass
public void setupWebDriver(String drivername) {
if (drivername.equalsIgnoreCase("Chrome"))
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver =new ChromeDriver(options);
}
else if (drivername.equalsIgnoreCase("Fire Fox"))
{
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
driver =new FirefoxDriver(options);
}
}

How can I use #BeforeTest for Capabilities class / or correctly extends on each #Test

I would like to create one class in which to insert #BeforeTest Capabilities. Referencing the below code, it is easy to insert tests into #Test.
Without TestNG everything works, but it doesn't work with TestNG.
Maybe I misunderstood something?
Class with Capabilities
public class test {
public static AndroidDriver<AndroidElement> Capabilities() throws MalformedURLException {
File f =new File("src");
File fs = new File(f,"ApiDemos-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "demo");
capabilities.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
AndroidDriver<AndroidElement> driver= new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
return driver;
}
Test example with extends Capabilities From test
public class swiping extends test {
public static void main(String[] args) throws MalformedURLException, InterruptedException {
AndroidDriver<AndroidElement> driver=Capabilities();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.TextView[#text='Views']").click();
driver.findElementByXPath("//android.widget.TextView[#text='Date Widgets']").click();
driver.findElementByAndroidUIAutomator("text(\"2. Inline\")").click();
driver.findElementByXPath("//*[#content-desc='9']").click();
Thread.sleep(1000);
TouchAction t=new TouchAction(driver);
WebElement first=driver.findElementByXPath("//*[#content-desc='15']");
WebElement second=driver.findElementByXPath("//*[#content-desc='45']");
t.longPress(longPressOptions().withElement(element(first)).withDuration(ofSeconds(2))).moveTo(element(second)).release().perform();
}
}
The below example shows a TestNG example of how to do the same thing.
The example leverages ThreadLocal so that tomorrow if you decide to run multiple #Test methods in parallel wherein every #Test method needs its own AndroidDriver instance, this would still work.
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static io.appium.java_client.touch.offset.ElementOption.element;
import static java.time.Duration.ofSeconds;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestClassExample {
//We use thread local so that even if you decide to run tests in parallel, every #Test method
//will get its own AndroidDriver instance
private static final ThreadLocal<AndroidDriver> drivers = new ThreadLocal<>();
#BeforeMethod
public void setupDriver() throws MalformedURLException {
File f = new File("src");
File fs = new File(f, "ApiDemos-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "demo");
capabilities.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
AndroidDriver driver =
new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
drivers.set(driver);
}
#AfterMethod
public void cleanupDriver() {
drivers.get().quit();
drivers.remove();
}
#Test
public void testMethod() throws InterruptedException {
AndroidDriver driver = drivers.get();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.TextView[#text='Views']").click();
driver.findElementByXPath("//android.widget.TextView[#text='Date Widgets']").click();
driver.findElementByAndroidUIAutomator("text(\"2. Inline\")").click();
driver.findElementByXPath("//*[#content-desc='9']").click();
Thread.sleep(1000);
TouchAction t = new TouchAction(driver);
WebElement first = driver.findElementByXPath("//*[#content-desc='15']");
WebElement second = driver.findElementByXPath("//*[#content-desc='45']");
t.longPress(longPressOptions().withElement(element(first)).withDuration(ofSeconds(2)))
.moveTo(element(second))
.release()
.perform();
}
}
PS: You should not be using #BeforeTest because that gets executed only once per <test> tag. You are better off using either a #BeforeClass (which gets executed once per test class (or) a #BeforeMethod (which gets executed once per #Test method)

I can't open anything with Selenium WebBrowser Java

I am trying to open local files with Selenium. With the code below, Firefox is opening, but I have the error org.openqa.selenium.WebDriverException: Timed out waiting 45 seconds for Firefox to start..
File gecko = new File("resources/geckodriver64.exe");
System.setProperty("webdriver.gecko.driver", gecko.getAbsolutePath());
FirefoxOptions capabilities = new FirefoxOptions();
capabilities.setCapability("marionette", false);
WebDriver driver = new FirefoxDriver(capabilities);
driver.get("file:///C:/example/myfile.pdf");
Can someone help me ? I couldn't find anything on the internet.
We have now come to the part where you will see how you can use GeckoDriver to launch Firefox. You will first need to download GeckoDriver and then set its path. There are three different ways to use GeckoDriver with Selenium 3:
With setting system properties in the test
With setting system properties by Environment Variable
With setting up Browser Desired Capabilities
Download Gecko Driver:-
1- Gecko Driver different versions can be downloaded from Github. I suggest you to use the latest version.
Set System Properties for Gecko Driver:-
Code to set the System properties is System.setProperty(“webdriver.gecko.driver”,”Path to geckodriver.exe”);
The complete program to launch the GeckoDriver will be like this:
package seleniumPrograms;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Gecko_Driver {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "D:\\\\XXXX\\trunk\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.toolsqa.com");
Thread.sleep(5000);
driver.quit();
}
}
Check Below answer. This is working solution on my machine. Please check your firefox version too.
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class geckodriver {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\username\\Downloads\\geckodriver-v0.20.1-win64\\geckodriver.exe");
Thread.sleep(5000);
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("marionette", true);
//
// WebDriver driver = new FirefoxDriver(capabilities);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.firefox();
capabilities.setBrowserName("firefox");
capabilities.setVersion("your firefox version");
capabilities.setPlatform(Platform.WINDOWS);
capabilities.setCapability("marionette", false);
WebDriver driver = new FireFoxDriver(capabilities);
driver.get("http://www.google.com");
Thread.sleep(5000);
driver.quit();
}}
Can you try below code ?
package seleniumPrograms;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Gecko_Driver {
public static void main(String[] args) throws InterruptedException {
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
driver.get("http://www.google.com");
Thread.sleep(5000);
driver.quit();
}

How to open incognito/private window with Selenium WD for different browser types?

I want to test my test cases in private window or incognito window.
How to do the same in various browsers:
firefox (prefered)
chrome (prefered)
IE
safari
opera
How to achieve it?
Chrome:
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("incognito");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
FireFox:
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
Internet Explorer:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true);
capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
Opera:
DesiredCapabilities capabilities = DesiredCapabilities.operaBlink();
OperaOptions options = new OperaOptions();
options.addArguments("private");
capabilities.setCapability(OperaOptions.CAPABILITY, options);
In chrome you can try using -incognito command line switch in options, not sure if there will be a problem with automation extension but worth a try.
ChromeOptions options = new ChromeOptions();
options.addArguments("incognito");
For FireFox, a special flag in the profile can be used for the purpose
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.private.browsing.autostart",true);
For IE
setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
FirefoxOptions opts = new FirefoxOptions();
opts.addArguments("-private");
FirefoxDrive f = new FirefoxDriver(opts);
This works fine for selenium version 3.14.0 and geckodriver-v0.22.0
public class gettext {
static WebDriver driver= null;
public static void main(String args[]) throws InterruptedException {
//for private window
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions option = new ChromeOptions();
option.addArguments("incognito");
capabilities.setCapability(ChromeOptions.CAPABILITY,option);
System.setProperty("webdriver.chrome.driver", "D:\\Tools\\chromedriver.exe");
driver= new ChromeDriver(capabilities);
String url = "https://www.google.com/";
driver.manage().window().maximize();
driver.get(url);
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
gettextdata();
}
}
Find the body element on the page and then fire off a Key Chord to it for the browser you want. In the sample below I've tried to abstract the browsers to an enumeration that outline the behavior for newTab, newWindow and newIncognitoWindow. I made content FF, IE, Chrome, Safari, and Opera; however, they may not be fully implemented due to my lack of knowledge.
/**
* Enumeration quantifying some common keystrokes for Browser Interactions.
*
* #see "http://stackoverflow.com/questions/33224070/how-to-open-incognito-private-window-through-selenium-java"
* #author http://stackoverflow.com/users/5407189/jeremiah
* #since Oct 19, 2015
*
*/
public static enum KeystrokeSupport {
CHROME,
FIREFOX {
#Override
protected CharSequence getNewIncognitoWindowCommand() {
return Keys.chord(Keys.CONTROL, Keys.SHIFT, "p");
}
},
IE {
#Override
protected CharSequence getNewIncognitoWindowCommand() {
return Keys.chord(Keys.CONTROL, Keys.SHIFT, "p");
}
},
SAFARI {
#Override
protected CharSequence getNewTabCommand() {
throw new UnsupportedOperationException("Author does not know this keystroke");
}
#Override
protected CharSequence getNewWindowCommand() {
throw new UnsupportedOperationException("Author does not know this keystroke");
}
#Override
protected CharSequence getNewIncognitoWindowCommand() {
throw new UnsupportedOperationException("Author does not know this keystroke");
}
},
OPERA {
#Override
protected CharSequence getNewIncognitoWindowCommand() {
throw new UnsupportedOperationException("Author does not know this keystroke");
}
};
public final void newTab(WebDriver driver) {
WebElement target = getKeystrokeTarget(driver);
target.sendKeys(getNewTabCommand());
}
public final void newWindow(WebDriver driver) {
WebElement target = getKeystrokeTarget(driver);
target.sendKeys(getNewWindowCommand());
}
public final void newIncognitoWindow(WebDriver driver) {
WebElement target = getKeystrokeTarget(driver);
target.sendKeys(getNewIncognitoWindowCommand());
}
protected CharSequence getNewTabCommand() {
return Keys.chord(Keys.CONTROL, "t");
}
protected CharSequence getNewWindowCommand() {
return Keys.chord(Keys.CONTROL, "n");
}
protected CharSequence getNewIncognitoWindowCommand() {
return Keys.chord(Keys.CONTROL, Keys.SHIFT, "t");
}
protected final WebElement getKeystrokeTarget(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 10);
return wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("body")));
}
}
With that then, we can offer a Parameterized test that will run through each of the configurations and execute the behaviors for visual verification. You may want to add whatever asserts you want to the test.
package stackoverflow.proof.selenium;
import java.util.Collection;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
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 com.google.common.base.Supplier;
import com.google.common.collect.Lists;
/**
* Test to try out some various browser keystrokes and try to get the environment to do what we want.
*
* #see "http://stackoverflow.com/questions/33224070/how-to-open-incognito-private-window-through-selenium-java"
* #author http://stackoverflow.com/users/5407189/jeremiah
* #since Oct 19, 2015
*
*/
#RunWith(Parameterized.class)
public class KeyStrokeTests {
#Parameters(name="{0}")
public static Collection<Object[]> buildTestParams() {
Collection<Object[]> params = Lists.newArrayList();
Supplier<WebDriver> ffS = new Supplier<WebDriver>() {
public WebDriver get() {
return new FirefoxDriver();
}
};
params.add(new Object[]{KeystrokeSupport.FIREFOX, ffS});
/* I'm not currently using these browsers, but this should work with minimal effort.
Supplier<WebDriver> chrome = new Supplier<WebDriver>() {
public WebDriver get() {
return new ChromeDriver();
}
};
Supplier<WebDriver> ie = new Supplier<WebDriver>() {
public WebDriver get() {
return new InternetExplorerDriver();
}
};
Supplier<WebDriver> safari = new Supplier<WebDriver>() {
public WebDriver get() {
return new SafariDriver();
}
};
Supplier<WebDriver> opera = new Supplier<WebDriver>() {
public WebDriver get() {
return new OperaDriver();
}
};
params.add(new Object[]{KeystrokeSupport.CHROME, chrome});
params.add(new Object[]{KeystrokeSupport.IE, ie});
params.add(new Object[]{KeystrokeSupport.SAFARI, safari});
params.add(new Object[]{KeystrokeSupport.OPERA, opera});
*/
return params;
}
Supplier<WebDriver> supplier;
WebDriver driver;
KeystrokeSupport support;
public KeyStrokeTests(KeystrokeSupport support,Supplier<WebDriver> supplier) {
this.supplier = supplier;
this.support = support;
}
#Before
public void setup() {
driver = supplier.get();
driver.get("http://google.com");
}
#Test
public void testNewTab() {
support.newTab(driver);
}
#Test
public void testNewIncognitoWindow() {
support.newIncognitoWindow(driver);
}
#Test
public void testNewWindow() {
support.newWindow(driver);
}
#After
public void lookAtMe() throws Exception{
Thread.sleep(5000);
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
driver.close();
}
}
}
Best of Luck.
For Chrome use this code to open the browser in incognito mode:
public WebDriver chromedriver;
ChromeOptions options = new ChromeOptions();
options.addArguments("-incognito");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver chromedriver=new ChromeDriver(capabilities);
chromedriver.get("url");
public static void OpenBrowser() {
if (Browser.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver", "E:\\Workspace\\proj\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("incognito");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
} else if (Browser.equals("IE")) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, false);
// if you get this exception "org.openqa.selenium.remote.SessionNotFoundException: " . uncomment the below line and comment the above line
// capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true);
System.setProperty("webdriver.ie.driver", "E:\\Workspace\\proj\\IEDriverServer32.exe");capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
driver = new InternetExplorerDriver(capabilities);
} else {
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
driver = new FirefoxDriver(firefoxProfile);
}
I was able to run remote IE in private mode only after following updates:
InternetExplorerOptions options = new InternetExplorerOptions()
.ignoreZoomSettings()
.useCreateProcessApiToLaunchIe()
.addCommandSwitches("-private");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability("se:ieOptions", options);
return new RemoteWebDriver(url, capabilities);
All of above didn't work for RemoteWebDriver.
How to avoid Extensions in Private Mode prompt
For the actual geckodriver version I use:
options.addArguments("-private");
It works fine but the annoying notification appears: Extensions in Private Mode.
I found the way to avoid it:
options.addPreference("extensions.allowPrivateBrowsingByDefault",true);
As a result all extensions will run in private browsing mode without prompting at start
For other browser everyone has answered
so for OPERA
OperaOptions options = new OperaOptions();
options.addArguments("private");
WebDriver driver = new OperaDriver(options);
driver.get("https://selenium.dev");

Categories