selenium2 TestNG参数化

想要参数化,首先要加入@Parameters({"参数1","参数2"})

package com.demo.test;

import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class NewTest {
    private WebDriver driver;

    @Test
    @Parameters({ "keyword" })
    // 参数化
    public void f(String keyword) {
        By inputBox = By.id("kw");
        By searchButton = By.id("su");

        // 智能等待元素加载完成
        intelligentWait(driver, 10, inputBox);
        intelligentWait(driver, 10, searchButton);

        driver.findElement(inputBox).sendKeys(keyword);
        driver.findElement(searchButton).click();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @BeforeTest
    public void beforeTest() {
        driver = new FirefoxDriver();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://baidu.com");
    }

    @AfterTest
    public void afterTest() {
        driver.quit();
    }

    public void intelligentWait(WebDriver driver, int timeOut, final By by) {
        try {
            (new WebDriverWait(driver, timeOut))
                    .until(new ExpectedCondition<Boolean>() {
                        public Boolean apply(WebDriver driver) {
                            WebElement element = driver.findElement(by);
                            return element.isDisplayed();
                        }
                    });
        } catch (TimeoutException e) {
            Assert.fail("超时!!" + timeOut + "秒之后还没有找到元素[" + by + "]");
        }
    }
}

其中的TestNg.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
    <parameter name="keyword" value="java"/>
  <test name="Test">
    <classes>
      <class name="com.demo.test.NewTest"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

注意:如果测试代码中有需要用到参数,并且参数在xml文件中声明了,那么运行的时候一定通过xml文件来执行测试。不然参数会找不到,用例会跳过。

跳过时,会有以下这样的结果:

原文地址:https://www.cnblogs.com/yajing-zh/p/5077871.html