Fail to run tests in Chrome headless mode - java

I am trying to run tests in Chrome headless mode but getting java.lang.NullPointerException
Chrome version: Version 72.0.3626.121 (Official Build) (64-bit)
Selenium version: 3.8.1
Chromedriver version: 2.45.615355
Here is my BaseTest:
public abstract class BaseTest {
public WebDriver driver;
protected abstract String getUrl();
#Before
public void setUp() {
Log.startLog("Test is Starting...");
System.setProperty("webdriver.chrome.driver", "src//test//resources//chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(true);
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(getUrl());
}
#After
public void tearDown() {
Log.endLog("Test is Ending...");
driver.manage().deleteAllCookies();
driver.close();
}
}
When I'm running tests, not in headless mode every test works good but in headless mode, I can't even run a simple test to understand if the headless mode is working or not.
Test example:
#Test
public void test() {
System.out.println(driver.getTitle());
}
Example URL: https://www.wikipedia.org/
UPDATE:
I've created new sample project with this code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class test {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/Users/alexsomov/Desktop/chromedriver2");
//Set Chrome Headless mode as TRUE
ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
//Instantiate Web Driver
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com/");
System.out.println("Page title is - " + driver.getTitle());
driver.close();
}
And bingo, everything works well... Need to figure out why code above from real project doesn't work seems something wrong with BaseTest class and when I run code with debugger I'm getting driver == null, maybe anyone have a solution how I can solve this problem :/
ANSWER
The solution was super easy, just need to change 1 string in setUp() method in BaseTest class.
This one:
WebDriver driver = new ChromeDriver(chromeOptions);
change to this:
driver = new ChromeDriver(chromeOptions);
and everything will work.

If you are using linux environment, may be you have to add --no-sandbox as well and also specific window size settings. --no-sandbox is no needed in windows if you set user container properly.
disable-gpu Only on Windows. Other platforms no longer require it. The --disable-gpu flag is a temporary work around for a few bugs.
if(browser.equalsIgnoreCase("HLChrome")){
//Headless chrome browser and configure
WebDriverManager.chromedriver().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("disable-gpu");
// chromeOptions.addArguments("window-size=1400,2100"); // linux should be activate
driver = new ChromeDriver(chromeOptions);

ANSWER The solution was super easy, just need to change 1 string in setUp() method in BaseTest class.
This one:
WebDriver driver = new ChromeDriver(chromeOptions);
change to this:
driver = new ChromeDriver(chromeOptions);
and everything will work.

Related

How to set up SauceLabs for TestNg Java

Can someone please help me to figure out how to set up saucelabs for testNg on Java?
I’ve tried different guides, and it’s always different variations of set up, here's one of the examples that didn't work for me
#BeforeClass
public void init() throws MalformedURLException {
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("username", "oauth-xxxxxx.yyyyyy-51awdfsa");
sauceOpts.setCapability("accesskey", "xxxxx-32b1-4c4d-ac70-yyyyyyyyy");
DesiredCapabilities options = new DesiredCapabilities();
options.setCapability("sauce:options", "sauceOpts");
options.setCapability("browserVersion", "latest");
options.setCapability("platformName", "windows 10");
options.setCapability("browserName","chrome");
Webdriver driver = new RemoteWebDriver(new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub"), options);
}
import com.saucelabs.saucebindings.testng.SauceBaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Example Test for running with the TestNG Sauce Bindings library.
*/
public class SauceBindingsTestngTest extends SauceBaseTest {
#Test
public void correctTitle() {
getDriver().navigate().to("https://www.saucedemo.com");
Assert.assertEquals("Swag Labs", getDriver().getTitle());
}
}
Chrome/Win10 is the default so no setup code is required. If you want to change the configuration, check the Sauce Bindings docs below.
Source Code for example
We have a Demo Java repo with any example you want, just browse the table of contents
We use Sauce Bindings to make the code so simple
This is working for me,
DesiredCapabilities DC = DesiredCapabilities.chrome();
DC.setBrowserName("chrome");
DC.setPlatform(Platform.WIN10);
driver = new RemoteWebDriver(new URL("https://oauth-jayanth_balakrishnan-ae.saucelabs.com:443/wd/hub"), DC); //http://127.0.0.1:4444/wd/hub

updated correct chrome driver path/driver version and add selenium jar too, but still getting below issue , could you help me for this?

code :
package Demo1;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Chrome {
public static void main(String[] args) {
WebDriver driver= new ChromeDriver();
System.setProperty("webdriver.chrome.driver","C:\\New folder\\chromedriver.exe");
driver.get("https://www.youtube.com/watch?v=BtmeQOcdIKI");
System.out.println(driver.getTitle());
}
}
error :
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:847)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:134)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:35)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:159)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
at Demo1.Chrome.main(Chrome.java:9)
You are setting the system property too late.
Looking at the stacktrace, the exception is being thrown while executing the following line of your code:
WebDriver driver= new ChromeDriver();
At that point, the line of your code that sets the system property hasn't been reached yet.
Evidently, you need to set the system property before creating the ChromeDriver object.
The first line in your main method should be :
System.setProperty("webdriver.chrome.driver","C:\\New folder\\chromedriver.exe");
something like this.
public class Chrome {
WebDriver driver = null;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.youtube.com/watch?v=BtmeQOcdIKI");
System.out.println(driver.getTitle());
}
}
should get the job done.

testNG problem runing a suite with open browser

I have 2 similar classes.
I changed the opening of the browser to ChromeOptions so the tests can't be execute when a browser is open.
When I am execute the testNG.xml (with the 2 tests) its open immiditly both of the browsers and the suite can't be run.
What should I need to change in order to execute this well ?
Thanks alot
public class Demo2 {
public static WebDriver driver;
public static void main(String[] args)
{
initializeDriver();
print2();
}
#BeforeTest
private static void initializeDriver() {
System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Selenium\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=C:/Users/עמית/AppData/Local/Google/Chrome/User Data");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
#Test
public static void print2()
{
driver.get("https://www.google.com");
System.out.println("1");
driver.close();
}
}
I think this path C:/Users/עמית/AppData/Local/Google/Chrome/User Data") should use alphabet letters. Even if you try to use this, please config your font type to use the popular font as UTF-8.

Open Chrome with selenium

public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
}
So I downloaded chromedriver.exe and tried opening Chrome using the following code, but every time I run this code I get the following error:
Error:java: package com.google.common.collect does not exist
And also whenever I try and run chromedriver.exe from desktop, chrome does not want to open.
Thanks in advance
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/myPC/Desktop/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("http://www.google.com");
}

how to test multiple browser(versions) with selenium and junit

I just discovered selenium - a great tool!
I plan to run/use selenium-ide generated junit4 code. But I need it to run with many browsers/web drivers.
Is there a junit/java-pattern for this use case? My first idea was to use #RunWith(Parameterized.class) and provide a List of WebDrivers (the parameter for the class - probably provided as an external file listing browsers and versions?!). Is this a good idea? Is it possible to provide a central #Parameters -method to be used by all my Selenium-tests?
What alternatives are there?
Probably it is possible to change the "Format" that Selenium exports to minimize manual changes?
Well, I do need to switch drivers from time to time, so I did this:
I initialize selenium related stuff in my own Class - called by name of the application and the driver is approached by the getters. When calling my class constructor, I use enum type of driver to initialize with:
private WebDriver driver;
public TestUI(Environment.DriverToUse drv){
switch (drv){
case CHROME:{
ChromeDriverService service = ChromeDriverService.createDefaultService();
File file = new File(TestUI.class.getResource("/chromedriver.exe").toURI());
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, file.getAbsolutePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(service,options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
break;
}
case FIREFOX:{
FirefoxProfile ffProfile = new FirefoxProfile();
ffProfile.setPreference("browser.safebrowsing.malware.enabled", false);
driver = new FirefoxDriver(ffProfile);
driver.manage().window().setPosition(new Point(0, 0));
java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension dim = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(dim);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
break;
}
public WebDriver getDriver(){
return driver;
}
of course my Environment class looks like this
public class Environment {
public enum DriverToUse {FIREFOX, CHROME};
// .. and some other stuff, because I need to test on different environments, so I store here Environment URL for example
And my test class looks something like this
#Before
public static final Environment.DriverToUse USED_DRIVER = Environment.DriverToUse.FIREFOX;
#Test
public void testVersionNumber() throws Exception{
TestUI testUI= new TestUI(USED_DRIVER);
WebElement version = testUI.getDriver().findElement(By.id("the Id of element"));
version.click();
//...
}
Use Selenium RC/Selenium Server. These come with the API's you will need to run remote tests in multiple browsers simply. Happy Hunting!
Check out the Selenide library. It's an open source wrapper for selenium that makes UI testing a breeze. Here's an example test.
#Test
public void userCanLoginByUsername() {
open("/login");
$(By.name("user.name")).setValue("johny");
$("#submit").click();
$(".loading_progress").should(disappear); // Waits until element disappears
$("#username").shouldHave(text("Hello, Johny!")); // Waits until element gets text
}

Categories