`
public class CucumberHooks {
public static void main(String[] args) {
}
protected static WebDriver driver;
#Before
public void setup() throws IOException {
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("extension_5_3_2_0.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
String browser = ReadPropertyFileSingleton.getInstance().getProp("browser");
driver = Util.setEnvironmentAndGetDriver(browser);
assert driver != null;
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public static WebDriver getDriver() {
return driver;
}
#After
public void close() {
driver.quit();
}}
The code where I added adblock extensions via crx file
When I run tests through a feature file, a regular browser without a blocker is launched
the browser is also launched already with a blocker, but it does not see the steps
what could be the problem and is it possible to use adblock this way?
Can you please tell me why the values jsonKeyboard and jsonMouse of null and because of this my actions do not work?
When I try to get my driver like that: driver = DriverFactory.getDriver();
private static WebDriver driver;
public static WebDriver getDriver() {
if (null == driver) {
LOG.info("The driver is null. Attempt to create new instance for webdriver.");
driver = new ChromeDriver();
}
return driver
But if I try to use some wrapper for my driver and get driver like that: driver = new AddLogsForWebDriver(DriverFactory.getDriver());
public class AddLogsForWebDriver implements WebDriver {
private static final CustomLogger LOG = LoggerFactory.getLogger();
private final WebDriver driver;
public AddLogsForWebDriver(WebDriver driver) {
this.driver = driver;
}
#Override
public void get(String url) {
driver.get(url);
LOG.info("The " + url + " was opened.");
}
#Override
public String getCurrentUrl() {
LOG.info("The current url was got.");
return driver.getCurrentUrl();
}
...
}
After that my Actions don't work
Any help would be helpful. Thank you
When running tests in parallel sometimes I get this message:
org.openqa.selenium.NoSuchSessionException: invalid session id
I'm using WebDriverManager:
private WebDriver driver;
static { WebDriverManager.chromedriver().setup(); }
public Browser() {
Map<String, Object> prefs = new HashMap<>();
ChromeOptions chromeOptions = new ChromeOptions();
if (GVDLUtils.isOnServerEnv()) {
System.out.println("working on server");
chromeOptions.addArguments("--window-size=1400,900");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--no-proxy-server");
chromeOptions.addArguments("--proxy-server='direct://'");
chromeOptions.addArguments("--proxy-bypass-list=*");
}
String FilesPath = System.getProperty("user.dir") + File.separator + SeleniumUtilities.getDownloadsPath();
prefs.put("download.default_directory", FilesPath);
chromeOptions.setExperimentalOption("prefs", prefs);
this.driver = new ChromeDriver(chromeOptions);
if (!GVDLUtils.isOnServerEnv()) {
this.driver.manage().window().maximize();
}
}
And I initiate new browser before each test:
public static String redux = "";
protected Browser browser;
#BeforeMethod
public void initTest() {
this.browser = new Browser();
JavascriptExecutor jse = (JavascriptExecutor) this.browser.getDriver();
jse.executeScript("localStorage.setItem('redux', '"+redux+"')");
}
Any ideas why it happens?
My test is executed on my VM. Chrome loads first and then IE. IE Completes the test but Chrome gets orphaned. I think this has something to do with the threads connecting with the proper browser.
I have tried many hours trying different ways of setting up Parallel testing with Selenium/TestNG and the result is the same as I described above.
My goal is for both browsers to complete the test. Can you please help me.
Please find my code below.
public class BaseTestDirectory {
// -------Reference Variables-------------
// ----- Regression Test Cases -----
LoginLogoutPage objBELogin;
HomeNavigationPage obj_navigation;
DirectoryPage obj_directory;
// -------------------------------
protected static WebDriver driver;
protected ExtentTest test;// --parent test
ExtentReports report;
ExtentTest childTest;
#BeforeClass
#Parameters(value={"browser"})
public void setUp(String browser) throws InterruptedException, MalformedURLException {
// --------Extent Report--------
if(browser.equals("Chrome")){
report = ExtentManager.getInstance();
System.setProperty("webdriver.chrome.driver", "C:\\GRID\\chromedriver.exe");
System.out.println(System.getenv("BUILD_NUMBER"));
String env = System.getProperty("BUILD_NUMBER");
if (env == null) {
driver = new RemoteWebDriver(new URL(COMPLETE_NODE_URL), OptionsManager.getChromeOptions());
driver.get(HOME_PAGE);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
} else {
driver = new ChromeDriver();
driver.get(HOME_PAGE);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
else if (browser.equals("IE")) {
report = ExtentManager.getInstance_IE();
System.setProperty("webdriver.ie.driver", "C:\\GRID\\IEDriverServer.exe");
System.out.println(System.getenv("BUILD_NUMBER"));
String env = System.getProperty("BUILD_NUMBER");
driver = new RemoteWebDriver(new URL(COMPLETE_NODE_URL), OptionsManager.getInternetExplorerOptions());
driver.get(HOME_PAGE);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
public class OptionsManager {
//Get Chrome Options
// --https://stackoverflow.com/questions/43143014/chrome-is-being-controlled-by-automated-test-software
// --https://stackoverflow.com/questions/56311000/how-can-i-disable-save-password-popup-in-selenium
public static ChromeOptions getChromeOptions() {
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("useAutomationExtension", false);
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.addArguments("--disable-features=VizDisplayCompositor");
options.addArguments("--start-maximized");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capability = DesiredCapabilities.chrome();
capability.setCapability(CapabilityType.BROWSER_NAME, "Chrome");
capability.setPlatform(Platform.XP);
capability.setBrowserName("Chrome");
capability.setCapability(ChromeOptions.CAPABILITY, options);
options.merge(capability);
return options;
}
public static InternetExplorerOptions getInternetExplorerOptions () {
InternetExplorerOptions capabilities = new InternetExplorerOptions();
capabilities.ignoreZoomSettings();
capabilities.setCapability("browser.download.folderList", 2);
capabilities.setCapability("browser.download.manager.showWhenStarting", false);
capabilities.setCapability("browser.helperApps.neverAsk.saveToDisk","application/octet-stream;application/csv;text/csv;application/vnd.ms-excel;");
capabilities.setCapability("browser.helperApps.alwaysAsk.force", false);
capabilities.setCapability("browser.download.manager.alertOnEXEOpen", false);
capabilities.setCapability("browser.download.manager.focusWhenStarting", false);
capabilities.setCapability("browser.download.manager.useWindow", false);
capabilities.setCapability("browser.download.manager.showAlertOnComplete", false);
capabilities.setCapability("browser.download.manager.closeWhenDone", false);
//capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");
//capabilities.setCapability("requireWindowFocus", true);
return capabilities;
}
}
Initializing the WebDriver object as a Thread Local for Parallel Test Execution: When you have decided to run your selenium's tests in parallel, your Webdriver object should be thread-safe i.e. a single object can be used with multiple threads at the same time without causing problems.
public class BaseTest {
//Declare ThreadLocal Driver (ThreadLocalMap) for ThreadSafe Tests
protected static ThreadLocal<RemoteWebDriver> driver = new ThreadLocal<>();
public CapabilityFactory capabilityFactory = new CapabilityFactory();
#BeforeMethod
#Parameters(value={"browser"})
public void setup (String browser) throws MalformedURLException {
//Set Browser to ThreadLocalMap
driver.set(new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilityFactory.getCapabilities(browser)));
}
public WebDriver getDriver() {
//Get driver from ThreadLocalMap
return driver.get();
}
#AfterMethod
public void tearDown() {
getDriver().quit();
}
#AfterClass void terminate () {
//Remove the ThreadLocalMap element
driver.remove();
}
}
Try to design your base class in the below given example
public class WebDriverFactory {
static WebDriver create(String type) throws IllegalAccessException{
WebDriver driver;
switch(type) {
case "Firefox":
driver = new FirefoxDriver();
break;
case "Chrome":
driver = new ChromeDriver();
break;
default:
throw new IllegalAccessException();
}
return driver;
}
}
public class BaseClass extends WebDriverFactory {
public static ThreadLocal<WebDriver> dr = new ThreadLocal<WebDriver>();
#Parameters("browser")
#BeforeMethod
public void beforemethod() throws IllegalAccessException{
WebDriver driver = new WebDriverFactory().create(browser);
setWebDriver(driver);
getWebDriver().manage().window().maximize();
getWebDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public void setWebDriver(WebDriver driver){
dr.set(driver);
}
public WebDriver getWebDriver(){
return dr.get();
}
#AfterMethod
public void aftermethod(){
getWebDriver().quit();
dr.set(null);
}
}
This is my first question ever asked here, so I hope I ask it the right way:
I'm working on a multimodule maven project to test a software that is still in a development. I've been using Cucumber, Selenium, JUnit for some time and doing online courses to improve my skills. In one of the tutorials was explained how to use Driver Factory and configuration files so I applied it to my project, but after that was unable to run any of the drivers (gecko/chrome/ie). Here is a big part of the code, so I hope someone can help :)
I catch the exception from the DriverFactory.class:
"Unable to load browser: null"
config.properties file has only one line:
browser=chrome
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
//Read Config
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (driver == null) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
FirefoxOptions options = new FirefoxOptions();
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
break;
case "chrome":
if (driver == null) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
/*case "ie":
if (driver == null) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", Constant.IE_DRIVER_DIRECTORY);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
}
*/
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
} finally {
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
return driver;
}
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch(IOException e) {
e.printStackTrace();
}
}
public String getBrowser() {
if(prop.getProperty("browser") == null) {
return "";
}
return prop.getProperty("browser");
}
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\geckodriver.exe";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\chromedriver.exe";
public class CreateCaseSteps extends DriverFactory {
//Background Steps
#Given("^user accesses the login page$")
public void userAccessesTheLoginPage() throws Throwable {
getDriver().get("http://localhost:8080/");
}
#When("^user enters a valid username")
public void userEntersAValidUsername(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='username']")).sendKeys(data.get(0).get(0));
}
#When("^user enters a valid password")
public void userEntersAValidPassword(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='password']")).sendKeys(data.get(0).get(0));
}
#And("^user clicks on the login button$")
public void userClicksOnTheLoginButton() throws Throwable {
getDriver().findElement(By.xpath("//input[#value='Login']")).click();
}
#Then("^user should be taken successfully to the login page$")
public void userShouldBeTakenSuccessfullyToTheLoginPage() throws Throwable {
Thread.sleep(3000);
WebElement logoutMenu = getDriver().findElement(By.xpath("//i[#class='glyphicon glyphicon-user']"));
Assert.assertEquals(true, logoutMenu.isDisplayed());
}