Null Pointer Exception using TestNG - selenium-webdriver

I am trying to automate and have integrated Selenium with Appium and I am using Eclipse with TestNG for execution.
Now within a project I have a package with two classes; the first class is for login into the App and the second class is for logout
First class code -
package com.gma.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoginApp {
public AppiumDriver driver;
#BeforeSuite
public void beforeMethod() throws InterruptedException {
File app = new File("C:\\Users\\mc30058\\Downloads\\gma-QA-RELEASE-QRCode-07022015_v4.5.4028.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName","Android Emulator");
capabilities.setCapability("platformVersion", "4.4");
capabilities.setCapability("app", app.getAbsolutePath());
try {
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.Button[#resource-id='com.mcdonalds.app:id/button_choose_closest']")).click();
driver.findElement(By.xpath("//android.widget.Button[#text='Continue']")).click();
driver.findElement(By.xpath("//android.widget.Button[#text='OK']")).click();
}
#Test (priority=1)
public void Login() {
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.TextView[#text='Sign In']")).click();
driver.findElement(By.xpath("//android.widget.EditText[#resource-id='com.mcdonalds.app:id/signin_edittext_email']")).sendKeys("anuj.shrivastava#us.mcd.com");
driver.findElement(By.xpath("//android.widget.EditText[#resource-id='com.mcdonalds.app:id/signin_edittext_password']")).sendKeys("Anujtest2");
currentTime();
driver.findElement(By.xpath("//android.widget.Button[#text='Sign In']")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//android.widget.Button[#text='Yeah, count me in!']")).isDisplayed();
currentTime();
driver.findElement(By.xpath("//android.widget.Button[#text='No, thanks. I like to be out of the loop']")).click();
}
private void currentTime() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println( sdf.format(cal.getTime()) );
}
}
Second class code:
package com.gma.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Logout {
public AppiumDriver driver;
#Test (priority=3)
public void LogoutApp() {
driver.findElement(By.xpath("//android.widget.TextView[#content-desc='Navigation Button']")).click();
driver.findElement(By.xpath("//android.widget.TextView[#text='Sign Out']")).click();
driver.findElement(By.xpath("//android.widget.Button[#text='Sign Out']")).click();
}
}
Contents from Testng.xml
<suite name = "GMA Automation">
<test name = "GMA Automation">
<classes>
<class name = "com.gma.test.LoginApp"/>
<class name = "com.gma.test.Logout"/>
</classes>
</test>
</suite>
I receive Null Pointer exception after execution of first class. Appium server stops saying no more commands received. Please help.

You are getting NPE b'coz you have declared one more driver reference public AppiumDriver driver; in your Logout class.
And you are using this driver reference without instantiation.

In logout class you forget to instantiate your AppiumDriver driver.
try this:
public AppiumDriver driver;
driver = new AndroidDriver();

Related

Getting an error as while reading a JSON file containing 'Usernames' and 'Passwords' using TestNG DataProviders in Selenium

Getting an error as while reading a JSON file using TestNG DataProviders in Selenium.
Error:
class com.google.gson.JsonObject cannot be cast to class org.json.simple.JSONObject (com.google.gson.JsonObject and org.json.simple.JSONObject are in unnamed module of loader &apos;app&apos;)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.google.gson.JsonParser;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataDrivenTest_json {
WebDriver driver;
#BeforeClass
void setUp() { /* to set up chromedriver */
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.MILLISECONDS);
}
#Test(dataProvider="dp") /* using dataproviders*/
void login(String data) {
String list[] = data.split(",");
driver.get("some website url");
driver.findElement(By.cssSelector("[id='Email']")).sendKeys(list[0]);//username
driver.findElement(By.cssSelector("[id='Password']")).sendKeys(list[1]);//password
driver.findElement(By.cssSelector("[type='submit']")).click();
}
#DataProvider(name="dp")
public String[] readJson() throws IOException{
#SuppressWarnings("deprecation")
JsonParser jsonparser = new JsonParser();
FileReader reader =new FileReader("C:\\Users\\dell\\eclipse-workspace-
photon\\ExcelDriven\\src\\test\\java\\Testdata.json");
#SuppressWarnings("deprecation")
Object obj = jsonparser.parse(reader); //java object
JSONObject userLoginsJsonObj = (JSONObject)obj;
JSONArray userLoginsArray =(JSONArray)userLoginsJsonObj.get("userLogins");
String array[] = new String[userLoginsArray.size()];
for(int i=0; i<userLoginsArray.size();i++) {
JSONObject users = (JSONObject)userLoginsArray.get(i);
String username = (String)users.get("username");
String password = (String)users.get("password");
array[i] = username+","+password;
}
return array;
}
#AfterClass
void tearDown() { //close driver
driver.close();
}
}
/*My MavenProject has testng included and pom.xml file has 'com.googlecode.json-simple' dependency added.Still the above error is visible in console.*/
You import class org.json.simple.JSONObject while you need to import com.google.gson.JsonObject. You cannot just cast an object to any class even if that class has the same name. The package of the class also matters.

Test annotation code is not working, just BeforeMethod is working

My code is working until #BeforeMethod and it is opening the URL, but what I'm typing after #Test is not working. It is not typing credentials on the login page, hence Test failed.
package com.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
// import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class Great {
WebDriver driver;
#BeforeMethod
public void setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\Program Files
(x86)\\Google\\Chrome\\Application\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String baseurl = "https://getfieldforce.com/dishqa";
driver.get(baseurl);
// Actions act = new Actions(driver);
}
#Test (priority=0)
public void login()
{
System.out.println("Login process starts");
driver.findElement(By.id("email")).sendKeys("123#p.com");
driver.findElement(By.id("password")).sendKeys("123456");
driver.findElement(By.id("cta")).click();
System.out.println("Login Sucessfully");
}
Removing webdriver from this line fixed the issue; WebDriver driver = new ChromeDriver();
Thanks for looking into this :-)

Error when executing testng.xml using pagefactory

I am running 2 classes using testNG.First class is running successfully but second class is failing with error:
"org.testng.TestNGException:Can't invoke public void TestScripts.NewAccountCreation.AccountCreation1(): either make it static or add a no-args constructor to your class"
If I add non argument constructor I am getting null pointer exception.
I am using Pagefactory to design my test cases.
Eclipse version:kepler
TestnG:6.9.9
Chrome version: 57.0.2987.133
Chrome driver: 2.27
Any suggestions would be greatly appreciated.
Please find the below code:
Page factory Code for Login Page:
/**
*
*/
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import Pages.LoginPage;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver = ldriver;
}
#FindBy(xpath = "//input[contains(#id,'username-inputEl')]")
public WebElement username;
#FindBy(xpath = "//input[contains(#id,'password-inputEl')]")
public WebElement password;
#FindBy(xpath = "//span[contains(#id,'submit-btnInnerEl')]")
public WebElement LoginButton;
// Methods to perform actions
public void pCLogin(String Username, String Password, WebDriver driver)
{
username.sendKeys(Username);
password.sendKeys(Password);
LoginButton.click();
}
}
Page Factory code for Account creation page:
package Pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Accounttab {
WebDriver driver;
public Accounttab(WebDriver ldriver)
{
this.driver = ldriver;
}
#FindBy(xpath = "//span[#id='TabBar:AccountTab-btnWrap']")
public WebElement accountDropDown;
#FindBy(xpath = "//span[contains(#id,'AccountTab_NewAccount-textEl')]")
public WebElement NewAccount_Button;
#FindBy(xpath = "//textarea[contains(#id,'GlobalContactNameInputSet:Name-inputEl')]")
public WebElement Companyname;
#FindBy(xpath = "//input[contains(#id,'OfficialIDDV_Input-inputEl')]")
public WebElement FEINNumber;
#FindBy(xpath = "//input[contains(#id,'GlobalAddressInputSet:City-inputEl')]")
public WebElement City;
#FindBy(xpath = "//input[contains(#id,'GlobalAddressInputSet:PostalCode-inputEl')]")
public WebElement Zipcode;
#FindBy(xpath = "//a[contains(#id,'SearchLinksInputSet:Search')]")
public WebElement AccountsearchButton;
#FindBy(xpath = "//span[#class='x-btn-inner x-btn-inner-center'][contains(#id,'NewAccountButton-btnInnerEl')]")
public WebElement CreateNewButton;
#FindBy(css = "input[id='TabBar:AccountTab:AccountTab_AccountNumberSearchItem-inputEl']")
public WebElement AccountSearch;
#FindBy(xpath = "//tbody[contains(#id,'gridview')]//tr[1]//td[2]")
public WebElement SelectAccountNumber;
public void accountMouseHover(WebDriver driver) {
WebDriverWait wait1 = new WebDriverWait(driver, 10);
wait1.until(ExpectedConditions.visibilityOf(accountDropDown));
Actions builder2 = new Actions(driver);
builder2.moveToElement(accountDropDown).moveByOffset(50, 0).click()
.build().perform();
System.out.println("Dropdown is opened");
}
public void accountSearch(String AccountName, WebDriver driver)
{
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions .visibilityOf(NewAccount_Button));
driver.manage().window().maximize();
Actions builder1 = new Actions(driver);
builder1.moveToElement(NewAccount_Button).click().build().perform();
System.out.println("Clicked on New Accounr Button");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Companyname.sendKeys(AccountName);
try {
AccountsearchButton.click();
} catch (Exception e) {
System.out
.println("Please enter one of the minimum required fields: Company Name, FEIN"
+ e);
throw (e);
}
wait.until(ExpectedConditions .visibilityOf(CreateNewButton));
CreateNewButton.click();
}
}
Test Scripts1:
LoginClass:
**
package TestScripts;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import Pages.LoginPage;
import Utility.Configreader;
import Utility.GenericMethods;
public class Login {
WebDriver driver;
LoginPage Login_page;
#BeforeSuite
public void setUp() {
Configreader cr = new Configreader(
"H://Selenium//Selenium_ODSRegression//TestData//config.properties");
driver = GenericMethods.startBrowser("Chrome", cr.getURL());
Login_page = PageFactory.initElements(driver, LoginPage.class);
}
#Test
public void PClogin() {
Login_page.pCLogin("su", "gw", driver);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
**
Test Script2:
AccountCreation class:
package TestScripts;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import Pages.AccountFileSummary;
import Pages.Accounttab;
import Pages.CreateNewAccount;
public class NewAccountCreation {
WebDriver driver;
Accounttab Account_tab1;
CreateNewAccount NewAccount1;
AccountFileSummary AFS1;
public NewAccountCreation(WebDriver ldriver)
{
this.driver = ldriver;
Account_tab1 = PageFactory.initElements(driver, Accounttab.class);
}
#Test
public void AccountCreation1() {
Account_tab1.accountMouseHover(driver);
Account_tab1.accountSearch("WebDriver_Test1", driver);
}
}
driver class:
package Utility;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import Utility.Configreader;
public class GenericMethods {
public static WebDriver driver = null;
static Configreader cr = new Configreader(
"H://Selenium//Selenium_ODSRegression//TestData//config.properties");
public static WebDriver startBrowser(String browsername, String URL)
{
if (browsername.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver",
cr.getChromeDriverPath());
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
else if (browsername.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", cr.getIEDriverPath());
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
}
driver.get(URL);
return driver;
}
}
Property file:
PCURL = http://biltipolicycenter.thehartford.com/pc/PolicyCenter.do
ChromeBrowserPath = C://Selenium//ChromeDriver 2.27//chromedriver.exe
IEBrowserPath = C://Selenium//IEDriverServer x86 2.53//IEDriverServer.exe
TestNG.XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="TestScripts.Login"/>
<class name="TestScripts.NewAccountCreation"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
NewAccountCreation is a test class because it contains test method(s) and because you declare it as a class test in the testng.xml.
So, it means TestNG must be able to create an instance of the class and that's why TestNG is complaining.
You have 2 options:
Using a factory to explain to TestNG how to create test classes
(best option IMO)
Using a static shared driver instance (Login#driver is not
yet static)
BTW, your organization of classes looks a bit dirty and you should rework them a bit.

Method created in 2nd class skipped while running 2 classes in Testng using xml

I had created 2 classes having 3 methods/test in these 2 classes. 2 methods/test in 1st class and 3rd method/test is in 2nd class. But when I run these using xml 1st class runs both the tests and tests pass where as method/test in 2nd class skips.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<suite name= "Expedia Call Tracker">
<test name="Expedia Home Smoke Testcases">
<classes>
<class name="ExpediaCallTracker.Expedia"/>
<class name="ExpediaCallTracker.ExpediaCreateSale" />
</classes>
</test>
</suite>
First Class :
package ExpediaCallTracker;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
public class Expedia {
public String e;
WebDriver expedia = new FirefoxDriver();
#Test(priority=1)
public void ExpediaLogin()
{
expedia.manage().window().maximize();
expedia.get("http://fedev.teleperformanceusa.com/Expedia/ExpediaCallTracker/Account/Login");
expedia.findElement(By.id("UserName")).sendKeys("kochhar.5");
expedia.findElement(By.id("Password")).sendKeys("Password11");
expedia.findElement(By.xpath(".//*[#id='loginForm']/form/fieldset/p/input")).click();
}
#Test(priority=2)
public void ExpediaDashSale()
{
expedia.findElement(By.linkText("Sale - HWW/EAN")).click();
}
}
Second Class :
package ExpediaCallTracker;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ExpediaCreateSale {
private static final WebDriver d = null;
public ExpediaCreateSale()
{
}
WebDriver expedia = d;
#Test
public void ExpediaCreate(WebDriver d)
{
expedia.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Select LineOfBusiness = new Select(expedia.findElement(By.id("lineOfBusiness")));
LineOfBusiness.selectByIndex(1);
expedia.findElement(By.id("sourceCode")).sendKeys("abcdefgh");
WebElement Upsell = expedia.findElement(By.xpath("html/body/div[1]/section[2]/form/fieldset/div[6]/input[1]"));
Upsell.click();
WebElement SaleCall =expedia.findElement(By.xpath("html/body/div[1]/section[2]/form/fieldset/div[8]/input[1]"));
SaleCall.click();
expedia.findElement(By.id("checkInDate")).sendKeys("09/14/2016");
Select numberOfNights = new Select(expedia.findElement(By.id("numberOfNights")));
numberOfNights.selectByIndex(1);
WebElement PaymentMethod = expedia.findElement(By.xpath("html/body/div[1]/section[2]/form/fieldset/div[9]/div[6]/input[1]"));
PaymentMethod.click();
Select currency = new Select(expedia.findElement(By.id("currency")));
currency.selectByIndex(70);
expedia.findElement(By.id("grossBooking")).sendKeys("123456");
expedia.findElement(By.id("itineraryNumber")).sendKeys("123456789");
expedia.findElement(By.id("remark")).sendKeys("Itinery number saved.");
expedia.findElement(By.xpath(".//*[#id='body']/section[2] /form/fieldset/p/input[1]")).click();
}
}
Can anyone suggest what should I try to do ?
Test method ExpediaCreate that takes a parameter WebDriver is causing this issue. To fix this, follow the same approach as Expedia class and it should work.
Moreover, you have not initialized webdriver instance variable d in the ExpediaCreateSale class. Once you initialize the driver instance, it is available in your test methods so you dont have to pass as a paramater.
You dont have to have this line of code also.
private static final WebDriver d = null;
Hope this helps.

unable to launch internet explorer in TestNG

I am new in TestNG. This is my code which I tried in eclipse, but there is a problem occurring in launching internet explorer.
The error it is giving is
org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)
This is the complete code....
package com.tcs.medmantra;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Registration {
WebDriver driver;
WebElement element;
WebElement element2;
WebDriverWait waiter;
#Test(priority = 1)
public void register_With_Cash() throws RowsExceededException, BiffException, WriteException, IOException
{
driver=new InternetExplorerDriver();
driver.get("https://172.25.155.250/loginpage.aspx");
//((JavascriptExecutor)driver).executeScript("window.resizeTo(1366, 768);");
waiter = new WebDriverWait (driver, 40);
driver.findElement(By.id("txtuname")).sendKeys("122337");
driver.findElement(By.name("txtpwd")).sendKeys("Tcs!#345");
driver.findElement(By.id("btnsubmit")).click();
sleep(25000);
//print URL
String url = driver.getCurrentUrl();
System.out.println(url);
}
#BeforeTest
public void beforeTest() {
File file = new File("D:\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
}
#AfterTest
public void afterTest() {
driver.quit();
}
}
As the error says you need set the protected mode same for all zones, either enabled or disabled. Preferred would be enabled. See here
Change your code to include the path for InternetExplorerDriver.
File file = new File("C:/Selenium/iexploredriver.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();

Resources