While using selenium with java, WebdriverManager is not running and the below code is giving null pointer exception. I have returned the driver at end of class.
I have one ask whether should I keep the Webdriver driver as static or not.
import io.github.bonigarcia.wdm.WebDriverManager;
public class Browserselector {
public WebDriver driver;
public static Properties prop;
public WebDriver initializeDriver() throws IOException {
{
String browserName = "firefox";
System.out.println(browserName);
if (browserName.contains("Chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.contains("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if (browserName.contains("FireFox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if (browserName.contains("EDGE")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
}
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("google.com");
return driver;
}
}
Thanks for your help in advance.
you are trying to start "firefox" - but the if condition checks for "Firefox", if you want to use it like that change the following condition
browserName.contains("FireFox")
into
browserName.equalsIgnoreCase("FireFox")
I recommend you to change the nested if with a "switch" it's more readable and easy to follow/understand
Also, don't use a URL without specifying the protocol
driver.get("https://www.google.com");
Related
public class Prog1 {
public static void main(String[] args) {
System.setProperty("WebDriver.chrome.driver", "D:\\Users\\sh\\workspace\\Java2020\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println("Hello world");
You need to replace this line; don't use upper case "Webdriver.chrome.driver"
System.setProperty("webdriver.chrome.driver", "C:/drivders/chromedriver.exe");
And also change this driver1 to use driver
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Time out exception driver object should be driver instead of driver1
I am running my Cucumber suite tests with TestNG (Selenium + Java) and getting java.lang.NullPointerException.
I realized the problem is that my #BeforeTest() is being ignored for some reason causing the NullPointer problem.
I am using the TestNG 7.0.0 (but tried to use latest Beta also).
#BeforeTest()
public void setUp() {
driver = Web.createChrome(); // it call a method that has the Chromedriver
}
Web.java
public class Web {
public static WebDriver createChrome() {
System.setProperty("webdriver.chrome.driver", webdriver_path);
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://the-internet.herokuapp.com/");
return driver;
}
}
Output
java.lang.NullPointerException
at br.dsanders.steps.steps.accessing_the_Tnternet_herokuapp_com_website(steps.java:62)
at ?.Given accessing the Tnternet.herokuapp.com website(testing.feature:9)
Try like below:
public class steps {
WebDriver driver = null;
public steps() {
this.driver=Web.createChrome();
}
#BeforeMethod()
public void setUp() {
driver.get("http://the-internet.herokuapp.com/");
}
}
Note ClassName here is steps if you have other class name then change the class name and constructor name.
Change the #BeforeTest to #BeforeMethod
Source:
What is the difference between BeforeTest and BeforeMethod in TestNG
I get an exception when I run my test. I am using selenium with page factory. When I run following code ,it will open up the website and fail with exception below. it doesn't perform the HomePage.ClickbtnCookieWarning() in my test case.
Can someone please help me to understand why my code isn't working?
FAILED CONFIGURATION: #BeforeTest SetUp java.lang.NullPointerException
at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.click(Unknown Source) at
pageObjects.HomePage.ClickLoginLink(HomePage.java:57) at
myaccountsuite.TC1DefaultDeliveryAddDisplay.SetUp(TC1DefaultDeliveryAddDisplay.java:29)
Home Page page object
public class HomePage {
WebDriver driver;
public HomePage (WebDriver driver)
{
this.driver=driver;
}
#FindBy(id="ctl00_header_hdrCookieWarning_btnHideCookieWarning")
WebElement btnCookieWarning;
#FindBy(xpath=".//*#id='ctl00_masterContainerTop_Block_637_LoginView1_ulAnonymous']/li[2]/a")
WebElement LoginLink;
public void ClickbtnCookieWarning()
{
btnCookieWarning.click();
}
public void ClickLoginLink()
{
LoginLink.click();
}
}
Login Page Object
public class login {
WebDriver driver;
public login(WebDriver driver)
{
this.driver = driver;
}
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_UserName")
WebElement UserName;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_Password")
WebElement Password;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_LoginButton")
WebElement btn_LogIn;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_txtAccount")
WebElement Account;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_btnHomeBranch_3")
WebElement btn_Continue;
public void userLogin(String uname, String pass, String acc)
{
UserName.sendKeys(uname);
Password.sendKeys(pass);
btn_LogIn.click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Account.sendKeys(acc);
btn_LogIn.click();
btn_Continue.click();
}
}
My Test
public class TC1DefaultDeliveryAddDisplay {
public WebDriver driver;
#BeforeTest(alwaysRun = true)
public void SetUp() {
HomePage HomePage = PageFactory.initElements(driver, HomePage.class);
login loginpage = PageFactory.initElements(driver, login.class);
driver = new FirefoxDriver();
driver.get("http://URL/");
HomePage.ClickbtnCookieWarning();
HomePage.ClickLoginLink();
loginpage.userLogin("aa#yahoo.com", "125", "Test");
}
You're getting NullPointerException because you're using WebDriver instance before initialising.
You need to Initialize WebDriver before using this instance as :-
driver = new FirefoxDriver();
HomePage HomePage = PageFactory.initElements(driver, HomePage.class);
Login loginpage =PageFactory.initElements(driver, login.class);
If you want to use WebDriver as singleton which returns single instance for all your test methods you can follow this answer which is exactly you want.
The problem is in each class you are creating new instance of driver. You just need to create one driver instance in you base class where you do your browser setup. Please refer Page Object Model. Once the Driver instance is created you need to use the same in all your classes. Or else it will throw NullPointerException because driver will not have any reference.
I'd appreciate and thank for any advice here. I am trying to user the driver object from POM framework by use of TestNG and implementing ITestListerner interface.
This is a TestNG class implementing ItestListener
public class TestNGListener implements ITestListener {
#Override
public void onFinish(ITestContext result) {
WebDriver driver = BrowserFactory.LanuchBrowser("firefox", "http://10.207.182.108:81/opencart/");
Util.takescreenshot(driver, result.getName());
}
This class is used to return a WebDriver Object after launch one of the browser from switch case. I am using same driver as apart of TestNG by implementing Itestlistener & overriding failure public void onFinish(ITestContext result) in the above class & unfortunately, it doesn't return a webdriver object & take a screen shot but launches a new browser instead.
public class BrowserFactory {
static WebDriver driver;
public static WebDriver LanuchBrowser(String Brwsr, String URL){
System.out.println(Brwsr.toLowerCase());
switch (Brwsr.toLowerCase()){
case "firefox":
driver=new FirefoxDriver();
break;
case "chrome":
driver= new ChromeDriver();
System.setProperty("WebDriver.chrome.driver", "chromedriver.exe");
break;
case "internet explorer":
System.out.println("IE");
driver= new InternetExplorerDriver();
System.setProperty("WebDriver.IE.driver","IEDriverServer.exe");
break;
default:
System.out.println("Please select one of the Browsers listed : Chrome,Firefox or InternetExplorer");
break;
}
driver.manage().window().maximize();
driver.get(URL);
return driver;
}
}
Here is my method to capture screenshot
public class Util {
final static Logger logger = Logger.getLogger(Util.class);
public static void validatePgeNavgtn(WebDriver driver, String PgeTitle){
PropertyConfigurator.configure("log4j.properties");
String pgtitle=driver.getTitle();
if (pgtitle.equalsIgnoreCase(PgeTitle)){
logger.info("title matched");
}
}
public static void takescreenshot(WebDriver driver, String screen){
TakesScreenshot ts = (TakesScreenshot)driver;
File src= ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(src, new File("./Screenshot/"+screen+".png"));
} catch (IOException e) {
logger.warn(e.getMessage());
}
}
Could you please suggest an approach that below method shouldn't launch a new browser session but the focus should be retained on first browser instance & also capture a screenshot
You need create BrowserFactory class as singleton which will create always give single instance of BrowserFactory as below :-
public class BrowserFactory {
private WebDriver driver;
private static BrowserFactory browserFactoryInstance = null;
private BrowserFactory(String Brwsr, String URL) {
System.out.println(Brwsr.toLowerCase());
switch (Brwsr.toLowerCase()) {
case "firefox":
this.driver = new FirefoxDriver();
break;
case "chrome":
System.setProperty("WebDriver.chrome.driver", "chromedriver.exe");
this.driver = new ChromeDriver();
break;
case "internet explorer":
System.out.println("IE");
System.setProperty("WebDriver.IE.driver", "IEDriverServer.exe");
this.driver = new InternetExplorerDriver();
break;
default:
System.out
.println("Please select one of the Browsers listed : Chrome,Firefox or InternetExplorer");
break;
}
this.driver.manage().window().maximize();
this.driver.get(URL);
}
public static BrowserFactory getInstance(String Brwsr, String URL) {
if(browserFactoryInstance == null) {
browserFactoryInstance = new BrowserFactory(Brwsr, URL);
}
return browserFactoryInstance;
}
public WebDriver getDriver() {
return this.driver;
}
}
Now you can get WebDriver instance as below :-
//It will return always single instance per test run
WebDriver driver = BrowserFactory.getInstance("firefox", "http://10.207.182.108:81/opencart/").getDriver();
Util.takescreenshot(driver, result.getName());
I am new to phantomjs driver, I need to run my script in background using phantomjs headless driver.
Here is my code i am getting null-pointer exception.
currently am using selenium 2.32,testNG,phantomjs jar 1.0.3
public class PhantomjsDemo {
public WebDriver driver;
#BeforeMethod
public void setup(){
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", true);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,"C:\\phantomjs-1.9.2-windows\\phantomjs.exe");
WebDriver driver = new PhantomJSDriver(caps);
driver.get("www.google.com");
}
#Test
public void google(){
driver.findElement(By.xpath("//*[#id='gbqfba']")).getText();
driver.findElement(By.xpath("//*[#id='gbqfba']")).getSize().getHeight();
driver.findElement(By.xpath("//*[#id='gbqfba']")).getSize().getWidth();
driver.findElement(By.xpath("//*[#id='gbqfba']")).click();
}
#AfterMethod
public void close(){
driver.quit();
}
}
You are not initializing your Webdriver member variable in the setup() method, but a method variable:
WebDriver driver = new PhantomJSDriver(caps);
Change it to
this.driver = new PhantomJSDriver(caps);
and the NPE should go away.