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)
Related
I'm using the Page Object Model I just started i created 2 packages one is com.automation.pages another one is com.automation.testcases.
In both packages I created a class for the login page it works fine I'm sharing the code below.
package com.automation.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver=ldriver;
}
#FindBy (xpath="//input[#name='email'] ") WebElement email;
#FindBy (xpath="//input[#name='password']") WebElement password;
#FindBy (xpath="//body/div[2]/div[2]/div[2]/form[1]/div[3]/div[2]/button[1]") WebElement loginbutton;
public void logintoLabaiik(String email1, String password1 )
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
email.sendKeys(email1);
password.sendKeys(password1);
loginbutton.click();
}
}
The problem I'm facing when I working on the new page is when I created a driver and when using ldriver it throws me an error also when I replace the "l" still it throws me the error. kindly solve my problem.
package com.automation.pages;
import org.openqa.selenium.WebDriver;
public class TaxSetup {
WebDriver driver;
public TaxSetup(WebDriver driver)
{
this.driver.ldriver;
}
}
It looks you have an issue in TaxSetup constructor.
This should work.
public TaxSetup(WebDriver driver){
this.driver=driver;
}
Take a look at how to create 2 Page Object classes and use them in tests:
LoginPage
public class LoginPage {
final WebDriver driver;
public LoginPage(WebDriver driver){
this.driver=driver;
}
// page implementation
}
TaxSetup
public class TaxSetup {
final WebDriver driver;
public TaxSetup(WebDriver driver){
this.driver=driver;
}
// page implementation
}
How to use in test
public class SomeTest {
WebDriver driver;
LoginPage loginPage;
TaxSetup taxSetupPage;
#BeforeClass
public void initDriverAndPages() {
driver = ... // e.g. new ChromeDriver()
loginPage = PageFactory.initElements(driver, LoginPage.class);
taxSetupPage = PageFactory.initElements(driver, TaxSetup.class);
}
#Test
public void someTest() {
// implement test using loginPage, taxSetupPage as you like
}
#AfterClass
public void quitDriver() {
driver.quit();
}
}
Please correct the below line in your TaxSetUp constructor.
this.driver.ldriver;
This is suppose to be
this.driver = driver;
And yes, you have to pass the WebDriver instance for all the page classes that you create as part of your application otherwise they will assign default value to the driver which is null.
I am trying to create a framework where I can run my test cases(test tags in xml file) in parallel in different browsers. I have tried using all combinations of testNG annotations but after reading a blog came to know that this can only be achieved by using testNg listners. I am using ThreadLocal to keep my driver thread-safe. I am getting null pointer exception when trying to access Webdriver in my test cases class in line LocalDriverManager.getDriver().get(url);
This is LocalBrowserFactory.Class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import DataProvider.ConfigDataProvider;
public class LocalDriverFactory {
public static WebDriver createInstance(String browserName) {
WebDriver driver = null;
ConfigDataProvider config=new ConfigDataProvider();
if (browserName.toLowerCase().contains("firefox")) {
System.setProperty("webdriver.gecko.driver", config.getgeckoPath());
driver = new FirefoxDriver();
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
}
if (browserName.toLowerCase().contains("chrome")) {
System.setProperty("webdriver.chrome.driver", config.getchromePath());
driver = new ChromeDriver();
}
driver.manage().window().maximize();
return driver;
}
}
This is my LocalDriverManager.class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
public static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
This is my ConfigPropertyReader.class
package DataProvider;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigDataProvider {
static Properties p;
public ConfigDataProvider()
{
File f =new File("C:/Eclipse/parallelframework/configuration/config.properties");
try {
FileInputStream fis = new FileInputStream(f);
p=new Properties();
p.load(fis);
}
catch (Exception e)
{
System.out.println("Custom Exception- cannot load properties file"+e.getMessage());
}
}
public String getvalue(String key)
{
return p.getProperty(key);
}
public String getUrl()
{
return p.getProperty("url");
}
public String getchromePath()
{
return p.getProperty("chromepath");
}
public String getgeckoPath()
{
return p.getProperty("firefoxpath");
}
public String getIEPath()
{
return System.getProperty("User.dir")+p.getProperty("IEPath");
}
}
This is WebDriverListner.class
package Listners;
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import BrowserFactory.LocalDriverFactory;
import BrowserFactory.LocalDriverManager;
public class WebDriverListner implements IInvokedMethodListener {
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
System.out.println(browserName);
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
System.out.println("Driver Set");
}
}
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
This is my sample testcase.class
package tests;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import BrowserFactory.LocalDriverManager;
public class sampleTest {
#Test
public void testMethod1() {
invokeBrowser("http://www.ndtv.com");
}
#Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
LocalDriverManager.getDriver().get(url);
}
}
Your Listener code is messed up. You basically have the beforeInvocation and afterInvocation in the wrong order.
Here's how it should have looked like
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
#Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
You basically would setup the webdriver into the thread local variable (push the webdriver instance into the thread local variable's context) from within the beforeInvocation and then within your afterInvocation method, you would pop it out and clean up the webdriver instance (by calling quit() ). In your case, your code is doing the opposite.
For more details you can refer to my blog post here.
I've written my code in Java using Selenium. When I run the code, it's throwing a NullPointerException. Check the exception below
Exception in thread "main" java.lang.NullPointerException
at AdminInterface.loginApplication(AdminInterface.java:17)
at AdminInterface.main(AdminInterface.java:29)
My code is as follows:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AdminInterface {
public WebDriver driver;
public void launchApplication() throws Exception
{
System.setProperty("webdriver.ie.driver", "C:\\Users\\rprem\\Downloads\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.gcrit.com/build3/admin/");
}
public void loginApplication(String Username, String Password)
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tbd1")).click();
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args)
{
AdminInterface obj = new AdminInterface();
obj.loginApplication("admin", "admin#123");
}
}
You are seeing a NullPointerException because from main() you are trying to access the loginApplication() method right in the begining, which requires an active instance of the WebDriver i.e. the driver to findElement(By.name("username")); & findElement(By.name("password")); and perform sendKeys() method on the HTML DOM.
The solution would be to first access the launchApplication() method so you have an active instance of driver and IE Browser. Next you can access loginApplication() method.
Here is your working code block:
package demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Q45474353_NPE
{
public WebDriver driver;
public void launchApplication()
{
System.setProperty("webdriver.ie.driver", "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.gcrit.com/build3/admin/");
}
public void loginApplication(String Username, String Password)
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tbd1")).click();
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args)
{
Q45474353_NPE obj = new Q45474353_NPE();
obj.launchApplication();
obj.loginApplication("admin", "admin#123");
obj.closeBrowser();
}
}
I have a feature file where i have 2 scenarios
Feature: Login to Online Store
Scenario: Login successful with valid credentials
Given User is on Home Page
When User navigates to Login Page
And User provides username and password
Then Message displays Login successfully
Scenario: User logout successfully
When User logouts from application
Then Message displays Logout successfully
Every time I run the RunFeatures.java file, after the first Scenario, driver to open new Browser to execute next Scenario. Can we use the same browser to execute the 2nd scenario?
Below is my code:
RunFeatures.java
package cucumbertest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="src/test/java/features/"
,glue={"steps"}
,dryRun=false
,monochrome=false)
public class RunFeatures
{
}
ClientSteps.java:
package steps;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.*;
import pages.HomePage;
import pages.LoginPage;
public class ClientSteps
{
WebDriver driver=new FirefoxDriver();
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
new HomePage(driver).user_is_on_Home_Page();
}
#When("^User navigates to Login Page$")
public void user_navigates_to_Login_Page() throws Throwable {
new HomePage(driver).user_navigates_to_Login_Page();
}
#When("^User provides username and password$")
public void user_provides_username_and_password() throws Throwable {
new LoginPage(driver).user_provides_username_and_password();
}
#Then("^Message displays Login successfully$")
public void message_displays_Login_successfully() throws Throwable {
new LoginPage(driver).message_displays_Login_successfully();
}
#When("^User logouts from application$")
public void user_logouts_from_application() throws Throwable {
new LoginPage(driver).user_Logout_from_the_Application();
}
#Then("^Message displays Logout successfully$")
public void message_displays_Logout_successfully() throws Throwable {
new LoginPage(driver).message_displayed_Logout_successfully();
}
}
Homepage.java file
package pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class HomePage
{
WebDriver driver;
public HomePage(WebDriver driver)
{
this.driver=driver;
}
public void user_is_on_Home_Page() throws Throwable {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.store.demoqa.com");
}
public void user_navigates_to_Login_Page() throws Throwable {
driver.findElement(By.xpath(".//*[#id='account']/a")).click();
}
}
LoginPage.java
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginPage
{
WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
public void user_provides_username_and_password() throws Throwable {
// This is to get the first data of the set (First Row + First Column)
driver.findElement(By.id("log")).sendKeys("tri.nguyen");
// This is to get the first data of the set (First Row + Second Column)
driver.findElement(By.id("pwd")).sendKeys("Test#123");
driver.findElement(By.id("login")).click();
}
public void message_displays_Login_successfully() throws Throwable {
System.out.println("Login Successfully");
}
public void user_Logout_from_the_Application() throws Throwable {
driver.findElement (By.xpath(".//*[#id='account_logout']/a")).click();
}
public void message_displayed_Logout_successfully() throws Throwable {
System.out.println("Logout Successfully");
driver.quit();
}
}
As a good practice, test cases should be atomic. Automation Test case shouldn't be dependent on another test case for browser instance, data etc.
You rather should close all browser windows after every test case and open browser again as a new instance for a next test case.
Use #Before and #After in your stefdef file to achieve this.
as I am not able to add as a comment due to word restrictions, writing it here as a answer again! This is in continuation to my previous post. You can try this. Replace #Given by following
WebDriver driver;
#Before
public void setUp(){
driver=new FirefoxDriver();
}
#After
public void cleanUp(){
driver.quit();
}
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
new HomePage(driver).user_is_on_Home_Page();
}
make sure you import following files only and not junit*
import cucumber.api.java.After;
import cucumber.api.java.Before;
I tried to modify my codes following your instruction but its getting NullPointer exception:
WebDriver driver;
#Before
public void setUp(){
WebDriver driver=new FirefoxDriver();
}
#After
public void cleanUp(){
driver.quit();
}
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
new HomePage(driver).user_is_on_Home_Page();
}
Exception:
java.lang.NullPointerException
at pages.HomePage.user_is_on_Home_Page(HomePage.java:24)
at steps.ClientSteps.user_is_on_Home_Page(ClientSteps.java:30)
at ✽.Given User is on Home Page(Login.feature:4)
java.lang.NullPointerException
at steps.ClientSteps.cleanUp(ClientSteps.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
I'm again not able to add it as a comment :(.
You have declared and instantiated driver variable inside setup method which makes it local to setup method only. Declare driver at class level.
WebDriver driver;
#Before
public void setUp(){
driver=new FirefoxDriver();
}
This should work. Let me know in case you face any issues, we may get on hangout to resolve it.
Below is my simple testcase program:
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public WebDriver driver;
public static void main(String[] args) {
myclass dr= new myclass();
dr.start();
dr.select();
}
public void start(){
WebDriver driver= new FirefoxDriver();
driver.get("https://www.google.co.in/");
}
public void select(){
driver.findElement(By.linkText("Gmail")).click();
}
}
but it throws the below error everytime i run it:
Exception in thread "main" java.lang.NullPointerException
at mypackage.myclass.select(myclass.java:26)
at mypackage.myclass.main(myclass.java:15)
The browser gets launched and the google home page is also displayed but the next action of selecting the gmail link doesnt happen and the error appears.
**tried this on different browsers(i.e. chrome) but error still persists
please help me with this i am new to selenium..
Look up "variable scope" in Java.
This line:
driver.findElement(By.linkText("Gmail")).click();
is referencing:
public WebDriver driver;
which is never set as anything.
This should fix that error:
public void start(){
driver= new FirefoxDriver();
driver.get("https://www.google.co.in/");
}
Also, class names should start with a capital letter.
just remove the "WebDriver" instance from the start() method which is already declared above ,if you use it then "WebDriver" declare globally is not in current scope of method start()
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public WebDriver driver;
public static void main(String[] args) {
myclass dr= new myclass();
dr.start();
dr.select();
}
public void start(){
driver= new FirefoxDriver();
driver.get("https://www.google.co.in/");
}
public void select(){
driver.findElement(By.linkText("Gmail")).click();
}
}