Java Selenium, NullPointerException if page object initialized outside of method - java

I am using Java, Selenium, Cucumber and Page Objects to run my tests. I have StepDef file which looks like below:
public class stepDefinition extends Base{
#Given("^Navigate to Landing page$")
public void navigate_to_landing_page() throws Throwable {
driver= initializeDriver();
driver.get(prop.getProperty("url"));
}
#Then("^Landing page is rendered$")
public void landing_page_is_rendered() throws Throwable {
SomePage ep = new SomePage ();
sp.LandingPageLoaded();
}
#When("^Clicks Apply Now$")
public void clicks_apply_now() throws Throwable {
SomePage ep = new SomePage ();
sp.clickApplyNow();
}
And I want initialize object of SomePage only once on class level, and use in all methods inside my stepDefinition class, see below:
public class stepDefinition extends Base{
SomePage sp = new SomePage ();
#Given("^Navigate to Landing page$")
public void navigate_to_landing_page() throws Throwable {
driver= initializeDriver();
driver.get(prop.getProperty("url"));
}
#Then("^Landing page is rendered$")
public void landing_page_is_rendered() throws Throwable {
sp.LandingPageLoaded();
}
#When("^Clicks Apply Now$")
public void clicks_apply_now() throws Throwable {
sp.clickApplyNow();
}
But it throws me NullPointerException for sp.clickApplyNow(); if I'm not initializing object inside that method. Is there any way to initialize object only on class level. I am new to java.

Related

How to verify and assert nonvisible Icon via Selenium?

I have a situation- I want to write a test when a particular User Logs in, he should not see Budget Icon. Budget icon is obviously not available when he's logged in. So I want to make sure that its working right though assertion. I am confused how should I do it ..I am using Page Object Model and I am trying below: using isDisplayed method
Below is my Base class:
public class LaydownHomePage extends TestBase {
#FindBy(xpath="//nav[#id=\"mainnav-container\"]/div[2]/a[2]")
WebElement budgeticon;
public LaydownHomePage () {
PageFactory.initElements(driver, this);
}
public boolean CheckIfBudgetIconIsAvailable ()
{
return budgeticon.isDisplayed();
}
}
And this is my Test class:
public class VerifyLaydownBudgeticon extends TestBase
{
LoginPage loginpage;
LaydownHomePage homepage;
public VerifyLaydownBudgeticon()
{
super();
}
#Test(priority=1)
public void setUp()
{
//TestBase base= new TestBase();
initialization();
loginpage= new LoginPage();
loginpage.loginToBase(prop.getProperty("username"),prop.getProperty(
"password"));
homepage=loginpage.changeLogin();
}
#Test(priority=2)
public void BudgetIconDisplayed (){
// Assert.assertTrue(false);
Assert.assertEquals(true, homepage.CheckIfBudgetIconIsAvailable());
}
}

java.lang.NullPointerException error witt #Test [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I am new to this java Selenium.
I have 2 classes. 1 parent and 1 child.
I have some methods in the parent class.
I pass 2 of them to the child class.
The problem is only 1 method (from the parent) executes and the 2nd failed.
can you help me to understand why I am getting the error and how to resolve it please :
"java.lang.NullPointerException"
Parent class :
public class SignUp {
public WebDriver driver;
public void go(WebDriver driver)
{
driver.findElement(By.id("id_sign_up")).click();
}
#Test
public void signup(WebDriver driver)
{
driver.findElement(By.linkText("I’m an advertiser")).click();
}
public void FormSign (WebDriver driver)
{
driver.findElement(By.xpath("//span[#css='1']")).sendKeys("Miron");
}
}
Child class :
public class OpenBrowser extends SignUp{
#Test
public void Start() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://account.admitad.com/en/sign_in/");
SignUp sg = new SignUp();
sg.go(driver);
//sg.signup(driver);
}
#Test
public void miron ()
{
SignUp mi = new SignUp();
mi.signup(driver);
}
Can someone please help me?
Thanks in advance
Ans: WebDriver driver object is inside Start().
Object declaration should be defined out side. Then all methods can access driver obj.
public class SignUp {
public WebDriver driver;
public void go(WebDriver driver)
{
driver.findElement(By.id("id_sign_up")).click();
}
//#Test
public void signup(WebDriver driver)
{
driver.findElement(By.linkText("I’m an advertiser")).click();
}
public void FormSign (WebDriver driver)
{
driver.findElement(By.xpath("//span[#css='1']")).sendKeys("Miron");
}
}
/*******************/
public class OpenBrowser extends SignUp{
WebDriver driver = null;
#BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://account.admitad.com/en/sign_in/");
}
#Test
public void Start() throws InterruptedException
{
SignUp sg = new SignUp();
sg.go(driver);
//sg.signup(driver);
}
#Test
public void miron ()
{
SignUp mi = new SignUp();
mi.signup(driver);
}
}

Selenium Java base class for all browser drivers and code which is redundant

I am new in Selenium and Java and I need help with base class. I have I base where I set methods for driver browsers and for its close. Problem is that when I call these method from main always web driver is called and browser is open many times. What is best practice if I don't want to have code duplication
and I want a good structure of project.
Main:
public class Main extends TestBase {
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
LoginTest LoginTest = new LoginTest();
LogofTest LogofTest = new LogofTest();
TestBase TestBase = new TestBase();
LoginTest.setUpBeforeTestMethod();
LoginTest.loginAsAdmin();
LogofTest.logofAsAdmin();
LoginTest.tearDownAfterTestClass();
}
}
TestBase:
public class TestBase {
String a = System.setProperty("webdriver.chrome.driver",
"path");
WebDriver driver = new ChromeDriver();
protected WebDriver setUpBeforeTestClass() {
return driver;
}
protected void setUpBeforeTestMethod() {
driver.get("website");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void tearDownAfterTestClass() {
driver.close();
}}
LoginTest:
public class LoginTest extends TestBase {
public void login() throws InterruptedException {
WebElement username = driver.findElement(By.name("username"));
username.sendKeys("username");
}
}
The main focus is that I don't want to write again
WebDriver driver = new ChromeDriver();
driver.get("website"); System.setProperty("webdriver.chrome,"path");
for each test in function or class. So I want to create base class and inherit from it.
Example Selenium Test with JUnit using the Page Object Model
TestBase
public class TestBase
{
private String a = System.setProperty("webdriver.chrome.driver", "path");
protected WebDriver driver;
#Before //Before each test case, use BeforeClass for before each test class
public static void setUpBeforeTestCase() {
driver = new ChromeDriver();
driver.get("website");
}
#After
public static void tearDownAfterTestCase() {
driver.Quit(); //driver.Close() closes the window, but doesn't properly dispose of the driver
}
}
LoginTest:
public class LoginTest extends TestBase {
#Test
public void loginAndOutAsAdmin(){
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
LandingPage landingPage = loginPage.login("adminUser", "adminPassword");
landingPage.logout();
//Do some sort of assert here that you are logged out
}
}
BasePage
public class BasePage
{
protected WebDriver driver;
//Other common stuff your Page Objects will do, like wait for an element
}
LoginPage
public class LoginPage extends BasePage
{
#FindBy(how = How.NAME, using = "username")
private WebElement usernameBox;
//something for passwordBox and loginButton
public LoginPage(WebDriver currentDriver)
{
driver = currentDriver;
}
public LandingPage login(String username, String password)
{
usernameBox.sendKeys(username);
passwordBox.sendKeys(password);
loginButton.click();
return PageFactory.initElements(driver, LandingPage.class);
}
}
I haven't tried to compile this, but that's the basic idea. I'll let you fill in the details.

Selenium Grid Implementaiton with exisiting framework produce an Null pointer exception

We have implemented the Selenium Grid (Distributed Test) Concept with our existing framework, while implemented its produce an Null Pointer Exception
as of now i have an single package, with three class file (Baseclass, Loginclass, testcase)
Baseclass - getting my desired driver and navigate to application
class Baseclass {
public WebDriver myDriver;
public static String baseUrl;
// Explicit Constructors
public Baseclass() {
baseUrl = "https://example.com/";
}
public void Navigate(String url) {
String navigateToThisUrl = baseUrl + url;
myDriver.navigate().to(navigateToThisUrl);
}
public void GetDriver() throws MalformedURLException {
threadDriver = new ThreadLocal<RemoteWebDriver>();
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
FirefoxProfile fp = new FirefoxProfile();
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, fp);
desiredCapabilities.setBrowserName(DesiredCapabilities.firefox()
.getBrowserName());
myDriver = new RemoteWebDriver(new URL(
"http://localhost:5555/wd/hub"), desiredCapabilities);
}
}
and in Loginclass navigate to the location (either QA or UAT etc.,)
public class Loginclass extends Baseclass {
public Loginclass navigateToLogin() {
Navigate("qa");
return new Loginclass();
}
}
Testcase we have an test case and executed the same
public class TestcaseSearch extends Loginclass {
#BeforeTest
public final void Startup() throws MalformedURLException {
Baseclass baseClass = new Baseclass();
baseClass.GetDriver;
}
#Test
public void fieldsSearch(String username, String password)
throws Exception {
Loginclass loginClass = new Loginclass();
navigateToLogin();
}
}
While Execute the above its produce an Null Pointer Exception
Baseclass: idsDriver.navigate().to(navigateToThisUrl);
Loginclass :Navigate("qa");
Let me know how can i rectify this
Exception output
java.lang.NullPointerException
at com.Baseclass.Navigate(Baseclass.java:11)
at com.Loginclass.Navigate(Loginclass.java:1)
at com.TestcaseSearch.Navigate(TestcaseSearch.java:1)
at com.Loginclass.navigateToLogin(Loginclass.java:4)
at com.TestcaseSearch.fieldsSearch(TestcaseSearch.java:11)
Your myDriver instance is null because you create a new instance of Baseclass in Startup(), which sets myDriver on itself rather than the actual test class instance.
Similarly, you don't need to create a new Loginclass in fieldsSearch, because TestcaseSearch is a subclass of Loginclass:
public class TestcaseSearch extends Loginclass {
#BeforeTest
public final void Startup() throws MalformedURLException {
GetDriver();
}
#Test
public void fieldsSearch(String username, String password)
throws Exception {
navigateToLogin();
}
}

How to reuse the exiting instance of webdriver for different classes

I have gone through the existitng questions on this site, but unable to resolve
the following issue
Tools:Junit,IntelliJ,Java Language
//SetUp Class
public class SetUpTest {
public static WebDriver driver;
#BeforeClass
public static void setUpTest() throws InterruptedException
{
driver=new FirefoxDriver();
driver.get("http://www.ABC.co.uk");
Thread.sleep(5000);
}
//Test1
public class HomePageTest extends SetUpTest {
#Test
public void titleTest()
{
assertTrue(driver.getTitle().startsWith("ABC"));
//Test2
public void merchandisingTest() throws InterruptedException {
#Test
public void merchandisingTest()
{
driver.navigate().to("http://ABC.co.uk/deals");
assertThat(driver.getPageSource(),containsString("deals"));
I have tried running the tests with #TestBefore but still two browser windows are opened
one for Test1 and the other for Test2.I have also used #Suite.SuiteClasses
but the problem is still there.
Can you try this code
public class BaseTest{
public WebDriver driver;
#BeforeSuite
public void startDriver(){
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5l, TimeUnit.SECONDS);
driver.get("http://www.ABC.co.uk");
}
}
public class HomePageTest extends BaseTest{
#Test
public void titleTest(){
assetTrue(driver.getTitle().startsWith("ABC"));
}
#Test
public void merchanisingTest(){
driver.navigate().to("http://www.ABC.co.uk/deals");
assertTrue(driver.getTitle().startsWith("deals"));
}
}
Also, you are running this using TestNG XML I guess, within which the #BeforeSuite method is called only once

Categories

Resources