How to fix this NullPointerException with selenium and java? - selenium-webdriver

I am trying to run my Automation script, I am launching URL but I am getting java.lang.NullPointerException
package lib.Page;
public class LoginPage {
public static final String URL = null;
public static final String TITLE = null;
public static final String EMAIL = null;
public static final String PASSWORD = null;
WebDriver driver;
WebDriverWait wait;
public LoginPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public LoginPage lauchUrl(String url){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.get(LoginPageData.URL);
return this;

Check your stack trace for the exact row where you are getting this error. My guess would be this:
driver.get(LoginPageData.URL);
as I don't see you initializing LoginPageData anywhere.

Related

Can't read properties file on device farm :- src/test/resources/Properties/Android_Or.properties -error

Please let me know how to read properties file in device farm, since following code is not working. I have looked into various solutions but still device farm is not able to recognize properties file, although this code works fine locally
public abstract class AndroidCapabilities {
// protected static AppiumDriver<MobileElement> driver;
public static ExtentHtmlReporter reporter;
public static ExtentReports extent;
public static ExtentTest logger1;
// #Parameters("browser")
// #BeforeSuite
// public void setUp() throws MalformedURLException {
public static AndroidDriver<MobileElement> driver;
public abstract String getName();
#BeforeTest
public abstract void setUpPage();
#BeforeSuite
public void setUpAppium() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
// capabilities.setCapability("device", "Android");
// capabilities.setCapability("platformName", "Android");
// capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");
final String URL_STRING = "http://127.0.0.1:4723/wd/hub";
URL url = new URL(URL_STRING);
// Use a empty DesiredCapabilities object
driver = new AndroidDriver<MobileElement>(url, capabilities);
// Use a higher value if your mobile elements take time to show up
driver.manage().timeouts().implicitlyWait(35, TimeUnit.SECONDS);
}
public static Properties properties;
static {
properties = new Properties();
FileInputStream fis;
InputStream input;
try {
// fis = new FileInputStream(System.getProperty("user.dir") +
// "//src//test//resources//Properties//Android_OR.properties");
fis = (FileInputStream) Thread.currentThread().getContextClassLoader()
.getResourceAsStream("//Properties//Android_OR.properties");
System.out.println(properties.getProperty("url"));
properties.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
}
#BeforeTest
public void createReport() {
reporter = new ExtentHtmlReporter("./extent.html");
extent = new ExtentReports();
extent.attachReporter(reporter);
}
#AfterTest
public void flush() throws IOException {
extent.flush();
// reporter.setAppendExisting(true);
}
#AfterSuite
public void closeApplication() {
driver.quit();
Reporter.log("===Session End===", true);
}
}
Faced the same issue. Instead of using System.getProperty, try this:
// pass fileName as "Android_OR.properties"
public Properties loadProperty(String fileName) {
Properties prop = new Properties();
try (InputStream input = Base.class.getClassLoader().getResourceAsStream(filePath)) {
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return prop;
}
// load a properties file from class path, inside static method
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
return prop;
}

Page Objects erro (java.lang.NullPointerException)

I did a basic project to training about Page Objects using selenium WebDriver with java and Junit. So, I make a page object class and Junit class too. I Make a call of method and pass the parameters to method but, the eclipse show a message that say: java.lang.NullPointerException
public class LogarBkoMaisPage {
static WebDriver driver;
By campoNome = By.id("matricula_I");
By campoSenha = By.id("senha_I");
By btnLogin = By.id("bt_entrar");
public LogarBkoMaisPage(WebDriver driver) {
this.driver = driver;
}
public void logar(String usuario, String senha) {
driver.findElement(campoNome).sendKeys(usuario);
driver.findElement(campoSenha).sendKeys(senha);
driver.findElement(btnLogin).click();
}
}
public class LogarBkoMaisTest {
static WebDriver driver;
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}
#Test
public void logarAplicacao() {
try {
LogarBkoMaisPage login = new LogarBkoMaisPage(driver);
login.logar("844502","Bcc201707");
}catch(Exception e) {
System.out.println("Mensagem de erro: " +e);
}
}
#After
public void tearDown() throws Exception {
}
}
public class SelecionarNavegador {
static WebDriver driver;
public static WebDriver iniciarNavegador(String nomeNavegador, String url) {
if(nomeNavegador.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.gecko.driver", "E:\\workspace_BCC_QA_BKOMAIS\\"
+ "FireFoxGeckodriver64\\geckodriver.exe");
driver = new FirefoxDriver();
}
else if(nomeNavegador.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}else if(nomeNavegador.equalsIgnoreCase("IE")) {
System.setProperty("webdriver.ie.driver", "E:\\workspace_BCC_QA_BKOMAIS"
+ "\\IE Plugin\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
Exception:
You are getting a null pointer exception because iniciarNavegador method inside SelecionarNavegador class is the one which initializes the driver and it returns the driver which has to be assigned to a vairable. You need to do this in your setUp()method
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
driver=nav.iniciarNavegador("ie","http://10.5.9.45/BkoMais_Selenium/");
}

Cannt able to find Element in selenium

My coding not find element. Pls anyone help me to come out of my mistake.
Testcase
#Test
public void main() throws Exception {
Thread.sleep(5000);
System.out.println("Before sign in action execution");
SignIn_Action.Execute(iTestCaseRow);
}
SignIn_Action
public class SignIn_Action{
public static void Execute(int iTestCaseRow) throws Exception{
// Fetch user name from Excel
String sUserName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_UserName);
System.out.println("User Name read from --> "+ sUserName);
// Fetch password from Excel
String sPassword = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Password);
System.out.println("Password read from excel --> "+ sPassword);
LoginPageObjects.txtbx_username().sendKeys(sUserName);
LoginPageObjects.txtbx_password().sendKeys(sPassword);
LoginPageObjects.btn_login().click();
}
LoginPageObject class
public class LoginPageObjects extends BaseClass {
private static WebElement element = null;
public LoginPageObjects(WebDriver driver){
super(driver);
}
public static WebElement txtbx_username(){
try {
WebElement element = null;
System.out.println("Inside txtbx_username method");
element = driver.findElement(By.name("first_name"));
System.out.println("Fetched element name is : "+element);
Log.info("Username text box found");
}catch (Exception e){
Log.error("UserName text box is not found on the Login Page");
throw(e);
}
return element;
}
}
}
BaseClass
public class BaseClass {
public static WebDriver driver;
public static boolean bResult;
public BaseClass(WebDriver driver){
BaseClass.driver = driver;
BaseClass.bResult = true;
}
}
My problem is in the below code
element = driver.findElement(By.name("first_name"));
This code is not find element and it shows below error message
java.lang.NullPointerException
at pageObjects.LoginPageObjects.txtbx_username(LoginPageObjects.java:27)

Null pointer exception for Extent Report

It wouldbe silly question but would be great help it you can help me out.
I tried implementing extent report for multple test cases, but report are not getting generated .
Code:
public class SampleTc1
{
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
static void testcase1()
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.co.in");
logger.log(LogStatus.PASS, "This step is passed");
driver.close();
}
}
public class SampleTc2
{
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
static void testcase2()
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.co.in");
logger.log(LogStatus.PASS, "This step is passed");
driver.close();
}
}
Main Class:
public class Maindriver {
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
report=new ExtentReports("./Report/ExtentReport/ExecutionResult.html", true);
logger=report.startTest("TC1", "Testc Case1");
SampleTc1.testcase1();
report.endTest(logger);
logger=report.startTest("TC2", "Testc Case2");
SampleTc2.testcase2();
report.endTest(logger);
report.flush();
}
}
After running no reports are getting generated and it is showing null ponter exception:
Exception in thread "main" java.lang.NullPointerException
at SmokeTest.SampleTc1.testcase1(SampleTc1.java:24)
at SmokeTest.Maindriver.main(Maindriver.java:22)
Above exception I am getting.
Thanks in advance.
If you are using testng for running selenium suite, you can implement extent reports as a listener.
Like,
public class ExtentReporterNG implements IReporter
{
public ExtentReports extent;
private void buildTestNodes(IResultMap testMap, LogStatus status)
{
ExtentTest test;
if (testMap.size() > 0)
{
for (ITestResult result : testMap.getAllResults())
{
//test = extent.startTest(result.getInstance().getClass().getSimpleName(),result.getMethod().getMethodName());
test = extent.startTest(result.getMethod().getMethodName().toUpperCase(),result.getInstance().getClass().getSimpleName().toUpperCase());
test.assignCategory(result.getInstance().getClass().getSimpleName().toUpperCase());
test.setStartedTime(getTime(result.getStartMillis()));
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
String message = "Test " + status.toString().toLowerCase() + "ed";
if (result.getThrowable() != null)
message = result.getThrowable().getMessage();
test.setEndedTime(getTime(result.getEndMillis()));
test.log(status, message);
extent.endTest(test);
}
}
}
private Date getTime(long millis)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
#Override
public void generateReport(List<XmlSuite> xmlsuite, List<ISuite> suites,String file)
{
final String filePath=GlobalSettings.getProperty(GlobalSettings.EXTENTFILE);
extent = new ExtentReports(filePath, true,DisplayOrder.NEWEST_FIRST,NetworkMode.OFFLINE );
extent.loadConfig(new File("./config/extentConfig.xml"));
for (ISuite suite : suites)
{
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values())
{
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
buildTestNodes(context.getFailedConfigurations(),LogStatus.FAIL);
buildTestNodes(context.getSkippedConfigurations(),LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}}
It is not well organized, hard to say what/where is the problem ...
You can check here a selenium webdriver testng tutorial I used it when I started and it is a good starting point!
You have to change your ExtentReports as static in the base class. I got this idea from Mukesh Otwani, Selenium automation trainer for Learn-Automation.
I created separate class for extent report, hence avoided NULL pointer exception

Selenium POM java.lang.NullPointerException

I am getting "java.lang.NullPointerException" when I am trying to execute my test case based on POM.
The class BrowserFactory lets me choose a browser, the class Flipkart_Login based on POM stores all the element of that particular page and has a method for Valid_Login()
and finally Test_Flipkart_Login class - calls the Valid_Login() method for executon but when I try to execute this class, I get java.lang.NullPointerException.
Kindly advise!
FAILED: Flipkart_Login_Test
java.lang.NullPointerException
at DataProviders.ConfigDataProvider.getURL(ConfigDataProvider.java:31)
at TestCases.Test_Flipkart_Login.Flipkart_Login_Test(Test_Flipkart_Login.java:19)
public class ConfigDataProvider
{
static Properties pro;
public ConfigDataProvider()
{
File src = new File("C:\\Data\\Bimlesh\\Flipkart_HybridFramework\\Flipkart.Hybrid.FrameworkComplete\\Configuration\\Config.Properties");
try
{
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
} catch (Exception e)
{
System.out.println("The Config exception is :"+e.getMessage());
}
}
public static String getURL()
{
String URL = pro.getProperty("URL");
return URL;
}
public static String ChromePath()
{
String Chrome = pro.getProperty("Chromepath");
return Chrome;
}
public static String IEPath()
{
String IE = pro.getProperty("IEpath");
return IE;
}
}
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver getBrowser(String BrowserName)
{
if(BrowserName.equalsIgnoreCase("Firefox"))
{
driver = new FirefoxDriver();
}
else if(BrowserName.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver", ConfigDataProvider.ChromePath());
driver = new ChromeDriver();
}
else if(BrowserName.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", ConfigDataProvider.IEPath());
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
return driver;
}
public void ShutDown(WebDriver driver)
{
driver.quit();
}
}
public class Flipkart_Login
{
WebDriver driver;
public Flipkart_Login(WebDriver driver)
{
this.driver=driver;
}
#FindBy(xpath="//a[text()='Log In']") WebElement Login_Click;
#FindBy(xpath="//input[#class='_2zrpKA' and #type='text']") WebElement Enter_Email;
#FindBy(xpath="//input[#class='_2zrpKA _3v41xv' and #type='password']") WebElement Enter_Pass;
#FindBy(xpath="//button[#type='submit' and #class='_3zLR9i _1LctnI _36SmAs']") WebElement Login_Button;
public void Valid_Login()
{
Login_Click.click();
Enter_Email.sendKeys("xxx#gmail.com");
Enter_Pass.sendKeys("xxx");
Login_Button.click();
}
}
public class Test_Flipkart_Login
{
WebDriver driver;
#Test
public void Flipkart_Login_Test()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(ConfigDataProvider.getURL());
Flipkart_Login page1 = PageFactory.initElements(driver, Flipkart_Login.class);
page1.Valid_Login();
}
}
You have initialized Properties pro in the constructor of the COnfigDataProider but you are using a static call to getURL method from your test class. Thus pro will be null and not initialized. Remove static call and use the constructor or make pro to static and initialize in static block.

Resources