JUnit Parallel Testing - selenium

I'm trying to run a piece of code that I found online to run JUnit test in parallel but the only thing I've modified is the URL to hit my local host. Problem is I'm constantly getting the following error and even though I've setup selenium grid many times and know how to set paths etc. I don't know how to fix this one.
org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see http://code.google.com/p/selenium/wiki/InternetExplorerDriver.
here's the code
package AutomationFrameWork;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;
public class Parallelized extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService executor;
public ThreadPoolScheduler() {
String threads = System.getProperty("junit.parallel.threads", "16");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}
#Override
public void finished() {
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
#Override
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
}
}
public Parallelized(Class<?> klass) throws Throwable {
super(klass);
setScheduler(new ThreadPoolScheduler());
}
}
package AutomationFrameWork;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
#RunWith(Parallelized.class)
public class JUnitParallel {
private String platform;
private String browserName;
private String browserVersion;
private WebDriver driver;
#Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
env.add(new String[]{Platform.WINDOWS.toString(), "chrome", "27"});
env.add(new String[]{Platform.WINDOWS.toString(),"firefox","20"});
env.add(new String[]{Platform.WINDOWS.toString(),"ie","11"});
env.add(new String[]{Platform.WINDOWS.toString(),"safari","5.1.7"});
//add more browsers here
return env;
}
public JUnitParallel(String platform, String browserName, String browserVersion) {
this.platform = platform;
this.browserName = browserName;
this.browserVersion = browserVersion;
}
#Before
public void setUp() throws Exception {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("platform", platform);
capability.setCapability("browser", browserName);
capability.setCapability("browserVersion", browserVersion);
capability.setCapability("build", "JUnit-Parallel");
capability.setCapability("InternetExplorerDriverServer.IE_ENSURE_CLEAN_SESSION",true);
System.setProperty("webdriver.ie.driver",
"C:\\Users\\path to driver\\IEDriverServer.exe");
driver = new RemoteWebDriver(
new URL("http://localhost:7777".concat("/wd/hub")),
capability
);
}
#Test
public void testSimple() throws Exception {
driver.get("http://www.google.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
driver = new Augmenter().augment(driver);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("Screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}

Related

NUll Pointer Exception using getTilte(); Selenium with Java

Have two classes one Login and the other which is the TestNG class, I created variable to get the Title of the page but when trying to run the test it is displaying null pointer exception, if I remove the getTitle variable it runs.
package main;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Login {
WebDriver driver ;
By userNameTextBox = By.name("email");
By passwordTestBox = By.id("password");
By loginButton = By.id("signInButton");
String titleText = driver.getTitle();
public Login(WebDriver driver) {
this.driver=driver;
}
public void setUserName() {
driver.findElement(userNameTextBox).sendKeys("v-tobias.rivera#shutterfly.com");
}
public void setPassword() {
driver.findElement(passwordTestBox).sendKeys("Indecomm1");
}
public void clickLogin() {
driver.findElement(loginButton).click();;
}
}
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
//import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
//import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import main.Login;
public class LoginTest {
WebDriver driver;
Login objLogin;
#BeforeMethod
public void beforeTest() {
System.setProperty("chromedriver", "/Users/tobiasriveramonge/eclipse-
workspaceAutomation/seleniumAutomation");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://accounts.shutterfly.com/?
redirectUri=https%3A%2F%2Fwww.shutterfly.com%2F&cid=&brand=SFLY&theme=SFLY");
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));
WebElement element =
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("email")));
element.isDisplayed();
}
#Test
public void Test() {
objLogin = new Login(driver);
//String title = objLogin.getTitle();
// System.out.println(title);
//Assert.assertTrue(loginPageTitle.toLowerCase().contains(" "));
objLogin.setUserName();
objLogin.setPassword();
objLogin.clickLogin();
}
#AfterTest
public void afterTest() {
driver.quit();
}
}
I would like to know why am I getting this exception.
Hi, Have two classes one Login and the other which is the TestNG class, I created variable to get the Title of the page but when trying to run the test it is displaying null pointer exception, if I remove the getTitle variable it runs.
You did not initialize the driver object.
That's why referencing to that not initialized object throws the null pointer exception.
You only declared the driver object type by
WebDriver driver;
but never initialized it.

How Can I implement Hooks In Cucumber as a separate Class file?

This is the baseclass.
package utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
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.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BaseClass {
public static WebDriver driver;
public WebDriverWait wait;
public static Properties prop;
FileInputStream fis;
static String browserName;
String currentDir = System.getProperty("user.dir");
public BaseClass()
{
prop=new Properties();
try {
fis = new FileInputStream(currentDir + "/src/test/java/config/data.properties");
} catch (FileNotFoundException e1) {
}
try {
prop.load(fis);
} catch (IOException e) {
}
}
public static void initialization()
{
browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("Chrome"))
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
else if(browserName.contains("Firefox"))
{
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
else
{
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(prop.getProperty("url"));
}
}
This is login page
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import utils.BaseClass;
public class LoginPage extends BaseClass {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver= ldriver;
wait = new WebDriverWait(driver, 90);
PageFactory.initElements(driver, this);
}
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[1]//parent::div")
WebElement radioAccount;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[2]//parent::div")
WebElement radioVcNumber;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[3]//parent::div")
WebElement macId;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[4]//parent::div")
WebElement vSc;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[5]//parent::div")
WebElement rMn;
#FindBy(how=How.XPATH,using="//*[#id='txt_InputVal']")
WebElement enterRmn;
#FindBy(how=How.XPATH, using="//*[#id='btnsubmit']")
WebElement buttonSubmit;
public void clickRadioButtons()
{
wait.until(ExpectedConditions.visibilityOf(radioAccount));
radioAccount.click();
radioVcNumber.click();
macId.click();
vSc.click();
rMn.click();
}
public void loginWithRmn(String num)
{
rMn.click();
wait.until(ExpectedConditions.visibilityOf(enterRmn));
enterRmn.sendKeys(num);
}
public void clickOnLoginButton()
{
buttonSubmit.click();
}
}
This is step definition of login page.
package stepDefs;
import Pages.LoginPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import utils.BaseClass;
public class LoginStepDef extends BaseClass{
LoginPage login;
String title;
#Given("^User has launched URL on browser$")
public void user_has_launched_URL_on_browser()
{
BaseClass.initialization();
System.out.println("Browser Launched");
login = new LoginPage(driver);
}
#Given("^User is able to select different account types$")
public void user_is_able_to_select_different_account_types()
{
login = new LoginPage(driver);
login.clickRadioButtons();
}
#When("^User enters tries to login with Mobile Number \"([^\"]*)\"$")
public void user_enters_tries_to_login_with_Mobile_Number(String arg1)
{
login.loginWithRmn(arg1);
}
#Then("^User is logged in$")
public void user_is_logged_in()
{
login.clickOnLoginButton();
}
#After()
public void tearDown()
{
System.out.println("Browser Closed");
driver.quit();
}
}
This is test runner.
package runners;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features= {"src/test/java/featureFiles"},
glue= {"stepDefs"},
monochrome=true,
dryRun=false,
plugin= {"pretty"}
)
public class TestRunnerLogin {
}
How can I implement Hooks ?
Hooks as a different class file(Hooks.java) so that I don't have to write invoke browser again and again for further pages.
I want Hooks.java as a separate class and not implemented in some step definition.
this is my HOOKS file. maybe this can help you:
public class Hooks {
public static WebDriver driver;
#Before
public void startTest(Scenario scenario) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/mac/chromedriver");
driver = new ChromeDriver();
driver.get("http://google.com");
}
#After
public void tearDown(Scenario scenario) {
Helper.screenshot(scenario);
driver.close();
}
public static WebDriver getDriver() { 
return driver;
}
}
and follow how to use:
public class LoginSteps {
private LoginPage loginPage = new LoginPage(Hooks.getDriver());
#When("something")
public void signCheck()  {
Assert.assertTrue("Login", homePage.checkPage());
}
}

getWindowHandle() throws error message "Nullpointerexception"

this is a simple selenium function that is trying to get a windowhandle.
right at that statement it throws" Nullpointerexception"
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandles {
WebDriver achromeDriver;
String abaseUrl;
public void setUp() throws Exception {
abaseUrl = "http://letskodeit.teachable.com/pages/practice";
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
achromeDriver = new ChromeDriver();
achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
achromeDriver.manage().window().maximize();;
System.out.println("setup completed");
}
#Test
public void test() {
try{
String aparentwindowHandle = achromeDriver.getWindowHandle();
System.out.println("the parent window handle is "+ aparentwindowHandle);
WebElement aopenwindowelementbutton = achromeDriver.findElement(By.id("openwindow"));
aopenwindowelementbutton.click();
String achildwindowhandle = achromeDriver.getWindowHandle();
System.out.println("the child window handle is: " + achildwindowhandle);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A bit more details about your usecase and your observation would have helped us to debug the issue in a better way. However, it seems as you are using the junit framework and in-absence of any of the annotations the setUp() method is never executed.
As the test() method is annotated with #Test the program reaches there with achromeDriver as Null
Solution
A quick solution would be to add #Before annotation to setUp() method as follows:
#Before
public void setUp() throws Exception {
abaseUrl = "http://letskodeit.teachable.com/pages/practice";
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
achromeDriver = new ChromeDriver();
achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
achromeDriver.manage().window().maximize();;
System.out.println("setup completed");
}

Getting NullPointerException when trying to access Selenium Webdriver instance in below scenario.

I am trying to create a framework where I can run my test cases(test tags in xml file) in parallel in different browsers. I have tried using all combinations of testNG annotations but after reading a blog came to know that this can only be achieved by using testNg listners. I am using ThreadLocal to keep my driver thread-safe. I am getting null pointer exception when trying to access Webdriver in my test cases class in line LocalDriverManager.getDriver().get(url);
This is LocalBrowserFactory.Class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import DataProvider.ConfigDataProvider;
public class LocalDriverFactory {
public static WebDriver createInstance(String browserName) {
WebDriver driver = null;
ConfigDataProvider config=new ConfigDataProvider();
if (browserName.toLowerCase().contains("firefox")) {
System.setProperty("webdriver.gecko.driver", config.getgeckoPath());
driver = new FirefoxDriver();
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
}
if (browserName.toLowerCase().contains("chrome")) {
System.setProperty("webdriver.chrome.driver", config.getchromePath());
driver = new ChromeDriver();
}
driver.manage().window().maximize();
return driver;
}
}
This is my LocalDriverManager.class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
public static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
This is my ConfigPropertyReader.class
package DataProvider;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigDataProvider {
static Properties p;
public ConfigDataProvider()
{
File f =new File("C:/Eclipse/parallelframework/configuration/config.properties");
try {
FileInputStream fis = new FileInputStream(f);
p=new Properties();
p.load(fis);
}
catch (Exception e)
{
System.out.println("Custom Exception- cannot load properties file"+e.getMessage());
}
}
public String getvalue(String key)
{
return p.getProperty(key);
}
public String getUrl()
{
return p.getProperty("url");
}
public String getchromePath()
{
return p.getProperty("chromepath");
}
public String getgeckoPath()
{
return p.getProperty("firefoxpath");
}
public String getIEPath()
{
return System.getProperty("User.dir")+p.getProperty("IEPath");
}
}
This is WebDriverListner.class
package Listners;
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import BrowserFactory.LocalDriverFactory;
import BrowserFactory.LocalDriverManager;
public class WebDriverListner implements IInvokedMethodListener {
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
System.out.println(browserName);
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
System.out.println("Driver Set");
}
}
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
This is my sample testcase.class
package tests;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import BrowserFactory.LocalDriverManager;
public class sampleTest {
#Test
public void testMethod1() {
invokeBrowser("http://www.ndtv.com");
}
#Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
LocalDriverManager.getDriver().get(url);
}
}
Your Listener code is messed up. You basically have the beforeInvocation and afterInvocation in the wrong order.
Here's how it should have looked like
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
#Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
You basically would setup the webdriver into the thread local variable (push the webdriver instance into the thread local variable's context) from within the beforeInvocation and then within your afterInvocation method, you would pop it out and clean up the webdriver instance (by calling quit() ). In your case, your code is doing the opposite.
For more details you can refer to my blog post here.

how to remove error "Cannot instantiate class day2practice.day2" in testng class

package day2practice;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeSuite;
public class day2 {
ChromeDriver driver = new ChromeDriver();
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Ashok\\Desktop\\chromedriver.exe");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.navigate().to("http://live.guru99.com");
}
#Test
public void f() {
String actual = driver.getTitle();
String expected = "THIS IS DEMO SITE";
Assert.assertEquals(actual, expected, "page title is same");
}
#AfterMethod
public void close() {
driver.quit();
}
}
Don't instantiate ChromeDriver class before assigning the path to chromedriver.exe. Moved the instantiation code to beforeMethod.
try the following code:
package day2practice;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class day2 {
ChromeDriver driver;
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Ashok\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.navigate().to("http://live.guru99.com");
}
#Test
public void f() {
String actual = driver.getTitle();
String expected = "THIS IS DEMO SITE";
Assert.assertEquals(actual, expected, "page title is same");
}
#AfterMethod
public void close() {
driver.quit();
}
}