nullpointerexception error on new installation - java

A fresh installation of eclipse has been created as a result of this error (I deleted all the files, however I'm guessing I missed a few)
This is the error:
java.lang.NullPointerException
at testing.testsrc.testcase1(testsrc.java:16)
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)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Getting it on a brand new project too so believe this is away from any project specific configuration.
Can anyone assist?
EDIT:
As an example this code will also return the same error:
package testing;
package TestsStudies;
import static org.junit.Assert.*;
import java.awt.Desktop.Action;
import java.awt.List;
import java.awt.RenderingHints.Key;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
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 com.gargoylesoftware.htmlunit.javascript.host.Iterator;
public class TestingStd {
WebDriver driver;
WebElement sidearrow;
WebElement sidemenu;
WebDriverWait wait = new WebDriverWait(driver, 3);
#Before
public void setUp() throws InterruptedException { //Creating driver and connecting to url
String baseURL = "url";
System.setProperty("webdriver.gecko.driver", "/Users/user/Desktop/gecko/geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(baseURL);
driver.findElement(By.id("isid")).sendKeys("username");
WebElement Password = driver.findElement(By.id("password"));
Password.sendKeys("password");
Password.sendKeys(Keys.RETURN);
Thread.sleep(1500);
driver.findElement(By.xpath("//img[# src='/url/images/icons/logo_gif/Br.svg']")).click();;
Thread.sleep(1500);
driver.findElement(By.xpath("//*[#id=\"nosaveq\"]/div[3]/div[1]/span/img")).click();;
Thread.sleep(1500);
}
#Test
public void expDescriptionandSave() throws InterruptedException {
sidemenu = driver.findElement(By.id("optionstd"));
sidearrow = driver.findElement(By.id("slideButton_internal"));
Actions builder = new Actions(driver);
builder.moveToElement(sidemenu).perform();
Thread.sleep(1500);
builder.moveToElement(sidearrow).click().perform();
driver.findElement(By.xpath("//*[#id=\"unusedFolderProtocols\"]/div[2]")).click();
Thread.sleep(1500);
driver.findElement(By.xpath("//*[#id=\"unusedFolderProtocolsContent\"]/div[1]/div[2]/div/img")).click(); //click BioELN
Thread.sleep(1500);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp + " experimentDescriptionandSave");
driver.switchTo().frame("details");
driver.findElement(By.cssSelector("#experiments > table > tbody > tr:nth-child(3) > td:nth-child(2) > textarea")).sendKeys(timeStamp);
driver.findElement(By.xpath("//*[#title='create study']")).click();
Thread.sleep(1500);
String timeStampSecond = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStampSecond + " experimentDescriptionandSave");
WebElement description = driver.findElement(By.name("DESCR"));
description.clear();
description.sendKeys(timeStampSecond);
driver.findElement(By.xpath("//*[#id=\"exp\"]/table/tbody/tr[11]/td/label[1]")).click();
Thread.sleep(1500);
String descriptionText = driver.findElement(By.name("DESCR")).getText();
assertTrue(descriptionText.contains(timeStampSecond));
}

As per your code, you are not initializing your driver variable. The basic code would be -
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
Also, based on what browser you want to use, you would need to download and then setup the corresponding driver as well. For Firefox, it's called GeckoDriver and for Chrome it's called ChromeDriver. Finally, you would need to provide the driver location in your script. So the code would look like this -
System.setProperty("webdriver.gecko.driver", "C:\\some_folder\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
If you are looking for detailed steps, then you can follow this article - Selenium WebDriver Setup

In your code it seems that you haven't initialized your driver
So you might want to add two statements before you write driver.get(); statement.
System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\lib\\chromedriver.exe");
//Or any other browser's driver that you have used.
driver = new ChromeDriver();

Related

java.lang.IllegalStateException: Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM

When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8., Intellij IDEA on Windows 10. Even Though I have mentioned the the Quasar.jar in VM options.
RUN >> Edit Configurations >> Junit>> Required Test Class >>VM options:-ea -javaagent:lib\quasar.jar
enter image description here
package com.template;
import com.google.common.collect.ImmutableList;
import com.template.contracts.MetalContract;
import com.template.flows.Responder;
import com.template.states.MetalState;
import net.corda.core.concurrent.CordaFuture;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.TransactionState;
import net.corda.core.transactions.SignedTransaction;
import net.corda.testing.node.MockNetwork;
import net.corda.testing.node.MockNetworkParameters;
import net.corda.testing.node.StartedMockNode;
import net.corda.testing.node.TestCordapp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.template.flows.IssueMetal;
import com.template.flows.TransferMetal;
import static org.junit.Assert.assertEquals;
import static junit.framework.TestCase.assertTrue;
public class FlowTests {
private final MockNetwork network = new MockNetwork(new MockNetworkParameters(ImmutableList.of(
TestCordapp.findCordapp("com.template.contracts"),
TestCordapp.findCordapp("com.template.flows")
)));
private final StartedMockNode Mint = network.createNode();
private final StartedMockNode A = network.createNode();
private final StartedMockNode B = network.createNode();
#Before
public void setup() {
network.runNetwork();
}
#After
public void tearDown() {
network.stopNodes();
}
// ------------------------------------------ Issue Metal Flow Tests ----------------------------------------
#Test
public void transactionHasNoInputsHasOneMetalStateOutputWithTheCorrectOwner() throws Exception {
IssueMetal flow = new IssueMetal("Gold", 10, A.getInfo().getLegalIdentities().get(0));
CordaFuture<SignedTransaction> future = Mint.startFlow(flow);
setup();
SignedTransaction signedTransaction = future.get();
assertEquals (0, signedTransaction.getTx().getInputs().size());
assertEquals (1, signedTransaction.getTx().getOutputStates().size());
MetalState output = signedTransaction.getTx().outputsOfType(MetalState.class).get(0);
assertEquals(A.getInfo().getLegalIdentities().get(0), output.getOwner());
}
}
The Error is :
java.lang.IllegalStateException: Missing the '-javaagent' JVM argument. Make sure you run the tests with the Quasar java agent attached to your JVM.
See https://docs.corda.net/head/testing.html#running-tests-in-intellij - 'Fiber classes not instrumented' for more details.
at net.corda.node.services.statemachine.SingleThreadedStateMachineManager.checkQuasarJavaAgentPresence(SingleThreadedStateMachineManager.kt:317)
at net.corda.node.services.statemachine.SingleThreadedStateMachineManager.start(SingleThreadedStateMachineManager.kt:135)
at net.corda.node.internal.AbstractNode$start$8.invoke(AbstractNode.kt:409)
at net.corda.node.internal.AbstractNode$start$8.invoke(AbstractNode.kt:122)
at net.corda.nodeapi.internal.persistence.CordaPersistence.inTopLevelTransaction(CordaPersistence.kt:268)
at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:237)
at net.corda.nodeapi.internal.persistence.CordaPersistence.transaction(CordaPersistence.kt:254)
at net.corda.node.internal.AbstractNode.start(AbstractNode.kt:388)
at net.corda.testing.node.internal.InternalMockNetwork$MockNode.start(InternalMockNetwork.kt:346)
at net.corda.testing.node.internal.InternalMockNetwork.createNodeImpl(InternalMockNetwork.kt:471)
at net.corda.testing.node.internal.InternalMockNetwork.createNode(InternalMockNetwork.kt:449)
at net.corda.testing.node.internal.InternalMockNetwork.createNode(InternalMockNetwork.kt:444)
at net.corda.testing.node.internal.InternalMockNetwork.createNotaries$node_driver(InternalMockNetwork.kt:253)
at net.corda.testing.node.internal.InternalMockNetwork.<init>(InternalMockNetwork.kt:236)
at net.corda.testing.node.internal.InternalMockNetwork.<init>(InternalMockNetwork.kt:149)
at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:305)
at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:294)
at net.corda.testing.node.MockNetwork.<init>(MockNetwork.kt:303)
at com.template.FlowTests.<init>(FlowTests.java:25)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
I would recommend using the Gradle Test Runner so that you don't have to set the javaagent flag manually.
To use Gradle Test Runner Click the Run/Debug configuration drop down > Edit Configurations... > + > Gradle In the form that appears, fill in the details:
Gradle-Project : [path to your project]
Task: :cleanTest :test
Arguments: --tests ""
Reference below:

Errors when running a JUnit test case via Selenium

Here is my Class Main Page an
private WebDriver driver;
public MainPage(WebDriver driver) {
this.driver = driver;
}
#FindBy(xpath = "//form/h3")
private WebElement heading;
And here is my method that i want to test by JUnit
public String getErrorText(){
return errorMessage.getText();
}
Here my JUnit class
public class MainPageTest {
private WebDriver driver;
private MainPage mainPage;
#Before
public void setUp(){
System.setProperty("webdriver.chrome.driver", "D:\\Intellij IDEA\\testgroup\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://dtapi.if.ua/login");
mainPage = new MainPage(driver);
}
#Test
public void changeLanguage(){
String heading = mainPage.getHeadingText();
Assert.assertEquals("Authorization",heading);
}
But i'm getting an error:
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987#{#882}) on port 6024
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1584285941.329][WARNING]: Timed out connecting to Chrome, retrying..
And
java.lang.NullPointerException
at MainPage.getHeadingText(MainPage.java:70)
at MainPageTest.changeLanguage(MainPageTest.java:26)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Have you initated your PageFactory?
Try the following -
PageFactory.initElements(driver, this);
Ref:
Java/Selenium - java.lang.NullPointerException

NullPointerException in POM Model

I'm facing NullPointerException in below code - it's project created in POM model.
I was reading other posts related with NullPointerException but I was unable to find error in my Java code.
Appreciate any help.
Test Class:
package pl.b2b.ProjectAutomationPractice;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class AutomationPracticeTest extends Utils {
LoginPage LoginPage = new LoginPage();
DefaultPage DefaultPage = new DefaultPage();
#Test
public void incorrectEmailLoginPage() {
DefaultPage.clickButtonSignIn();
LoginPage.enterEmail("xxx");
LoginPage.enterPassword("xxx");
assertEquals("There is 1 error\n" + "Invalid email address.", LoginPage.getWarningIncorrectLoginDetails());
}
#Test
public void incorrectPasswordLoginPage() {
DefaultPage.clickButtonSignIn();
LoginPage.enterEmail("xxx");
LoginPage.enterPassword("xxx");
assertEquals("There is 1 error\n" + "Authentication failed.", LoginPage.getWarningIncorrectLoginDetails());
}
}
Page Class:
package pl.b2b.ProjectAutomationPractice;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
#FindBy(id = "email")
private WebElement fieldEmailLogin;
#FindBy(id = "passwd")
private WebElement fieldPassword;
#FindBy(xpath = "//*[#id=\\\"SubmitLogin\\\"]/span")
private WebElement buttonSignInAfterEnteringLoginDetails;
#FindBy(xpath = "//*[#id=\\\"searchbox\\\"]/button")
private WebElement buttonSearchMagnifyingGlass;
#FindBy(xpath = "//*[#id=\\\"center_column\\\"]/p")
private WebElement messageSuccessfulLogin;
#FindBy(xpath = "//*[#id=\\\"center_column\\\"]/div[1]")
private WebElement warningIncorrectLoginDetails;
public String enterEmail(String email) {
this.fieldEmailLogin.sendKeys(email);
return email;
}
public String enterPassword(String password) {
this.fieldPassword.sendKeys(password);
return password;
}
public void clickButtonSignInAfterEnteringLoginDetails() {
this.buttonSignInAfterEnteringLoginDetails.click();
}
public String getMessageSuccessfulLogin() {
return this.messageSuccessfulLogin.getText().trim();
}
public String getWarningIncorrectLoginDetails() {
return this.warningIncorrectLoginDetails.getText().trim();
}
}
Another Page Class:
package pl.b2b.ProjectAutomationPractice;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class DefaultPage {
#FindBy(xpath = "//*[#id=\\\"header\\\"]/div[2]/div/div/nav/div[1]/a")
private WebElement buttonSignIn;
public void clickButtonSignIn() {
this.buttonSignIn.click();
}
}
Methods:
package pl.b2b.ProjectAutomationPractice;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Utils {
private WebDriver driver;
#Before
public void createBrowserInstanceNavigateToURL() {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php");
}
#After
public void close() {
driver.close();
}
}
Error:
java.lang.NullPointerException
at pl.b2b.ProjectAutomationPractice.DefaultPage.clickButtonSignIn(DefaultPage.java:12)
at pl.b2b.ProjectAutomationPractice.AutomationPracticeTest.incorrectEmailLoginPage(AutomationPracticeTest.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
private WebElement buttonSignIn in the DefaultPage class does not appear to ever be instantiated. Your regex might be failing
I was trying to edit my code - when i input row with xpath into my test it works perfectly. When I trying to copy same Xpath into DefaultPage class error message is displayed. Have no idea why.
public void incorrectEmailLoginPage() {
driver.findElement(By.xpath("//*[#id='header']/div[2]/div/div/nav/div[1]/a")).click();
DefaultPage.clickButtonSignIn();
LoginPage.enterEmail("incorrectEmail#test.com");
LoginPage.enterPassword("n3tw0rk2017");
assertEquals("There is 1 error\n" + "Invalid email address.", LoginPage.getWarningIncorrectLoginDetails());

IntelliJ Error: java.lang.NullPointerException

I'm new in Selenium, I use IntelliJ, Selenium WebDriver, Junit. My problem is
java.lang.NullPointerException . These are my pages in project.
This is HomePage page:
package PageObjectPage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class HomePage extends BasePage {
#FindBy(how = How.CLASS_NAME, using = "account_icon")
#CacheLookup
WebElement button_my_accout;
public HomePage(WebDriver driver){
super(driver);
}
public MyAccount clickOnMyAccount(){
//Click on My Account
button_my_accout.click();
return PageFactory.initElements(getDriver(), MyAccount.class);
}
This is MyAccount page:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class MyAccount extends BasePage {
#FindBy(id = "log")
#CacheLookup
WebElement username;
#FindBy(how = How.ID, using = "pwd")
#CacheLookup
WebElement password;
#FindBy(how = How.ID, using = "login")
#CacheLookup
WebElement login_button;
public MyAccount(WebDriver driver){
super(driver);
}
public MyAccount LogIn(){
//Fill in the text box username
username.sendKeys("Dragana");
//Fill in the text box password
password.sendKeys("123456");
return new MyAccount(driver);
}
public LogInResultPage submitForm() {
//Click on button Log in
login_button.click();
return new LogInResultPage(driver);
}
}
This is my LogInResultPage:
package PageObjectPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LogInResultPage extends BasePage{
public LogInResultPage(WebDriver driver){
super(driver);
}
public String getMessage(){
//Printing message
return driver.findElement(By.tagName("p")).getText();
}
}
This is BasePage page:
package PageObjectPage;
import org.openqa.selenium.WebDriver;
public class BasePage {
protected WebDriver driver;
public BasePage (WebDriver driver){
this.driver = driver;
}
public WebDriver getDriver() {
return this.driver;
}
}
This is TestBase page:
public class TestBase {
WebDriver driver;
public WebDriver getDriver() {
return driver;
}
#Before
public void testSetUp(){
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dragana\\Desktop\\chromedriver.exe ");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized", "--disable-cache");
driver = new ChromeDriver(options);
driver.navigate().to("http://store.demoqa.com/");
}
#After
public void testTearDown(){
driver.close();
}
}
This is test page:
package test;
import PageObjectPage.HomePage;
import PageObjectPage.LogInResultPage;
import PageObjectPage.MyAccount;
import TestBaseSetup.TestBase;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class AccountTest extends TestBase {
public WebDriver getDriver() {
return driver;
}
WebDriver driver;
#Test
public void shouldLogIn() {
HomePage onHomePage = PageFactory.initElements(driver, HomePage.class);
System.out.println("Step 1 ");
MyAccount onMyAccount = onHomePage.clickOnMyAccount();
System.out.println("Step 2");
LogInResultPage onResultPage = onMyAccount.LogIn().submitForm();
System.out.println("Step 3");
wait(2000);
Assert.assertTrue(onResultPage.getMessage().contains("ERROR"));
}
public void wait(int seconds){
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
Error:
"C:\Program Files\Java\jdk1.8.0_101\bin\java" -ea -Didea.launcher.port=7532 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.2.1\bin" -Didea.junit.sm_runner -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.2.1\lib\idea_rt.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.2.1\plugins\junit\lib\junit-rt.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_101\jre\lib\rt.jar;C:\Users\Dragana\workspace\proba\target\test-classes;C:\Users\Dragana\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\Dragana\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-java\3.0.0-beta3\selenium-java-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-chrome-driver\3.0.0-beta3\selenium-chrome-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-remote-driver\3.0.0-beta3\selenium-remote-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-api\3.0.0-beta3\selenium-api-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\cglib\cglib-nodep\3.2.4\cglib-nodep-3.2.4.jar;C:\Users\Dragana\.m2\repository\org\apache\commons\commons-exec\1.3\commons-exec-1.3.jar;C:\Users\Dragana\.m2\repository\com\google\code\gson\gson\2.3.1\gson-2.3.1.jar;C:\Users\Dragana\.m2\repository\com\google\guava\guava\19.0\guava-19.0.jar;C:\Users\Dragana\.m2\repository\org\apache\httpcomponents\httpclient\4.5.2\httpclient-4.5.2.jar;C:\Users\Dragana\.m2\repository\org\apache\httpcomponents\httpcore\4.4.4\httpcore-4.4.4.jar;C:\Users\Dragana\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;C:\Users\Dragana\.m2\repository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;C:\Users\Dragana\.m2\repository\org\apache\httpcomponents\httpmime\4.5.2\httpmime-4.5.2.jar;C:\Users\Dragana\.m2\repository\net\java\dev\jna\jna\4.1.0\jna-4.1.0.jar;C:\Users\Dragana\.m2\repository\net\java\dev\jna\jna-platform\4.1.0\jna-platform-4.1.0.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-edge-driver\3.0.0-beta3\selenium-edge-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-firefox-driver\3.0.0-beta3\selenium-firefox-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-ie-driver\3.0.0-beta3\selenium-ie-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-opera-driver\3.0.0-beta3\selenium-opera-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-safari-driver\3.0.0-beta3\selenium-safari-driver-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\io\netty\netty\3.5.7.Final\netty-3.5.7.Final.jar;C:\Users\Dragana\.m2\repository\org\seleniumhq\selenium\selenium-support\3.0.0-beta3\selenium-support-3.0.0-beta3.jar;C:\Users\Dragana\.m2\repository\com\codeborne\phantomjsdriver\1.3.0\phantomjsdriver-1.3.0.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 test.AccountTest,shouldLogIn
Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 33399
Only local connections are allowed.
Dec 07, 2016 6:54:51 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Dec 07, 2016 6:54:54 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Step 1
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.$Proxy8.click(Unknown Source)
at PageObjectPage.HomePage.clickOnMyAccount(HomePage.java:25)
at test.AccountTest.shouldLogIn(AccountTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
In your AccountTest class you are declaring WebDrive driver; again which setting to driver=null, this cause HomePage driver to be null; Also you do not need getter for webDriver. This should work just fine
public class AccountTest extends TestBase {
#Test
public void shouldLogIn() {
HomePage onHomePage = PageFactory.initElements(driver, HomePage.class);
System.out.println("Step 1 ");
MyAccount onMyAccount = onHomePage.clickOnMyAccount();
System.out.println("Step 2");
LogInResultPage onResultPage = onMyAccount.LogIn().submitForm();
System.out.println("Step 3");
wait(2000);
Assert.assertTrue(onResultPage.getMessage().contains("ERROR"));
}
public void wait(int seconds){
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}

NullPointerException on running selenium script with JUnit

I am using pageObject Model for my selenium automation.
Consider following browser config class.
package BrowserConfig;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class crossBrowserConfiguration {
By logInPanel = By.xpath("//div[#id='logInPanelHeading']");
public static WebDriver driver = null;
WebDriverWait wait = new WebDriverWait(driver,30);
#Before
public void initBrowser(){
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("Website that contains Login Page");
wait.until(ExpectedConditions.visibilityOfElementLocated(logInPanel));
}
#After
public void closeBrowser(){
driver.quit();
}
}
I have a page object of Log in screen.
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import BrowserConfig.crossBrowserConfiguration;
public class LoginScreen extends crossBrowserConfiguration {
WebDriverWait wait = new WebDriverWait(driver,30);
By userName = By.xpath("//input[#id='txtUsername']");
By password = By.xpath("//input[#id='txtPassword']");
By loginButton = By.xpath("//input[#id='btnLogin']");
By welcomeNote = By.xpath("//a[#id='welcome']");
By empListVerify = By.xpath("//div[#id='employee-information']/a");
public void logIN(String UserName, String Password){
driver.findElement(userName).sendKeys(UserName);
driver.findElement(password).sendKeys(Password);
driver.findElement(loginButton).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(welcomeNote));
//Employee List Verification
String empListBtnText = driver.findElement(empListVerify).getText();
System.out.println(empListBtnText);
}
}
And finally, I have the following test case script:
package TestCases;
import org.junit.Test;
import BrowserConfig.crossBrowserConfiguration;
import PageObjects.LoginScreen;
public class initiateBrows extends crossBrowserConfiguration{
LoginScreen Obj1 = new LoginScreen();
#Test
public void runThis() throws Exception{
Obj1.logIN("admin", "123456");
}
}
When I run my test as JUnit Test, it gives nullPointerException without running at all. Stack trace for the exception is:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:212)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:102)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
at BrowserConfig.crossBrowserConfiguration.<init>(crossBrowserConfiguration.java:15)
at TestCases.initiateBrows.<init>(initiateBrows.java:8)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
at BrowserConfig.crossBrowserConfiguration.<init>(crossBrowserConfiguration.java:15)
refers to WebDriverWait wait = new WebDriverWait(driver,30);
Any insight into why am I facing this exception?
The wait field is initialized when the an object of the class is created. This happens before JUnit calls the #Before method. Therefore the driver object is null. There are different ways of fixing the issue. One is making the driver object a simple field and initialize it immediately.
public class crossBrowserConfiguration {
By logInPanel = By.xpath("//div[#id='logInPanelHeading']");
public final WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,30);
#Before
public void initBrowser(){
driver.manage().window().maximize();
driver.get("Website that contains Login Page");
wait.until(ExpectedConditions.visibilityOfElementLocated(logInPanel));
}
#After
public void closeBrowser(){
driver.quit();
}
}

Categories

Resources