Exception in thread "main" java.lang.NullPointerException in Selenium Webdriver - testing

class Login as the following method Kreato_Login():-
public void Kreato_Login(){
driver = new FirefoxDriver();
baseUrl = "https://testrugtn.kreatocrm.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit. SECONDS);
driver.manage().window().maximize();
driver.get(baseUrl + "/");
driver.findElement(By. id("Login_txtUserName")).clear();
driver.findElement(By. id("Login_txtUserName")).sendKeys( "saravana");
driver.findElement(By. id("Login_txtPassword")).clear();
driver.findElement(By. id("Login_txtPassword")).sendKeys( "5678");
driver.findElement(By. id("Login_btnLogin")).click();
}
Class Lead as the following method "Lead_MandatoryCheck()":-
LoginLogout leadInstance=new LoginLogout();
public void Lead_MandatoryCheck() throws InterruptedException{
leadInstance.Kreato_Login();
driver1.findElement(By. xpath("//a[contains(text(),'Customers')]")).click();
driver1.findElement(By. linkText("Leads")).click();
//Add New
driver1.findElement(By. cssSelector( "#ctl00_ContentPlaceHolder1_cbpSubContent_imgAddNew_CD > span.dx-vam" )).click();
Thread.sleep(3000);
//Save
driver1.findElement(By. cssSelector("#ctl00_ContentPlaceHolder1_cbpAssociationNew_btnNewItemTopCreationSave_CD > span.dx-vam" )).click();
String mandatoryPopup= driver1.switchTo().alert().getText();
driver1.switchTo().alert().accept();
System.out.println(mandatoryPopup);
}
I try to call the above methods from the class Trigger as follows:-
public class TriggerClass {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
/*LeadCreation lc= new LeadCreation();
lc.setUp();
lc.testLeadCreation();
lc.tearDown();*/
LeadModule Lm=new LeadModule();
Lm.Lead_MandatoryCheck();
}
when i run the "Trigger.class"
Exception in thread "main" java.lang.NullPointerException
at workflow.LeadModule.Lead_MandatoryCheck(LeadModule.java:132)
at workflow.TriggerClass.main(TriggerClass.java:13)

This is how you should structure your class, members and functions:
TriggerClass.java:
public class TriggerClass {
public static WebDriver driver;
public static void main(String[] args) throws Exception {
driver = new FirefoxDriver();
LeadModule Lm=new LeadModule();
Lm.Lead_MandatoryCheck();
}
LeadModule.java:
public class LeadModule {
public WebDriver driver;
public LeadModule() {
this.driver = TriggerClass.driver;
}
public void Lead_MandatoryCheck() throws InterruptedException{
LoginLogout leadInstance = new LoginLogout();
leadInstance.Kreato_Login();
driver.findElement(By.xpath("//a[contains(text(),'Customers')]")).click();
driver.findElement(By.linkText("Leads")).click();
//Add New
driver.findElement(By.cssSelector( "#ctl00_ContentPlaceHolder1_cbpSubContent_imgAddNew_CD > span.dx-vam" )).click();
Thread.sleep(3000);
//Save
driver.findElement(By. cssSelector("#ctl00_ContentPlaceHolder1_cbpAssociationNew_btnNewItemTopCreationSave_CD > span.dx-vam" )).click();
String mandatoryPopup= driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(mandatoryPopup);
}
LoginLogout.java:
public class LoginLogout extends LeadModule {
public void Kreato_Login(){
baseUrl = "https://testrugtn.kreatocrm.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit. SECONDS);
driver.manage().window().maximize();
driver.get(baseUrl + "/");
driver.findElement(By.id("Login_txtUserName")).clear();
driver.findElement(By.id("Login_txtUserName")).sendKeys("saravana");
driver.findElement(By.id("Login_txtPassword")).clear();
driver.findElement(By.id("Login_txtPassword")).sendKeys("5678");
driver.findElement(By.id("Login_btnLogin")).click();
}
}
Your Java/Selenium basics are not clear. Please read through the documentation or view related tutorials on YouTube.

Related

How can I use Desktop automation?

I tried Winium but xpath is not working. Is there anything besides Winium?
public class Desktop_Steps {
public static void main (String[] args) throws MalformedURLException, InterruptedException {
DesktopOptions option = new DesktopOptions();
option.setApplicationPath("location of app");
URL url = new URL(" http://127.0.0.1:4723/");
WiniumDriver driver = new WiniumDriver(url,option);
// driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
Thread.sleep(7000);
driver.findElement(By.id("15894400")).sendKeys("hello");
}
}

NullPointerException error i.e. AndroidDriver not gets initialized for the second test class as It's working fine for the first test class

This is My setup class:
public class SetupClass {
//AppiumDriver<MobileElement> driver;
AndroidDriver<MobileElement> d;
public Properties prop =null;
public File file;
public FileInputStream fis;
#Parameters(value ="Android")
#BeforeSuite
public void setup(String Android) throws IOException, Exception{
LoadPropertiesFile();
DesiredCapabilities caps = new DesiredCapabilities();
/*caps.setCapability("plateformName", "Android");
caps.setCapability(CapabilityType.PLATFORM_NAME, "Android");*/
if (Android.equalsIgnoreCase("Moto_g4_Plus")) {
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.0");
caps.setCapability(MobileCapabilityType.UDID, "ZY223WZSQ9");
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "Moto G4 Plus");
}
caps.setCapability("app", "C:\\Users\\amarjeet.sharma\\eclipse-workspace\\com.asm.app\\src\\test\\resources\\app\\asmVisit.apk");
caps.setCapability("appPackage", "com.sumasoft.net.asmscheduler");
caps.setCapability("appActivity", "md5f32326382a711c73d2de951d70f3bd5e.MainActivity");
caps.setCapability("autoGrantPermissions", true);
URL url;
try {
url = new URL("http://127.0.0.1:4723/wd/hub");
//driver = new AppiumDriver<MobileElement>(url, caps);
d = new AndroidDriver<MobileElement>(url, caps);
Thread.sleep(5000);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("Cause is:" +e.getCause());
System.out.println("Message is:" +e.getMessage());
e.printStackTrace();
}
}
public void LoadPropertiesFile() throws IOException {
prop=new Properties();
file =new File(System.getProperty("user.dir")+"/src/main/resources/config.properties");
fis=new FileInputStream(file);
prop.load(fis);
//System.out.println(prop.getProperty("userId"));
}
//#AfterTest
public void TearDown() throws IOException{
System.out.println("Quit");
d.quit();
}
}
This is My LoginTest
public class LoginTest extends SetupClass{
#Test(priority = 1)
public void login() throws Exception {
LoginPage lp = new LoginPage(d);
//System.out.println(prop.getProperty("userId"));
lp.userName(prop.getProperty("userId"));
Thread.sleep(500);
lp.password(prop.getProperty("Passwd"));
Thread.sleep(500);
lp.loginButton();
}
}
And this is my create new journey class
public class AddJourneyTest extends SetupClass{
#Test(priority=2)
public void AddNewJourney() throws Exception {
AddjourneyPage addobj = new AddjourneyPage(d);
addobj.ClicktoAdd();
addobj.SelectFromToDate();
addobj.SelectState();
addobj.SelectCity();
addobj.ClickonSubmit();
}
}
I am getting NullPointerException for AddJourney class
I think when I run it as TestNG then the driver gets initiated for the LoginTest and holds the control. So that AddJourney class does not get driver initiated and hence getting NullPointerException.
I am using Appium Server, Java + Selenium + TestNG for the Android Application automation on Windows system with physical android device.
Maybe I am wrong. But I am not getting solution over it. Please help.

How to resolve null pointer exception in selenium when page factory method is used

I have 3 classes - one for page locator, one for page action and the other one as script to execute the function. am getting nullpointer exception in main scripts where the function is called. Can anyone help me out, please!!!!.
The following are the code :
HomePageLocator.page
public class HomePageLocator{
WebDriver driver;
public HomePageLocator(WebDriver driver)
{
this.driver= driver;
}
#FindBy(xpath="//*[#id='header']/div[2]/div/div/nav/div[1]/a")
public WebElement signIn;
}
HomePageAction.page
public class HomePageAction{
public WebDriver driver;
public HomePageLocator homepageor;
public HomePageAction() {
this.homepage = new HomePageLocator(driver);
PageFactory.initElements(driver, this.homepage);
}
public void login() {
homepageor.signIn.click();
}
BaseTestCase.java
public class BaseTestCase {
public static Logger log = Logger.getLogger("devpinoyLogger");
public static void main(String[] args) throws Throwable {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\src\\test\\resources\\Executables\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Home page validation
HomePageAction homepageaction= new HomePageAction();
homepageaction.login();
}
Note : Am getting exception in line (homepageaction.login();)
the following is the exception logs :
Exception in thread "main" 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.$Proxy3.click(Unknown Source)
at com.way2.Pages.actions.HomePage.login(HomePageAction.java:31)
at com.way2.Testcases.BaseTestCase.main(BaseTestCase.java:35)
You are creating the driver in main class, but not passing it to homepageAction
public static void main(String[] args) throws Throwable {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\src\\test\\resources\\Executables\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Try to pass driver as
HomePageAction homepageaction= new HomePageAction(driver);
this.driver =driver

Running selenium, cucumber and Page Factory. Second step definition fail to run

I wrote a cucumber framework that has two feature files and two stepdefinitions which are glued to the feature files. When i run the test together, it ran for the first stepDefinition and fail to enter the second stepDefinition. I have initialize my pages and yet couldn't get it to work.
Error and Codes below
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.$Proxy19.click(Unknown Source)
at Pages.HomePage.CreateANewOrderPage.createOrderLink(CreateANewOrderPage.java:35)
at StepDefinitions.CreateOrderStep.user_click_on_create_a_new_order(CreateOrderStep.java:24)
at ✽.When user click on create a new order(CreateOrder.feature:5)
public class CreateANewOrderPage {
WebDriver driver;
public CreateANewOrdePage(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy (linkText= "Create a new order")
public WebElement createOrderLink;
public void createOrderLink(){
createOrderLink.click();
}
public class SigninPage {
WebDriver driver;
public SigninPage(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//*[#id=\"userName\"]")
public WebElement usernameField;
#FindBy(name="password")
public WebElement passwordField;
#FindBy(id="buttonSubmitLogin")
public WebElement submitBtn;
public void loginDetails(String uname, String psw) {
usernameField.sendKeys(uname);
passwordField.sendKeys(psw);}
public void clickLogin(){
submitBtn.click();
}
}
public class SigninStep {
WebDriver driver;
SigninPage logIn = new SigninPage(driver);
#Given("^user navigates to mySite$")
public void userNavigatesToMysite() throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\mypc\\Documents\\Automation\\drivers\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("www.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#And("^user enter \"([^\"]*)\" and \"([^\"]*)\"$")
public void userEnterValidCredentials(String validuname, String validpsw) throws Throwable {
SigninPage logIn = new SigninPage(driver);
logIn.loginDetails("jdjdjdj","jjdjdj");
}
#When("^user click on Sign in$")
public void userClickSignIn() throws Throwable {
SigninPage logIn = new SigninPage(driver);
logIn.clickLogin();
}
}
public class CreateOrderStep {
WebDriver driver;
CreateANewOrderPage ordercreate;
#When("^user click on create a new order$")
public void user_click_on_create_a_new_order() throws Throwable {
ordercreate= PageFactory.initElements(driver,CreateANewOrderPage.class);
ordercreate.createOrderLink();
}
#RunWith(Cucumber.class)
#CucumberOptions (features = "src\\test\\java\\Features\\",
glue ={"StepDefinitions"},
tags={"#Signin, #CreateOrder"}
//format = {"pretty", "html:target/Destination.."}
// format={"json:target/Destination/cucumber.json"
)
public class SigninRunner {
}

FindBy in pageFactory (webdriver) doesn't work correctly

I want to write tests in selenium WebDriver with PageFactory, but if I add annotations in PageFactory form in class
#FindBy(id="email")
public WebElement mailLink;
and usage:
mailLink.sendKeys("mail#mail.com");
I get a NullPointerException every time. Another way:
driver.findElement(By.id("email")).sendKeys("mail#mail.com");
returns correct value. Where is the problem with first method?
My code:
I have got driver initialization in FaceClass:
public class FaceClass {
protected WebDriver driver;
public FaceClass(WebDriver driver){
this.driver = driver;
}
public HomePage navigateToApp(){
driver.navigate().to("https://facebook.pl");
return PageFactory.initElements(driver, HomePage.class);
}
}
and class with business logic:
public class HomePage extends FaceClass{
public HomePage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
#FindBy(id="email")
public WebElement mailLink;
#FindBy(id="pass")
public WebElement passLink;
#FindBy(how = How.ID, using="u_0_n")
public WebElement loginButton;
public ProfilePage navigateToProfile(){
try{
if(driver.findElement(By.id("pass")).isEnabled() || driver.findElement(By.id("pass")).isDisplayed()){
System.out.println("ok!");
}
//driver.findElement(By.id("pass")).sendKeys("pass_to_account");
//driver.findElement(By.id("email")).sendKeys("mail#mail.com");
//driver.findElement(By.id("u_0_n")).click();
mailLink.sendKeys("mail#mail.com");
passLink.sendKeys("pass_to_account");
loginButton.click();
} catch (Exception e) {
e.printStackTrace();
}
return PageFactory.initElements(driver, ProfilePage.class);
}
}
and test:
public class ExampleTest {
WebDriver driver;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setCapability("marionette", true);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("https://facebook.pl");
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void test() {
//fail("Not yet implemented");
HomePage homepage = new HomePage(driver);
homepage.navigateToProfile();
}
}
All elements are enabled and visible
You did not initialize your elements before using. To initialize your page elements PageFactory method initElements. It's better if you call it in your constructor like this:
public HomePage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
Hope it works.