Getting NullPointerException error message while running the selenium code using testng - java

package utils;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import java.util.concurrent.TimeUnit;
public class BrowserUtils {
public WebDriver driver = null;
#BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\sdad\\Downloads\\Softwares\\BrowserDrivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
#AfterTest
public void tearDown(){
driver.close();
driver.quit();
}
}
package parallel_3;
import org.testng.Assert;
import org.testng.annotations.Test;
import parallel_2.Headers;
import parallel_2.Images;
import parallel_2.Styles;
import utils.BrowserUtils;
public class Test_01 extends BrowserUtils {
Headers headers;
Images images;
Styles styles;
private final String HEADER_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Headers.html",
IMAGES_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Images.html";
#Test
public void test(){
driver.get(HEADER_FILE_PATH);
headers = new Headers(driver);
Assert.assertEquals(driver.getTitle(), "Headers");
Assert.assertEquals(headers.header4.getText(), "This is Header 4");
headers.images_link.click();
images = new Images(driver);
Assert.assertEquals(driver.getTitle(), "Images");
Assert.assertEquals(images.header2.getText(), "Image with width and height");
images.styles_link.click();
styles = new Styles(driver);
Assert.assertEquals(driver.getTitle(), "Page Styles");
Assert.assertEquals(styles.paragraph.getText(), "This is a paragraph");
styles.images_link.click();
}
}
package parallel_3;
import org.testng.Assert;
import org.testng.annotations.Test;
import parallel_2.Headers;
import parallel_2.Images;
import parallel_2.Styles;
import utils.BrowserUtils;
public class Test_02 extends BrowserUtils {
Headers headers;
Images images;
Styles styles;
private final String HEADER_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Headers.html",
IMAGES_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Images.html";
#Test
public void test(){
driver.get(IMAGES_FILE_PATH);
images = new Images(driver);
Assert.assertEquals(driver.getTitle(), "Images");
Assert.assertEquals(images.header2.getText(), "Image with width and height");
images.styles_link.click();
styles = new Styles(driver);
Assert.assertEquals(driver.getTitle(), "Page Styles");
Assert.assertEquals(styles.paragraph.getText(), "This is a paragraph");
styles.images_link.click();
headers = new Headers(driver);
Assert.assertEquals(driver.getTitle(), "Headers");
Assert.assertEquals(headers.header4.getText(), "This is Header 4");
headers.images_link.click();
}
}
Error message
java.lang.NullPointerException
at parallel_3.Test_01.test(Test_01.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

#BeforeTest doesn't run for all the #Test, only before the first one, so driver is never initialized. From testng docs
#BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
You can use #BeforeMethod annotation for that
#BeforeMethod: The annotated method will be run before each test method.
Same goes for #AfterTest and #AfterMethod.

Related

Cannot instantiate class (Selenium)

I've run into the following error."Cannot instantiate class co.edureka.tests.FBLoginTest". Below I've posted the entire error console. I'm trying to use POM (Page Obeject Model) for Selenium. I'm believe the issue has to do with me creating too many drivers... I've been digging through online resources, but haven't found anything that resolves my issue.
FBLoginPage.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class FBLoginPage {
WebDriver driver;
public FBLoginPage(WebDriver driver) {
this.driver=driver;
}
#FindBy(how=How.XPATH, using="/html/body/div[1]/div[1]/div[1]/div/div/div/div[2]/div/div[1]/form/div[1]/div[1]/input")
public WebElement emailTextBox;
#FindBy(how=How.XPATH, using="//input[#type='password'][#name='pass']") WebElement passwordTextBox;
#FindBy(how=How.XPATH, using="//input[#type='submit'][#value='Log In']") WebElement signinButton;
// Defining all the user actions (Methods) that can be performed in the Facebook home page
// This method is to set Email in the email text box
public void setEmail(String strEmail) {
emailTextBox.sendKeys(strEmail);
}
public void setPassword(String strPassword) {
passwordTextBox.sendKeys(strPassword);
}
// This method is to click on Login Button
public void clickOnLoginButton() {
signinButton.click();
}
}
FBHomePage.java
package co.edureka.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class FBHomePage {
WebDriver driver;
public FBHomePage(WebDriver driver) {
this.driver=driver;
}
#FindBy(how=How.XPATH, using="//div[text()='Account Settings']") WebElement profileDropdown;
#FindBy(how=How.LINK_TEXT, using="Log Out") WebElement logoutLink;
// Defining all the user actions (Methods) that can be performed in the Facebook home page
public void clickOnProfileDropdown() {
profileDropdown.click();
}
public void clickOnLogoutLink() {
logoutLink.click();
}
}
TestBase.java
package co.edureka.tests;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
public class TestBase {
public static WebDriver driver;
#BeforeSuite
public void initialize() throws IOException{
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
}
#AfterSuite
public void TeardownTest()
{
TestBase.driver.quit();
}
}
FBLoginTest.java
package co.edureka.tests;
import java.time.Duration;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import co.edureka.pages.FBHomePage;
import co.edureka.pages.FBLoginPage;
public class FBLoginTest extends TestBase {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
#Test
public void init() throws Exception{
//driver.get("https://www.facebook.com");
FBLoginPage loginpage = PageFactory.initElements(driver, FBLoginPage.class);
wait.until(ExpectedConditions.titleContains("Facebook"));
loginpage.setEmail("432547#gmail.com");
loginpage.setPassword("ashish.bakshi#selenium");
loginpage.clickOnLoginButton();
FBHomePage homepage = PageFactory.initElements(driver, FBHomePage.class);
homepage.clickOnProfileDropdown();
homepage.clickOnLogoutLink();
}
}
Error Console Results
[RemoteTestNG] detected TestNG version 7.4.0
org.testng.TestNGException:
Cannot instantiate class co.edureka.tests.FBLoginTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.InstanceCreator.instantiateUsingDefaultConstructor(InstanceCreator.java:193)
at org.testng.internal.InstanceCreator.createInstanceUsingObjectFactory(InstanceCreator.java:113)
at org.testng.internal.InstanceCreator.createInstance(InstanceCreator.java:79)
at org.testng.internal.objects.SimpleObjectDispenser.dispense(SimpleObjectDispenser.java:25)
at org.testng.internal.objects.GuiceBasedObjectDispenser.dispense(GuiceBasedObjectDispenser.java:30)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:112)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:165)
at org.testng.TestClass.getInstances(TestClass.java:122)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:102)
at org.testng.TestClass.init(TestClass.java:94)
at org.testng.TestClass.<init>(TestClass.java:59)
at org.testng.TestRunner.initMethods(TestRunner.java:463)
at org.testng.TestRunner.init(TestRunner.java:339)
at org.testng.TestRunner.init(TestRunner.java:292)
at org.testng.TestRunner.<init>(TestRunner.java:223)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.ITestRunnerFactory.newTestRunner(ITestRunnerFactory.java:55)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:659)
at org.testng.SuiteRunner.init(SuiteRunner.java:173)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:107)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1300)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1276)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1125)
at org.testng.TestNG.runSuites(TestNG.java:1063)
at org.testng.TestNG.run(TestNG.java:1031)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:79)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:23)
... 29 more
Caused by: java.lang.IllegalArgumentException: Input must be set
at org.openqa.selenium.internal.Require.nonNull(Require.java:59)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:97)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:77)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:46)
at co.edureka.tests.FBLoginTest.<init>(FBLoginTest.java:15)
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
... 32 more
If anyone has any suggestions I would appreciate it.
To solve this issue you should move the WebDriverWait initialization to the init or any other method in FBLoginTest.java like below.
package co.edureka.tests;
import java.time.Duration;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import co.edureka.pages.FBHomePage;
import co.edureka.pages.FBLoginPage;
public class FBLoginTest extends TestBase {
WebDriverWait wait;
#BeforeMethod
public void init() {
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
}
#Test
public void testLogin() throws Exception {
driver.get("https://www.facebook.com");
FBLoginPage loginpage = PageFactory.initElements(driver, FBLoginPage.class);
wait.until(ExpectedConditions.titleContains("Facebook"));
loginpage.setEmail("432547#gmail.com");
loginpage.setPassword("ashish.bakshi#selenium");
loginpage.clickOnLoginButton();
FBHomePage homepage = PageFactory.initElements(driver, FBHomePage.class);
homepage.clickOnProfileDropdown();
homepage.clickOnLogoutLink();
}
}

I am getting NPE when i try to validate a webElement using isDisplayed method. I am unable to access any webelement and action on it

I have a base class as follows where I load the property file and initialize browser
package com.mystore.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
//import org.apache.log4j.xml.DOMConfigurator;
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.PageFactory;
import org.testng.annotations.BeforeTest;
import io.github.bonigarcia.wdm.WebDriverManager;
import com.mystore.actiondriver.ActionDriver;
public class BaseClass1 {
public static Properties prop;
public static WebDriver driver;
//ActionDriver a = new ActionDriver();
#BeforeTest
public void loadConfig() {
try {
prop = new Properties();
System.out.println("super constructor invoked");
FileInputStream ip = new FileInputStream(
System.getProperty("user.dir") + "/Configuration/Config.properties");
prop.load(ip);
System.out.println("driver: "+ driver);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void launchApp() {
String browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("Chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
System.out.println("driver: "+ driver);
} else if (browserName.equalsIgnoreCase("FireFox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if (browserName.equalsIgnoreCase("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
}
ActionDriver.implicitWait(driver, 10);
ActionDriver.pageLoadTimeOut(driver, 30);
driver.get(prop.getProperty("url"));
}
}
Index page class which inherits BaseClass and code below
package com.mystore.pageobjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.mystore.actiondriver.ActionDriver;
import com.mystore.base.BaseClass;
import com.mystore.base.BaseClass1;
public class IndexPage1 extends BaseClass1{
#FindBy(xpath = "//a[#class='login']")
WebElement signInBtn;
#FindBy(xpath = "//img[#class='logo img-responsive']")
WebElement myStoreLogo;
#FindBy(id="search_query_top")
WebElement searchProductBox;
#FindBy(name="submit_search")
WebElement searchButton;
public IndexPage1() {
PageFactory.initElements(driver, this);
}
public LoginPage clickOnSignIn() {
ActionDriver.click(driver,signInBtn);
return new LoginPage();
}
public boolean validateLogo() throws Throwable{
System.out.println("Inside Validate Logo");
return myStoreLogo.isDisplayed();
//return true;
//return ActionDriver.isDisplayed(driver, myStoreLogo);
}
public String getMyStoreTitle() {
String myStoreTitle = driver.getTitle();
return myStoreTitle;
}
public SearchResultPage searchProduct(String productName) throws InterruptedException {
Thread.sleep(10000);
searchProductBox.sendKeys(productName);
Thread.sleep(10000);
System.out.println("I passed!");
ActionDriver.type(searchProductBox, productName);
ActionDriver.implicitWait(driver, 60);
ActionDriver.click(driver, searchButton);
return new SearchResultPage();
}
}
IndexPageTest class with test - where I try to call verifyLogo() test which checks if webElement myStoreLogo is displayed and should return true but returns false and NPE .
package com.mystore.testcases;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.mystore.base.BaseClass;
import com.mystore.base.BaseClass1;
import com.mystore.pageobjects.IndexPage;
import com.mystore.pageobjects.IndexPage1;
public class IndexPageTest1 extends BaseClass1{
IndexPage1 indexPage1 = new IndexPage1();
#BeforeMethod
public void setup() {
launchApp();
}
//#AfterMethod
public void tearDown() {
driver.quit();
}
#Test()
public void verifyLogo() throws Throwable{
//indexPage1= new IndexPage();
boolean result=indexPage1.validateLogo();
System.out.println("The value of result is:"+ result);
Assert.assertTrue(result);
}
#Test(enabled = false)
public void verifySearchProduct() throws InterruptedException {
indexPage1.searchProduct("t-shirt");
}
#Test(enabled=false)
public void verifyTitle() {
String actTitle=indexPage1.getMyStoreTitle();
Assert.assertEquals(actTitle, "My Store");
}
}
Gives results below
driver: ChromeDriver: chrome on MAC (fa4c8f6fb20e625d6d7e2b148850b17b)
Inside Validate Logo
FAILED: verifyLogo
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.$Proxy12.isDisplayed(Unknown Source)
at com.mystore.pageobjects.IndexPage1.validateLogo(IndexPage1.java:47)
at com.mystore.testcases.IndexPageTest1.verifyLogo(IndexPageTest1.java:40)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:597)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:816)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.testng.TestRunner.privateRun(TestRunner.java:766)
at org.testng.TestRunner.run(TestRunner.java:587)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
Please help, I'm not sure why the webelement is not identified. I tried with other web elements and they also get the same NPE.
The problem lies in your test code.
The WebDriver object that is part of your base class BaseClass1 is getting initialised only when the method launchApp() is invoked.
But the constructor of your page class IndexPage1 already tries to access the WebDriver object (which at the time of instantiation of IndexPage1 is null)
So you end up invoking PageFactory.initElements(driver, this); with a null value for driver
Solution.
Please remove the logic of managing your webdriver instances via your base class and segregate it to a separate utility method which when called can give you a WebDriver object. Alternatively you can also make use of a library such as Autospawn that I created which uses an annotation way of managing webdriver instances. - The documentation should explain how to use this library. Note that if you use this library, you would need to create all your page classes within your #Test method (because that's the only place wherein a valid WebDriver instance would be available in the current Thread's context)
Refactor your IndexPage1 class's constructor so that it accepts a WebDriver instance as a parameter from outside.

DataProvider using TestNG,Java and InteliJ Idea

I have implemented simple Login selenium framework using DataProvider.
I created a simple login page which contains username and password. I have also created excel file with login data and excel reader class as well. Seems that DataProvider within my test class fault.
I get the the information "java.lang.NullPointerException".I know that is something wrong with String in DataProvider, but if I changed to Object the issue is still as above.
Here is my code for testng:
package com.insurance.testCases;
import com.insurance.pageObjects.loginPage;
import com.insurance.utilities.excelReader;
import org.openqa.selenium.NoAlertPresentException;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
public class TC_LoginDdt_002 extends baseClass{
#Test(dataProvider = "loginData")
public void loginDDT(String user,String pwd){
driver.get(baseUrl);
loginPage lp=new loginPage(driver);
lp.setUserName(user);
lp.setPassword(pwd);
lp.clickSubmit();
if (isAlertPresent()==true){
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
Assert.assertTrue(false);
}
else {
Assert.assertTrue(true);
lp.clickLogout();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
}
public boolean isAlertPresent(){
try {
driver.switchTo().alert();
return true;
}
catch (NoAlertPresentException e){
return false;
}
}
#DataProvider(name="loginData")
String [][] getData() throws IOException {
String path="C:/Users/lachi/IdeaProjects/InetBanking_v1/target/DataSet.xls";
int rownum = excelReader.getRowCount(path,"DataSet");
int colcount = excelReader.getCellCount(path,"DataSet",1);
String logindata[][]=new String[rownum][colcount];
for (int i=1;i<=rownum;i++){
for (int j=0;j<colcount;j++){
logindata[i-1][j]=excelReader.getCellData(path,"DataSet",i,j);
}
}
return logindata;
}
}
exception below:
java.lang.NullPointerException
at com.insurance.testCases.TC_LoginDdt_002.loginDDT(TC_LoginDdt_002.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
base class:
package com.insurance.testCases;
import com.insurance.utilities.Log;
import com.insurance.utilities.readConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.annotations.Parameters;
import java.util.concurrent.TimeUnit;
public class baseClass {
readConfig readconfig = new readConfig();
public String baseUrl = readconfig.getApplicationUrl();
public String username = readconfig.getUsername();
public String password = readconfig.getPassword();
public static WebDriver driver;
public static Logger logger;
#Parameters("browser")
#Before
public void SetUp(){
Log.startLog("Test is Starting");
logger = Logger.getLogger("einsurance");
System.setProperty("webdriver.chrome.driver","Drivers/chromedriver.exe");
driver = new ChromeDriver();
//System.setProperty("webdriver.edge.driver","Drivers/msedgedriver.exe");
// driver = new EdgeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#After
public void tearDown(){
Log.endLog("Test is Ending!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
driver.quit();
}
public String randomestring(){
String generatedstring = RandomStringUtils.randomAlphanumeric(20);
return (generatedstring);
}
public static String randomeNum(){
String generatestring2 = RandomStringUtils.randomNumeric(8);
return (generatestring2);
}
}
The root cause of your problem is in your base class.
You are initialising/cleaning a WebDriver object via the Unit provided Before and After.
TestNG does not recognise JUnit setup and teardown annotations
To fix this problem, all you would need to do is to use
Instead of Before use org.testng.annotations.BeforeClass (or) BeforeMethod
Instead of After use org.testng.annotations.AfterClass (or) AfterMethod
I suspect your baseUrl seems to be empty based on NPE at line 17 of TC_LoginDdt_002. Run in Debug mode to ensure your public String baseUrl = readconfig.getApplicationUrl(); is actually retrieving and initializing the baseUrl to your desired URL

How to Handle Alerts Using Headless Browsers (HtmlUnitDriver/Phantomjs Driver)

I am using PhantomJs Driver for Headless Testing , I am getting below exception
Sample code:
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestLogin {
WebDriver d;
#BeforeMethod
public void launh_Browser() {
System.setProperty("phantomjs.binary.path", "D:\\Selenium\\driver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
d=new PhantomJSDriver(caps);
}
#Test
public void guru_banking_login_excel() throws Exception {
d.get("http://www.demo.guru99.com/V4/");
d.findElement(By.name("uid")).sendKeys("TestUser");
d.findElement(By.name("password")).sendKeys("testpwd");
d.findElement(By.name("btnLogin")).click();
try{
Alert alt = d.switchTo().alert();
String actualBoxMsg = alt.getText(); // get content of the Alter Message
assertEquals(actualBoxMsg,"User or Password is not valid");
alt.accept();
}
catch (NoAlertPresentException Ex){
String hometitle=d.getTitle();
assertEquals(hometitle,"Guru99 Bank Manager HomePage");
}
d.quit
}
Error Observed :
Exception : org.openqa.selenium.UnsupportedCommandException: Invalid Command Method - {"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","
I am trying to handle popup using phantomjs as a driver
Please help on This .........
Thanks in Advance..!!!!
You have to take care of a lot of points here in your code :
While working with PhantomJS when you mention System.setProperty use the following code lines instead :
File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
DesiredCapabilities type of objects must be initiated with reference to DesiredCapabilities class only. So change to :
DesiredCapabilities caps = new DesiredCapabilities();
While using assertEquals use Assert.assertEquals as follows :
Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
//
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
As you are using TestNG, for Assert, use org.testng.Assert; instead of static org.testng.Assert.assertEquals; as an import :
import org.testng.Assert;
You need to wrap up the line d.quit() within a separate TestNG Annotated function too as follows :
#AfterMethod
public void tearDown() {
d.quit();
}
Here is your own code block which executes successfully :
package headlessBrowserTesting;
import java.io.File;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class PhantomJS_webdriver_binary
{
WebDriver d;
#BeforeMethod
public void launh_Browser() {
File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
DesiredCapabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
d=new PhantomJSDriver(caps);
}
#Test
public void guru_banking_login_excel() throws Exception {
d.get("http://www.demo.guru99.com/V4/");
d.findElement(By.name("uid")).sendKeys("TestUser");
d.findElement(By.name("password")).sendKeys("testpwd");
d.findElement(By.name("btnLogin")).click();
try{
Alert alt = d.switchTo().alert();
String actualBoxMsg = alt.getText();
Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
alt.accept();
}
catch (NoAlertPresentException Ex){
String hometitle=d.getTitle();
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
}
}
#AfterMethod
public void tearDown() {
d.quit();
}
}

How to pass called WebDriver driver from #BeforeMethod to #Test in TestNG Webdriver Java

I have this class SignIn:
package automationFramework;
import java.util.concurrent.TimeUnit;
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.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import pageObject.devSplashScreenPage;
import utility.BrowserType;
import utility.Constant;
import appModule.SignIn_Action;
public class SignIn {
public WebDriver driver;
#BeforeMethod
#Parameters("browser")
public void SetUp(String browser) {
BrowserType.Execute(driver, browser);
}
#Test
public void signIn() {
// Call Sign In function
SignIn_Action.Execute(driver, Constant.StudentUsername, Constant.StudentPassword);
}
#AfterMethod
public void Teardown() {
driver.quit();
}
}
Where I am calling this code below which chooses the specific browser by the parameter that is passed. It works perfectly fine, it picks up the right browser and executes.
package utility;
import java.util.concurrent.TimeUnit;
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.remote.DesiredCapabilities;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserType {
#Test
public static void Execute(WebDriver driver, String browser) {
// Set Browsers
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("chrome")) {
{System.setProperty("webdriver.chrome.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/chromedriver.exe");}
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("ie")) {
{System.setProperty("webdriver.ie.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/IEDriverServer.exe");}
driver = new InternetExplorerDriver();
{DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
iecapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);}
}
// Implicit Wait and Maximize browser
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Navigate to URL
driver.get(Constant.URL);
}
}
So everything executes perfectly fine in #BeforeMethod, the issue I have is the test stops because the driver doesn't pass from #BeforeMethod to #Test.
How can I get the driver that is initiated by running BrowserType.class into the #Test Sign_in.class. I guess how can i return the driver properly from browsertype and call it in Sign_in #Test.
Thanks
You should make your Execute function return the driver:
public static WebDriver Execute(String browser) {
...
return driver;
}
In your test:
public void SetUp(String browser) {
driver = BrowserType.Execute(browser);
}
Solved like this:
BrowserType.java:
package utility;
import java.util.concurrent.TimeUnit;
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.remote.DesiredCapabilities;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserType {
#Test
public static WebDriver Execute(String browser) {
// Set Browsers
WebDriver driver = null;
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("chrome")) {
{System.setProperty("webdriver.chrome.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/chromedriver.exe");}
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("ie")) {
{System.setProperty("webdriver.ie.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/IEDriverServer.exe");}
driver = new InternetExplorerDriver();
{DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
iecapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);}
}
// Implicit Wait and Maximize browser
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Navigate to URL
driver.get(Constant.URL);
return driver;
}
SignIn.java class:
package automationFramework;
import java.util.concurrent.TimeUnit;
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.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import pageObject.devSplashScreenPage;
import utility.BrowserType;
import utility.Constant;
import appModule.SignIn_Action;
public class SignIn {
public WebDriver driver;
#BeforeMethod
#Parameters("browser")
public void SetUp(String browser) {
driver = BrowserType.Execute(browser);
}
#Test
public void signIn() {
// Call Sign In function
SignIn_Action.Execute(driver, Constant.StudentUsername, Constant.StudentPassword);
}
#AfterMethod
public void Teardown() {
driver.quit();
}
}
The way your doing things can be greatly improved.
public class BrowserTest extends TestBase{
#Test(dataProvider="test1")
public static void execute(WebDriverHelper helper, String browser) {
// Set Browsers
driver.get(url);
Just pass the driver object (coming from the DataProvider). I assume your generating the driver instance within the DataProvider method since your test method is already parameterized and takes the driver.
public class TestBase {
private WebDriver driver;
...
#BeforeMethod
#Parameters("browser")
public void setUp(Object[] params) {
driver = (WebDriverHelper)params.get(1);
browserName = (String)params.get(2);
this.setTestName( params.get(0) + "-" + browserName;
driver.navigateTo(startUrl);
}
This code I show above wont compile but what I am trying to convey here is that you need to use the optional TestNG arg to the #BeforeMethod method, which is Object[] , and it gives you access to objects passed to test methods, BEFORE the test method is called, such as getting access to a "driver helper" created in the DataProvider factory, and then doing some Capabilities setup on that before the test is ran.
#DataProvider(name = "test1")
public Object[][] createData1() {
return new Object[][] {
{ "Cedric", new WebDriverHelper(), "firefox" },
{ "Anne", new WebDriverHelper(), "chrome"}
};
}
public class TestSuiteDriver {
private static WebDriver driver;
#BeforeClass
public static void setUp(){
System.setProperty("webdriver.chrome.driver", "/Users/Kimberleyross/chromedriver");
driver = new ChromeDriver();
}
public static WebDriver getDriver() {
return TestSuiteDriver.driver;
}
}

Categories

Resources