Rick
Rick

Reputation: 91

How to create common object of a class to use in all methods Of TestNG class?

package com.test;

import org.testng.Reporter;

import org.testng.annotations.Test;

import org.openqa.selenium.support.PageFactory;

import utility.BaseClass;

import com.pages.LoginPageObjects;

public class UnderTest extends BaseClass

{

    @Test(description = "Email login")
    public void f()
    {
        Reporter.log("===dude===", true);
        LoginPageObjects lpage = PageFactory.initElements(driver, LoginPageObjects.class);
        lpage.click_signin_link();
        lpage.enter_uid("[email protected]");
        lpage.click_submit(); 
    }

    @Test(description = "fb login")
    public void fe() throws InterruptedException
    {
        Reporter.log("===dude===", true);
        LoginPageObjects lpage = PageFactory.initElements(driver, LoginPageObjects.class);
        lpage.click_fb_button();
        Thread.sleep(5000);

    }


}

The test runs well if I create object separately in both the methods. When declared in @BeforeTest it is not working. How can I reduce the reuse of that statement?

Upvotes: 0

Views: 1138

Answers (2)

Fenio
Fenio

Reputation: 3635

In order to get access to LoginPageObjects instance, you have to create it as class variable. It will be accessible for all methods within your class.

Then, initialize this variable in @BeforeTest annotation.

public class UnderTest extends BaseClass {
    private LoginPageObjects lpage;

@BeforeTest
   public void setUp() throws Exception {
       lpage = PageFactory.initElements(driver, LoginPageObjects.class);
   }

@Test(description = "Email login")
public void f()
{
    Reporter.log("===dude===", true);
    lpage.click_signin_link();
    lpage.enter_uid("[email protected]");
    lpage.click_submit(); 
}

@Test(description = "fb login")
public void fe() throws InterruptedException
{
    Reporter.log("===dude===", true);
    lpage.click_fb_button();
    Thread.sleep(5000);

}

Upvotes: 1

UmaShankar Chaurasiya
UmaShankar Chaurasiya

Reputation: 111

Try the Following code...

package com.test;

import org.testng.Reporter;

import org.testng.annotations.Test;

import org.openqa.selenium.support.PageFactory;

import utility.BaseClass;

import com.pages.LoginPageObjects;

public class UnderTest extends BaseClass

{

   @Before
   public void setUp() throws Exception {
     LoginPageObjects lpage = PageFactory.initElements(driver, 
     LoginPageObjects.class);

}
    @Test(description = "Email login")
    public void f()
    {
        Reporter.log("===dude===", true);
        lpage.click_signin_link();
        lpage.enter_uid("[email protected]");
        lpage.click_submit(); 
    }

    @Test(description = "fb login")
    public void fe() throws InterruptedException
    {
        Reporter.log("===dude===", true);
        lpage.click_fb_button();
        Thread.sleep(5000);

    }


}

Upvotes: 0

Related Questions