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());
Related
I am trying to apply junit test for my rest controllers.
I've tried to apply junit 4 but I got 404 error instead 200.
It looks like something is not initialized but cant't figured what.
Here is tutorial I have tried to apply.
https://www.youtube.com/watch?v=8S8o46avgAw
I also tried some different tutorials with junit 5 but the result was the same.
Here you can find the whole project.
https://github.com/WojciechWeg/tiny-bank/tree/tests
Just before publishing this post I've applied the following:
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
But the result of it is:
Customers from service: []
So it returns nothing. Above snippet is not in repo link.
Rest controller class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Account;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.model.CustomerResource;
import com.tinybank.tinybankapi.services.CustomerService;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
#RestController
#RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
public static final String BASE_URL = "api/customers";
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resources<List<Customer>>> getListOfCustomers() {
Resources<List<Customer>> resources = new Resources(customerService.getAllCustomers());
String uri = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
resources.add(new Link(uri,"self"));
return ResponseEntity.ok(resources);
}
#GetMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public Customer getCustomer(#PathVariable Long id) {
return customerService.getCustomerById(id);
}
#DeleteMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public void deleteCustomer(#PathVariable Long id) {
customerService.deleteCustomerById(id);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<CustomerResource> createNewCustomer(#RequestBody #Valid Customer Customer) {
Customer customer = customerService.createNewCustomer(Customer);
URI uri = MvcUriComponentsBuilder.fromController(getClass())
.path("/{id}")
.buildAndExpand(customer.getId())
.toUri();
return ResponseEntity.created(uri).body(new CustomerResource(customer));
}
#PutMapping({"/{id}/open_account"})
#ResponseStatus(HttpStatus.OK)
public void openAccount(#PathVariable Long id, #RequestBody Account account) {
customerService.openAccount(id, account);
}
}
Test class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.services.CustomerService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.Date;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
public class CustomerControllerTest {
private MockMvc mockMvc;
#Mock
private CustomerService customerService;
#InjectMocks
private CustomerController customerController;
Customer customer;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
#Test
public void getCustomer() throws Exception {
when(customerService.getCustomerById(any())).thenReturn(customer);
mockMvc.perform(get("api/customers/1"))
.andExpect(status().isOk());
}
}
This is how stack trace looks like:
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at com.tinybank.tinybankapi.controllers.CustomerControllerTest.getCustomer(CustomerControllerTest.java:53)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Have you tried below approach without injecting mocks?
MockMvcBuilders.standaloneSetup(new CustomerController())
.build();
EDIT:
I've ran your code locally.
Do this:
mockMvc = MockMvcBuilders.standaloneSetup(new CustomerController(customerService))
.build();
And add slash to the beginning of URL
mockMvc.perform(get("/api/customers/1"))
.andExpect(status().isOk());
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();
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();
}
}
}
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();
}
}
I am trying to write an automation framework using Java and selenium. While running Junit tests, Firefox browser starts but it cannot go to my local site. I get a NullPointer Exception. I am new to Java, any help will be greatly appreciated. Thanks
java.lang.NullPointerException
at WordpressFramework.LoginPage.GoTo(LoginPage.java:18)
at WordpressTest.LoginTests.Admin_User_Can_Log_In(LoginTests.java:26)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
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:50)
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)
public class LoginTests {
#Before
public void Init()
{
Driver_Setup.Initialize();
}
#Test
public void Admin_User_Can_Log_In(){
LoginPage.GoTo();
LoginPage.LoginAs("rizwan").WithPassword("*****").Login();
public class Driver_Setup {
private static WebDriver instance;
public static WebDriver getWebDriver() {
return instance;
}
public static void setWebDriver(WebDriver instance) {
Driver_Setup.instance = instance;
}
public static void Initialize()
{ WebDriver webdriver=new FirefoxDriver();
webdriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); }
}
public class LoginPage {
public static void GoTo() {
Driver_Setup.getWebDriver().navigate().to("http://localhost:57464/wp-login.php");
}
public static LoginCommand LoginAs(String username)
{
return new LoginCommand(username);
}
public static class LoginCommand
{
private String username;
private String password;
public LoginCommand(String username)
{
this.username = username;
}
public LoginCommand WithPassword(String password) {
this.password= password;
return this;
}
public void Login() {
WebElement loginInput = Driver_Setup.getWebDriver().findElement(By.id("user_login"));
loginInput.sendKeys(username);
WebElement passwordInput = Driver_Setup.getWebDriver().findElement(By.id("user_pass"));
WebElement loginButton = Driver_Setup.getWebDriver().findElement(By.id("wp-submit"));
loginButton.click();
}
}
Looks like the problem is inside Driver_Setup class - getWebDriver returns null since you have not called setWebDriver() to set the instance value.