【问题标题】:How to do parameterization in Selenium Webdriver?如何在 Selenium Webdriver 中进行参数化?
【发布时间】:2012-05-01 11:37:05
【问题描述】:

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

【问题讨论】:

    标签: java xml junit webdriver testng


    【解决方案1】:

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

    1. 制作扩展 Webdriver 的类并使其构造函数具有您需要传递的参数。然而,这是 hard 方式,因为您必须从 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;
        }
       }
      

    然后我有自己的 WebDriver 包装器,我将其初始化如下:

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

    在测试中:

     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
     }
     }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        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();
            }
        }
        

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

        【讨论】:

          【解决方案4】:
          @Parameters({ "first-name" })
          @Test
          public void testSingleString(String firstName) {
            System.out.println("Invoked testString " + firstName);
            assert "Cedric".equals(firstName);
          }
          

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

          如需了解更多详情,请访问以下网址: http://testng.org/doc/documentation-main.html#parameters

          【讨论】:

          • 您可以使用 JUnit 或 TestNG 作为测试框架。你想用什么?我更喜欢TestNG。如果您使用 TestNG,则需要制作一个 XML 文件,例如testng.xml,你可以使用TestNG的@Parameters注解来指定要参数化的数据(在上面的sn-p代码中已经提到过
          【解决方案5】:

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

           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;
            }}
          

          【讨论】:

            【解决方案6】:
            /* 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
            

            【讨论】:

              【解决方案7】:
              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;
              
                            }
              
              }
              

              【讨论】:

              • 字符串用户名 = read.readData("Sheet1", 1, 2); driver.findElement(By.id("ap_email")).sendKeys(用户名); driver.findElement(By.id("continue")).click(); String Password = read.readData("Sheet1", 1, 3); driver.findElement(By.id("ap_password")).sendKeys(Password);
              • 感谢您对 SO 的贡献。请花点时间访问SO Answering Help。你应该解释为什么你认为这是一个正确的答案
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-05-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-05-17
              • 1970-01-01
              相关资源
              最近更新 更多