I have created three files: one is index file, other is configuration file and last the last one is the property file. While executing the code I'm getting NULLPointerException.
I am not able to solve this issue. Please help me to rectify this code.
index.java:
package main;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import config.Configuration;
public class Index
{
WebDriver driver;
#Test(priority = 1)
public void handling_multiple_windows() throws Exception
{
Configuration obj = new Configuration();
System.setProperty("webdriver.chrome.driver", obj.path());
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(obj.handling_window_url());
}
}
Configuration.java:
package config;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
public class Configuration
{
Properties pro;
WebDriver driver;
public Configuration() throws Exception
{
File f = new File("./Config/config.property");
FileInputStream fis = new FileInputStream(f);
Properties pro = new Properties();
pro.load(fis);
}
public String path()
{
String url = pro.getProperty("ChromeDriverPath");
return url;
}
public String handling_window_url()
{
return pro.getProperty("URL");
}
}
config.property:
ChromeDriverPath = G:\\Selenium Webdriver\\chromedriver\\chromedriver.exe
URL = https://www.naukri.com
The reason you get a NullPointerException is because in the Configuration.java Class you have declared Properties pro; globally but again within the Configuration() constructor you have again initiated another instance of Properties as Properties pro = new Properties();. Hence the NullPointerException.
Change the line:
Properties pro = new Properties();
to:
pro = new Properties();
Your code will work fine.
Remove Properties from Properties pro = new Properties(); from this code and make it:
pro = new Properties();
You already declare it above, so need to declare it again
Related
I m trying to run a small test program with Extent Reports but getting Null Pointer Exception. If i am running this code, without using Extent Report functionality it's working fine. Kindly help.
Below is my code-
package selenium.ExtentReports;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ExtentReportDemo {
ExtentReports extent;
WebDriver driver;
#BeforeTest
public void config() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
String path = System.getProperty("user.dir") + "//Reports//index.html";
ExtentSparkReporter reporter = new ExtentSparkReporter(path);
reporter.config().setReportName("Web Automation Results");
reporter.config().setDocumentTitle("Test Results");
ExtentReports extent = new ExtentReports();
extent.attachReporter(reporter);
extent.setSystemInfo("Tester", "Gaurav Singh");
}
#Test
public void initialDemo() {
extent.createTest("Initial Demo");
driver.get("https://rahulshettyacademy.com");
System.out.println(driver.getTitle());
extent.flush();
}
}
Error which i am getting
FAILED: initialDemo
java.lang.NullPointerException
at selenium.ExtentReports.ExtentReportDemo.initialDemo(ExtentReportDemo.java:38)
I have just instantiate the extent variable outside the clas. And it's working for me now.
ExtentReports extent = new ExtentReports();
ExtentReports extent = new ExtentReports();
Don't initialize in #BeforeTest methods once you declared it Publicly. Instead Use :
extent = new ExtentReports();
I'm using the Boni Garcia 'webdrivermanager'.
https://github.com/bonigarcia/webdrivermanager/blob/master/README.md
My issue:
I'm not able to 'get' my initialized driver properties from 'BaseSwag' to 'home.page' in order to launch Chrome and go to the desired URL. Here is my set up as follows. What can I do to fix this?
src/main/java/swaglogin/BaseSwag
package swaggerLogin;
import io.github.bonigarcia.wdm.WebDriverManager;
import io.github.bonigarcia.wdm.managers.ChromeDriverManager;
import io.github.bonigarcia.wdm.managers.FirefoxDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class BaseSwag {
public WebDriver driver;
public Properties prop;
public WebDriverManager initializeDriver() throws IOException {
// Create global property file
prop = new Properties();
FileInputStream fis = new FileInputStream(
"//Users/rad/WebTest/src/main/resources/data.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
System.out.println(browserName);
if (browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
return driver;
}
}
resources/data.properties
url = http://qaclickacademy.com/
apiKey = 1234563333random
browser = chrome
test/java/home.page
package home.page;
import java.io.IOException;
import org.testng.annotations.BeforeTest;
import swaggerLogin.BaseSwag;
public class SwaggerLoginDev extends BaseSwag {
#BeforeTest
public void initialize() throws IOException {
driver = initializeDriver();
driver.get(prop.getProperty("url"));
}
}
Stack Trace
Error:(32, 12) java: cannot find symbol
symbol: method driver()
location: class resources.Base
Your driver variable should be an instance of WebDriver, not WebDriverManager.
You can consider WebDriverManager as utility class, that only manage (download, setup, etc...) your drivers for different browsers. Once you call .setup() method for the desired type of browser, you can create an instance of it:
public class BaseSwag {
public WebDriver driver;
public Properties prop;
public WebDriver initializeDriver() throws IOException {
// Create global property file
prop = new Properties();
FileInputStream fis = new FileInputStream(
"//Users/rad/WebTest/src/main/resources/data.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
System.out.println(browserName);
if (browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
return driver;
}
}
Now, you should be able to call .get(...) method on your driver.
Now i modified the code but still i am getting Null Pointer Exception
Below is my modified code
enter code here
package lib;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeMethod;
//#SuppressWarnings("unused")
public class Login {
WebDriver driver;
#BeforeMethod
void Initalisation()
{
System.setProperty("webdriver.ie.driver", "C:\\Eclipse\\IEDriverServer.exe");
DesiredCapabilities capability=new DesiredCapabilities();
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
InternetExplorerDriver driver=new InternetExplorerDriver(capability);
driver.get("http://segotn11540.rds.volvo.com/vss_connect_testr1/Login/Login.aspx");
}
public Login(String UserName,String BrandName)
{
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
private void CheckForCancel() {
if(!driver.findElements(By.id("Cancel")).isEmpty())
{
driver.findElement(By.id("Cancel")).click();
}
}
}
Now I will create the main Java file
Blockquote
This will initalise the login with the parameters supplied
Import Login library
public class MessageBoard {
public static void main(String[] args)
{
Login login=new Login("TYP40FI","Volvo");
}
}
What is wrong in above code
Try to initialize the driver variable as
WebDriver driver = new WebDriver();
public Login(String UserName,String BrandName)
{
//Add this line in your code as you are trying in IE
driver = new InternetExplorerDriver();
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
Debug and check: Is Initalisation() being called in the beginning?
Usually #BeforeMethod is called before test starts, so where is your #Test function. (syntax could be wrong)
If you don't really care about #Test property, that means your Main function needs to call Initalisation() before calling Login(...), otherwise the driver is not set yet (aka Null)
I am getting the null pointer error in the below code. If you run the code it will execute all the code just before the code where i mentioned 'captureScreenshot()' function after this its not executing.
package rough;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestEmailAndScreenshot1 {
public static WebDriver dr;
public static String mailscreenshotpath;
public static void captureScreenshot(){
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int sec = cal.get(Calendar.SECOND);
int min = cal.get(Calendar.MINUTE);
int date = cal.get(Calendar.DATE);
int day = cal.get(Calendar.HOUR_OF_DAY);
File scrFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
try {
mailscreenshotpath = System.getProperty("user.dir")+"\\screenshot\\"+year+"_"+date+"_"+(month+1)+"_"+day+"_"+min+"_" +sec+".jpeg";
FileUtils.copyFile(scrFile, new File(mailscreenshotpath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
WebDriver dr=new FirefoxDriver();
dr.manage().window().maximize();
dr.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);
dr.get("http://gmail.com");
dr.findElement(By.id("Email")).sendKeys("vijenderchhoker92");
captureScreenshot();
System.out.println(" Screenshot taken successfully....");
}
}
When you do
WebDriver dr = new FirefoxDriver();
In main you hide the public static WebDriver dr; variable, so in captureScreenshot() method it's still null and you get the error trying to use it. Change to
public static void main(String[] args) {
dr = new FirefoxDriver();
dr.manage().window().maximize();
//...
}
can someone help me with using property file for a sample login application? this helps in achieving me for another big automation.
I have given objects in objects.propreties
in main java class how shall i proceed with?
package valuescompare;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class practice {
public static FileInputStream fis;
public static String propertyfilepath="E:\\Ashik\\wkspSelenium\\valuescompare\\src\\valuescompare\\object.properties";
public static String getProperty(String key) throws IOException, FileNotFoundException{
fis=new FileInputStream(propertyfilepath);
Properties prop=new Properties();
prop.load(fis);
return prop.getProperty(key);
}
static WebDriver driver=new FirefoxDriver();
public static void openBrowser() throws FileNotFoundException, IOException {
//public WebDriver driver;
driver.get(getProperty("url"));
//maximizes the window
driver.manage().window().maximize();
Wait(1000);
}
public static void login() throws FileNotFoundException, IOException{
driver.findElement(By.xpath(getProperty("uidxpath"))).sendKeys(getProperty("uid"));
driver.findElement(By.xpath(getProperty("pwdxpath"))).sendKeys(getProperty("pwd"));
driver.findElement(By.xpath(getProperty("submit"))).click();
Wait(5000);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
/*practice prac=new practice();
prac.openBrowser();
prac.login(); */
openBrowser();
login();
}
public static void Wait(int time){
try {
Thread.sleep(time);
} catch (Exception e) {
// TODO: handle exception
}
}
}
Say you create a 'config.properties' named file somewhat like this :
userName=admin
password=admin
and say you are using Java as your programming language, then you have to use it in this manner:
Properties properties = new Properties();
properties.load(new FileInputStream("Config.properties"));
String uName = properties.getProperty("userName");
String pwd = properties.getProperty("password");
Now you have got the values fetched from properties file, use it wherever required.
For more info you may refer this link: http://www.mkyong.com/java/java-properties-file-examples/