Selenium - Java // Передача экземпляра браузера другому методу - PullRequest
0 голосов
/ 30 января 2019

Я сейчас пытаюсь автоматизировать веб-процесс, используя Selenium, и я довольно новичок в Java и Selenium.Мой основной метод в настоящее время - открытие веб-страницы, выполнение некоторой работы над ней, а затем вызов одного из моих вспомогательных методов (который также должен работать на том же экземпляре веб-страницы excat).Вместо этого вызываемый метод открывает новый экземпляр браузера и, очевидно, в результате выдает ошибку.До сих пор мне удавалось гуглить большинство моих проблем с такими темами, но я не могу найти решение для передачи экземпляра Browser вызываемому методу.Рад за любые чаевые, которые вы можете предоставить :-)

package test;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

public classautomationtest {
public static void main(String[] args) {
    String projectLocation = System.getProperty("user.dir");
    System.setProperty("webdriver.gecko.driver", projectLocation+"\\lib\\Geckodriver\\geckodriver.exe");
    System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
    WebDriver driver = new FirefoxDriver();

    driver.navigate().to("some webside"); //didnt put the url in for this post

    //.....

    //doing loads of stuff on the webside (works perfectly fine)

    //.....

    //calling for the 2nd methode
    methode_two(value1,value2,value3,value4);

}

//this method gets called correctly, but it opens its own browser instance, even though i want it to work on the one the main method did
public static void methode_two(int value1,int value2,int value3,int value4) {

    String projectLocation = System.getProperty("user.dir");
    System.setProperty("webdriver.gecko.driver", projectLocation+"\\lib\\Geckodriver\\geckodriver.exe");
    System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
    WebDriver driver = new FirefoxDriver();

    //doing some stuff on the webside
    //just a example line:
    driver.findElement(By.cssSelector("div.field:nth-child(5) > input:nth-child(1)")).click(); //works like a charm in the main method


}

}

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

Вам необходимо передать экземпляр webDriver в качестве аргумента функции:

package test;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

public classautomationtest {
public static void main(String[] args) {
    String projectLocation = System.getProperty("user.dir");
    System.setProperty("webdriver.gecko.driver", projectLocation+"\\lib\\Geckodriver\\geckodriver.exe");
    System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
    WebDriver driver = new FirefoxDriver();

    driver.navigate().to("some website"); //didn't put the url in for this post

    //.....

    //doing loads of stuff on the website (works perfectly fine)

    //.....

    //calling for the 2nd method
    method_two(driver, value1, value2, value3, value4);

}

public static void method_two(WebDriver driver, int value1,i nt value2, int value3, int value4) {

    String projectLocation = System.getProperty("user.dir");

    //doing some stuff on the webside
    driver.findElement(By.cssSelector("div.field:nth-child(5) > input:nth-child(1)")).click(); 


}
0 голосов
/ 30 января 2019

Попробуйте следующий код:

package test;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

public class automationtest {
    static WebDriver driver;
    public static void main(String[] args) {
        String projectLocation = System.getProperty("user.dir");
        System.setProperty("webdriver.gecko.driver", projectLocation+"\\lib\\Geckodriver\\geckodriver.exe");
        System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox\\firefox.exe");
        driver = new FirefoxDriver();

        driver.navigate().to("some webside"); //didnt put the url in for this post

        //.....

        //doing loads of stuff on the webside (works perfectly fine)

        //.....

        //calling for the 2nd methode
        methode_two(value1,value2,value3,value4);

    }

    //this method gets called correctly, but it opens its own browser instance, even though i want it to work on the one the main method did
    public static void methode_two(int value1,int value2,int value3,int value4) {

        //doing some stuff on the webside
        //just a example line:
        driver.findElement(By.cssSelector("div.field:nth-child(5) > input:nth-child(1)")).click(); //works like a charm in the main method
    }
}

Вам необходимо объявить WebDriver вне метода main, чтобы он мог быть доступен и другим статическим методам, и инициализация будет происходить в методе main (), так какявляется отправной точкой для Java.Надеюсь, это поможет ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...