java 如何在 Selenium Webdriver 中进行参数化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10397117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:53:26  来源:igfitidea点击:

How to do parameterization in Selenium Webdriver?

javaxmljunitwebdrivertestng

提问by Tufan

How to do parameterization in Selenium 2 (WebDriver)? I use Eclipse with maven plugins and I have no previous experience on Selenium Webdriver. When I google for it then every thing shows about testNG and JUnit. Is there any method through which we can parameterized the Webdriver?

如何在 Selenium 2 (WebDriver) 中进行参数化?我将 Eclipse 与 maven 插件一起使用,但我之前没有使用 Selenium Webdriver 的经验。当我用谷歌搜索它时,每件事都会显示关于 testNG 和 JUnit。有没有什么方法可以让我们参数化 Webdriver?

采纳答案by lionxlamb

You can use POI software from Apache or Jexcel.

您可以使用 Apache 或 Jexcel 的 POI 软件。

Check these links below,it may help you;

检查下面的这些链接,它可能对您有所帮助;

for POI

用于兴趣点

http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/

http://viralpatel.net/blogs/java-read-write-excel-file-apache-poi/

and for JExcel http://www.youtube.com/watch?v=yOGGdv8eT80

对于 JExcel http://www.youtube.com/watch?v=yOGGdv8eT80

I hope it helps you.I'm no pro either,but while trying learn Parametrization I googled and found these links.

我希望它能帮助你。我也不是专业人士,但在尝试学习参数化时,我用谷歌搜索并找到了这些链接。

回答by Pavel Janicek

I am going to make assumption - you would like to pass some parameter to the Webdriver. That can be done via two ways:

我要做一个假设——你想将一些参数传递给 Webdriver。这可以通过两种方式完成:

  1. Make class which extends Webdriver and make its constructor to have the parameter which you need to pass. However, this is the hardway, because you have to implement/override all (needed) functions from webdriver:

    public class MyWebdriver extends Webdriver{
          private String theParameter;
    
         public MyWebdriver(String parameter){
           //... initialize the Webdriver
    
           //store the parameter
           theParameter = parameter
    }
    
  2. Make your own wrapper, which will contain instance off WebDriver. That is easy(-ier). For example: In my own tests, I need to tell the Webdriver which environment I am testing. So I created my own class for the Environment:

    public class Environment{
      private String baseUrl;
      public enum NameOfEnvironment {DEV, ACC}
      private NameOfEnvironment environment;
    
      public Environment(NameOfEnvironment envName){
         environment = envName;
      }
    
      public String getBaseUrl(){
          switch (environment){
             case DEV: baseUrl = "https://10.10.11.12:9080/test/";
                       break;
             case ACC: baseUrl = "https://acceptance.our-official-site.com";
                       break;
          }
        return baseUrl;
      }
     }
    
  1. 创建扩展 Webdriver 的类并使其构造函数具有您需要传递的参数。但是,这是困难的方法,因为您必须从 webdriver 实现/覆盖所有(需要的)功能:

    public class MyWebdriver extends Webdriver{
          private String theParameter;
    
         public MyWebdriver(String parameter){
           //... initialize the Webdriver
    
           //store the parameter
           theParameter = parameter
    }
    
  2. 制作您自己的包装器,其中将包含 WebDriver 的实例。这很容易(-ier)。例如:在我自己的测试中,我需要告诉 Webdriver 我正在测试哪个环境。所以我为环境创建了自己的类:

    public class Environment{
      private String baseUrl;
      public enum NameOfEnvironment {DEV, ACC}
      private NameOfEnvironment environment;
    
      public Environment(NameOfEnvironment envName){
         environment = envName;
      }
    
      public String getBaseUrl(){
          switch (environment){
             case DEV: baseUrl = "https://10.10.11.12:9080/test/";
                       break;
             case ACC: baseUrl = "https://acceptance.our-official-site.com";
                       break;
          }
        return baseUrl;
      }
     }
    

and then I have my own WebDriver wrapper, where I initialize it like this:

然后我有我自己的 WebDriver 包装器,在那里我像这样初始化它:

public class TestUI{
      private Webdriver driver;
      private Environment env;

   public TestUI(Environment e){
       this.env = e;
       driver = new FirefoxDriver;
       driver.get(env.getBaseUrl());
   }
}

And in the test:

在测试中:

 public class TestCases{

   public static final Environment USED_ENVIRONMENT = new Environment(Environment.NameOfEnvironment.ACC);

 @Test
 public void testSomething(){
    testUI test = new testUI(USED_ENVIRONMENT);
    //.. further steps
 }
 }

回答by niharika_neo

My suggestion would be to try to use a testing framework (TestNG or Junit) which gives many more features than just parametrization. Probably a little effort in setting up the framework in the beginning will save a lot of effort when your test code grows.

我的建议是尝试使用一个测试框架(TestNG 或 Junit),它提供了比参数化更多的功能。可能一开始就设置框架的一点努力,当您的测试代码增长时会节省很多精力。

回答by shashank

public void property(){
    try {

        File file = new File("login.properties");
        FileInputStream fileInput = new FileInputStream(file);
        Properties properties = new Properties();
        properties.load(fileInput);
        fileInput.close();

        Enumeration enuKeys = properties.keys();
        while (enuKeys.hasMoreElements()) {
            String key = (String) enuKeys.nextElement();
            String value = properties.getProperty(key);
            driver.findElement(By.id(key)).sendKeys(value);
            System.out.println(key + ": " + value);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and to pass the values from the properties file use property(); in main class. and execute

并从属性文件使用 property() 传递值;在主班。并执行

回答by Ripon Al Wasim

@Parameters({ "first-name" })
@Test
public void testSingleString(String firstName) {
  System.out.println("Invoked testString " + firstName);
  assert "Cedric".equals(firstName);
}

In this code, we specify that the parameter firstName of your Java method should receive the value of the XML parameter called first-name. This XML parameter is defined in testng.xml: <-- ... -->

在此代码中,我们指定 Java 方法的参数 firstName 应接收名为 first-name 的 XML 参数的值。这个 XML 参数在 testng.xml 中定义:<-- ... -->

For more details, please visit the following: http://testng.org/doc/documentation-main.html#parameters

有关更多详细信息,请访问以下网址http: //testng.org/doc/documentation-main.html#parameters

回答by B-Gun

Here i am providing a test case that might be helpful

在这里,我提供了一个可能有用的测试用例

 package pac1;
 import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Wait;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
 import org.w3c.dom.*;

public class test extends sut  {
static WebDriver driver;
static Wait<WebDriver> wait;
  public static boolean run(WebDriver driverArg, Wait<WebDriver> waitArg)
{
    driver = driverArg;
    wait = waitArg;
   // Run all the methods and return false if any fails
    return (test1() );
                  } 
   private static boolean test1()
   {



  driver.get("https://accounts.google.com");

    try {
        File file = new File("emaildata.xml"); //file location should be specified correctly put your xml in the same folder of the source code.
        // Prepare XML
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(file);
        document.getDocumentElement().normalize();
        NodeList emailNodeElementList = document.getElementsByTagName("test");//test is the name of the child tag 
        for(int j=0;j<emailNodeElementList.getLength(); j++)//loop for the multiple data
    {
       String client = "The username or password you entered is incorrect. ?";
        Element emailNodeElement = (Element)emailNodeElementList.item(j);
        NodeList details = emailNodeElement.getChildNodes();
        String emailAddress=((Node) details.item(0)).getNodeValue();
        System.out.println("email :" + emailAddress);//it just prints which email is going to be parsed
        WebElement element = driver.findElement(By.cssSelector("body"));
            boolean feedBack = driver.findElement(By.cssSelector("body")).getText().contains(client);
            boolean feedbackVisible = element.isDisplayed();


    WebElement e1 = driver.findElement(By.id("Email"));//getting the location from the web
    e1.sendKeys(emailAddress);//sending keys to the server
    WebElement e3 = driver.findElement(By.id("signIn"));
    e3.click();


    if(feedBack==true){
        System.out.println(client+ "is present");
        if(feedbackVisible==true){
            System.out.println(client+ "is visible");
        }
        else{
            System.out.println(client+ "is not visible");
        }

    }
    else{
        System.out.println(client+ "is not present");

    }
    }
  }
 catch (Exception e) {e.printStackTrace();}

  return true;
  }}

回答by dfhfghfgdfghdf

/* You can pass parameters by creating two classes.
The first class, which you can call Main Class, will be public static void.
It will contain code such as:
*/
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
Parameters id = new Parameters();   //this is referring to second class
driver.findElement(By.name("q")).sendKeys(id.x);
//****************************************************************
//this is the second class [separate page] - here you can declare int or string varibale as public [so you can share them with other class while defining them]  - 
//when you make this class - don't need to add public static void

public String x = "username"
//if you look at the first page, I'm passing this string in the main script

回答by guest

public class ReadExcel {
       public String readData (String strSheetName, int strRowNo, int strCellNo) throws Exception {

              FileInputStream fis = new FileInputStream("D:\Selenium\TestData.xlsx");
              Workbook wb = WorkbookFactory.create(fis);
              Sheet sh = wb.getSheet(strSheetName);
              Row rw = sh.getRow(strRowNo);
              String val = rw.getCell(strCellNo).getStringCellValue();

              return val;

              }

}