简体   繁体   中英

How to pass values from one class to another class in TestNG framework

I am writing automation scripts for travel website. I have one class in for HomePage. In home page I am storing the value which I've entered in destination field so that I can compare that value on the search result page to ensure search result match with the value I've entered in destination. So I am getting the value from Homepage class and want to use that value in Search result page. Here is my code below. I am trying to integrate Selenium with TestNG framework. In selenium I've did this using constructor class.

HomePage Class:

 'public class HomePage extends MainSite{

    public static String Rdest ="";

    public HomePage(WebDriver driver) {
        // TODO Auto-generated constructor stub
    }
    @Test
    public void Home() throws InterruptedException
    {
        // Entering values in destination field
             SelectDestination();

                // Clicking calender to 5 months future month
                for (int i = 0; i <= 5; i++) {


driver.findElement(By.xpath("//div[contains(text(),'Select Departure 
Date')]/following::a[contains(@class,'ui-datepicker-next ui-corner-all')] 
[2]")).click();

                }

                //Calling SelectDate funtion to select date
                SelectDate();


                // clicking Search Flight button
                driver.findElement(By.xpath("//*[@id='btn-search- 
flight']")).click();


    }

public   String SelectDestination() throws InterruptedException{

    WebElement dest = driver.findElement(By.id("destination_0"));

        String[] des = { "Zurich", "Lahore", "Geneva", "Sydney", "Moscow", 
"Stockholm", "Cali", "Rome" };
        int index = (int) (Math.random() * 8);
         Rdest = des[index];
        dest.sendKeys(des[index]);
        System.out.println(index);
        //Char d =dest.charAt(index);
        System.out.println("Randomly selected destination:"+Rdest);
        Thread.sleep(5000);
        //dest.sendKeys(Keys.ARROW_DOWN);
        dest.sendKeys(Keys.RETURN);
        Thread.sleep(2000);


        System.out.println(Rdest);

        System.out.println("Destination Selected");
        //private static String Destval = Rdest;
        return Rdest;
    }

Am storing the destination value in Rdest Variable

As i dont want to run the entire above function, i store only the Rdest value in a separate function DestinationVal in Variable in the name of Destination as below

public String DestinationVal()
{
    String Destination = Rdest;
    System.out.println("Destination function value="+Destination);
    return Destination;
}

Kindly Guide me how i can use this Destination value in Search Result class

    public void SelectDate()
    {
        //Selecting Departure Date
        DateFormat dateFormat = new SimpleDateFormat("dd");
        Date date = new Date();
        String Dd=dateFormat.format(date);
        System.out.println(dateFormat.format(date));
        System.out.println(date);
        driver.findElement(By.xpath("//div[contains(text(),'Select Departure 



Date')]/following::a[contains(text(),'"+dateFormat.format(date)+"')]"))
.click();

        //Selecting Return Date
        int Dr= Integer.parseInt(Dd);
        int abc = (int) (Math.random() * 5);
        Dr= Dr+abc;
        System.out.println("Number of days increased:"+Dr);
        String Dr1 = Integer.toString(Dr);
        driver.findElement(By.xpath("//div[contains(text(),'Select Return 
Date')]/following::a[contains(text(),'"+Dr1+"')]")).click();

    } '

SearchResult Class:

public class SearchResult extends MainSite {
//@Test (Dataprovider="Destination")
public void Result() throws InterruptedException 
{

    // Waiting for the search result to get displayed
            Thread.sleep(10000);
            //Calling Homepage to use destination for comparition
            HomePage hp1 = new HomePage(driver);
            String returnVal = Destination;
            //System.out.println(returnVal);
            //Validating searched source
            String Src = 
driver.findElement(By.xpath("//span[contains(text(),'Flexible with 
')]/following::div[@class='loc'][1]/span[1]")).getText();
            //System.out.println(Src);
            if(Src.equals("Colombo"))
            { System.out.println("Search result match source location" );}
            else {System.out.println("Source locatoin is not match on second 
page");}
            String Dest = 
driver.findElement(By.xpath("//span[contains(text(),'Flexible with 
')]/following::span[contains(text(),'"+returnVal+"')][1]")).getText();
            //System.out.println(Dest);
            Thread.sleep(1000);
            if (Dest.toLowerCase().contains(returnVal)) 
{System.out.println("Search Result match Destination location");}
            else {System.out.println("Destination locatoin is not match on 
second page");}

            // Clicking on first book now button from the search result
            driver.findElement(By.xpath("//span[contains(text(),'Flexible 
with ')]/following::a[@class='btn-book'][1]")).click();
}

You can apply this logic:

Class TestA
{
    public void testMethod()
    {
    String testvalue = "XXXXXX"; 
    }    
}

Here testvalue is the variable to which you want to pass, The destination class, in which you want to use value of Base class:

You can retrieve it by :

TestA OBJ = new TestA();
System.out.println(OBJ.testvalue); 

Create in Your MainSite which You extend in both classes create getter/setter for destination:

private static String destination;

public String getDestination() {
    return destination;
}

public void setDestination(String destination) {
    this.destination = destination;
}

so You can do following:

HomePage homePage = new HomePage();
homePage.setDestination(homePage.SelectDestination()); //this will return Your random destination and store it in MainSite with get/set

than simply call

SearchResult searchResult = new SearchResult();
searchResult.getDestination();

I hope I got to bottom of a problem. But my suggestion is that You put all of Your pages into PageObject design pattern, check this page https://martinfowler.com/bliki/PageObject.html , and You will have cleaner code and easy to maintain.

You need to do the below 3 Steps in Home page Class.

  1. Create one private variable for the destination
  2. Create one public method to return the Destination variable value
  3. Update the destination variable value in your test method(after extracting the value)

SearchResult:

  1. Create on Object for the HomePage class as HomePage homepage=new HomePage();
  2. Access the getDestinationVariable method using the HomePage class Object as homepage.getDestinationValue();

Code needs to be added in HomePage Class:

//add it as instance variable
private String destinationValue;

public getDestinationValue(){
     return destinationValue;
}

public String SelectDestination() throws InterruptedException{
    -- etc ---
   destinationValue=Rdest;
   return Rdest;
}

SearchResult : Below code needs to be added in search result class

HomePage homepage=new HomePage();
homepage.getDestinationValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM