如何在TestNg类

时间:2016-01-30 04:05:34

标签: java selenium webdriver testng

我无法在网上的任何地方找到一个不同的答案。

我有多个TestNg类来运行测试,BrowserFunctions,登录,搜索,过滤(测试亚马逊的练习)。我还有一个BrowserLauncher类,它根据浏览器名称和testng.xml文件返回相应的webdriver。

BrowserFunctions.java

public class BrowserFunctions {

BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();

@BeforeSuite
public void initialioseBrowser() {
    driver = bl.launchBrowser("Firefox");
}

@Parameters({ "URL" })
@BeforeSuite
public void invokeURL(String URL) {
    driver.get(URL);
}

@AfterSuite
public void closeBrowser() {
    driver.close();
}

Login.java

public class Login {

BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();

@Parameters({ "email", "password" })
@Test
public void logInTest(String email, String passowrd) {
    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKsignInCTA), "Sign in CTA visible");
    CommonFunctions.clickButton(driver, PageElements.amzUKsignInCTA);
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKEmailField), "Email field visible");
    CommonFunctions.inputToField(driver, PageElements.amzUKEmailField, email);
    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKPasswordField),
            "Password field visible");
    CommonFunctions.inputToField(driver, PageElements.amzUKPasswordField, passowrd);
    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSignInButton),
            "Sign in button visible");
    CommonFunctions.clickButton(driver, PageElements.amzUKSignInButton);
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    Assert.assertEquals(driver.getCurrentUrl(), "https://www.amazon.co.uk/?ref_=nav_ya_signin&");
}

Search.java

public class Search {

BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();

@Parameters({ "searchTerm" })
@Test
public void searchTest(String searchTerm) {
    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSearchField),
            "Search field visible");
    CommonFunctions.inputToField(driver, PageElements.amzUKSearchField, searchTerm);
    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSearchButton),
            "Search button visible");
    CommonFunctions.clickButton(driver, PageElements.amzUKSearchButton);
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKResultContainer),
            "Results container visible");
    if (driver.findElements(PageElements.amzUKResultContainer).size() > 0) {
        List<WebElement> resultContainerList = driver.findElements(PageElements.amzUKResultContainer);
        for (WebElement w : resultContainerList) {
            if (w.findElements(PageElements.amzUKResultTitle).size() > 0) {
                if (w.findElement(PageElements.amzUKResultTitle).getText().contains(searchTerm)) {
                } else {
                    sb.append(w.findElement(PageElements.amzUKResultTitle).getText() + " does not contain"
                            + searchTerm + "\n");
                }
            }
            Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKResultImage),
                    "Result image visible");
            if (w.findElements(PageElements.amzUKResultImage).size() > 0) {
            } else {
                sb.append(w.findElement(PageElements.amzUKResultTitle).getText() 
                        + " does not contain an image\n");
            }
            Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKResultPrice),
                    "Result price visible");
            if (w.findElements(PageElements.amzUKResultPrice).size() > 0) {
                if (w.findElement(PageElements.amzUKResultPrice).getText().contains("£")) {
                } else {
                    sb.append(w.findElement(PageElements.amzUKResultTitle).getText() 
                            + " does not contain a price\n");
                }
            }
        }
    }
    System.out.println("searchTest(" + searchTerm + ") Failures:\n" + sb.toString());
}

Filter.java 公共类Filter {

BrowserLauncher bl = new BrowserLauncher();
WebDriver driver;
StringBuilder sb = new StringBuilder();

@Test
public void filterTest() {
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    List<String> filterOptionsList = new ArrayList<String>();

    sb.append(CommonFunctions.clickButton(driver, PageElements.amzUKFilterSeeMore));

    Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKFilterOptions),
            "Filter options visible");
    for (int i = 0; i < driver.findElements(PageElements.amzUKFilterOptions).size(); i++) {
        filterOptionsList.add(driver.findElements(PageElements.amzUKFilterOptions).get(i).getText());
    }

    for (String s : filterOptionsList) {
        Assert.assertTrue(CommonFunctions.checkVisibility(driver, By.partialLinkText(s)), "" 
                + s + " link visible");
        if (driver.findElements(By.partialLinkText(s)).size() > 0) {
            driver.findElement(By.partialLinkText(s)).click();
        }else {
            sb.append("Link " + s + " not visible");
            continue;
        }
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKFilterAnyCategory),
                "\"Any Category\" button visible");
        CommonFunctions.clickButton(driver, PageElements.amzUKFilterAnyCategory);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        sb.append(CommonFunctions.clickButton(driver, PageElements.amzUKFilterSeeMore));
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }
    System.out.println("filterTest Failures:\n" + sb.toString());
}

BrowserLauncher.java

public WebDriver launchBrowser(String BrowserName) {
    if(BrowserName.equalsIgnoreCase("Firefox")) {
        driver = new FirefoxDriver();
        driver.manage().window().maximize();
    } else if(BrowserName.equalsIgnoreCase("IE")) {
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "");
        System.setProperty("webdriver.ie.driver", "C:\\Eclipse EE x86 Workspace\\ResidentAdvisorLabels\\IEDriverServer.exe");
        driver = new InternetExplorerDriver(capabilities);
        driver.get("javascript:document.getElementById('overridelink').click();");
    } else if(BrowserName.equalsIgnoreCase("Chrome")) {
        ChromeOptions op = new ChromeOptions();
        op.addArguments("--user-data-dir=C:\\Users\\Bernard\\Desktop\\Selenium Data");
        op.addArguments("--start-maximized");
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        System.setProperty("webdriver.chrome.driver", "C:\\Eclipse EE x86 Workspace\\ResidentAdvisorLabels\\chromedriver.exe");
        driver = new ChromeDriver(op);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    } else if(BrowserName.equalsIgnoreCase("PhantomJS")) {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("takesScreenshot", false);
        String d = "\\";
        capabilities.setCapability("phantomjs.binary.path", "C:"+d+"Eclipse EE x86 Workspace"+d+"phantomjs-2.0.0-windows"+d+"bin"+d+"phantomjs.exe");
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setCapability("load-images", false);
        driver = new PhantomJSDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    }

    return driver;
}

的testng.xml

<suite name="Suite1" verbose="1">
<parameter name="searchTerm" value="Selenium Webdriver" />
<parameter name="URL" value="Http://www.amazon.co.uk" />
<parameter name="email" value="scrubbed" />
<parameter name="password" value="scrubbed" />
<test name="AmazonUKTesting">
    <classes>
        <class name="tests.amazonUKTests.BrowserFunctions" />
        <class name="tests.amazonUKTests.Login" />
        <class name="tests.amazonUKTests.Search" />
        <class name="tests.amazonUKTests.Filter" />
    </classes>
</test>

我的问题是,我似乎无法将返回到BrowserFunctions.java类的WebDriver传递给我的测试套件中的其他类,而无需在每个java文件中创建新的WebDriver实例。我打算打开浏览器,打开URL,然后在同一浏览器窗口中一个接一个地运行3个测试,并在完成后关闭浏览器。

5 个答案:

答案 0 :(得分:1)

是的,可以在多个类中使用相同的驱动程序实例,而无需每次都关闭浏览器窗口。 抱歉没有太多时间为您的代码设置此内容。但在这里,我为你准备了一个快速的例子。这肯定会有所帮助。

使用BrowserFunctions.java作为基类。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;

public class BrowserFunctions {
public static WebDriver driver;
StringBuilder sb = new StringBuilder();

@BeforeSuite
public void initialioseBrowser() {
driver = new FirefoxDriver();
}

@AfterSuite
public void closeBrowser() {
driver.quit();
}
}

在其他两个类中继承此类: 例如,Google.java

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;

public class Google extends BrowserFunctions{

@Test
public void google() throws InterruptedException{
driver.get("https://www.google.com");

WebDriverWait wait = new WebDriverWait(driver, 30); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("lst-ib"))); 

driver.findElement(By.id("lst-ib")).sendKeys("Bello");
Thread.sleep(5000);

}
}

和FB.java

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;

public class FB extends BrowserFunctions{

@Test
public void google() throws InterruptedException{

driver.get("https://www.fb.com");
WebDriverWait wait = new WebDriverWait(driver, 30); 

Thread.sleep(5000);
System.out.println("Title"+driver.getTitle());
System.out.println("URL"+driver.getCurrentUrl());

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("day"))); 

Select day= new Select(driver.findElement(By.id("day")));
day.selectByVisibleText("10");

Select month= new Select(driver.findElement(By.id("month")));
month.selectByVisibleText("Jan");

Select year= new Select(driver.findElement(By.id("year")));
year.selectByVisibleText("1950");


}
}

和你的Testng.xml有点像这样:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite1" verbose="1">
<test name="Test">
<classes>
    <class name="Google" />
    <class name="FB" />
</classes>
</test>
</suite>

在您的系统上尝试一次,然后使用您的代码尝试类似的内容。应该有帮助! 很抱歉在很多地方使用Thread.sleep,你不应该经常使用它。 :)

答案 1 :(得分:1)

您可以像其他人建议的那样扩展基类,也可以使用TestNG Guice dependency injection。 e.g:

TestModule.class

import com.google.inject.Binder;
import com.google.inject.Module;

public class TestModule implements Module {
    @Override
    public void configure(Binder binder) {
        BrowserLauncher bl = new BrowserLauncher();
        WebDriver driver = bl.launchBrowser("Firefox");
        binder.bind(WebDriver.class).toInstance(driver);
    }
}

BrowserFunctions.java

import com.google.inject.Inject;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Guice;
import org.testng.annotations.Parameters;

@Guice(modules = {TestModule.class})
public class BrowserFunctions {
    @Inject
    WebDriver driver;

    @Parameters({ "URL" })
    @BeforeSuite
    public void invokeURL(String URL) {
        driver.get(URL);
    }

    @AfterSuite
    public void closeBrowser() {
        driver.close();
    }
}

Login.java

import com.google.inject.Inject;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

import java.util.concurrent.TimeUnit;

@Guice(modules = {TestModule.class})
public class Login {
    @Inject
    WebDriver driver;
    StringBuilder sb = new StringBuilder();

    @Parameters({ "email", "password" })
    @Test
    public void logInTest(String email, String passowrd) {
        Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKsignInCTA), "Sign in CTA visible");
        CommonFunctions.clickButton(driver, PageElements.amzUKsignInCTA);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKEmailField), "Email field visible");
        CommonFunctions.inputToField(driver, PageElements.amzUKEmailField, email);
        Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKPasswordField),
                "Password field visible");
        CommonFunctions.inputToField(driver, PageElements.amzUKPasswordField, passowrd);
        Assert.assertTrue(CommonFunctions.checkVisibility(driver, PageElements.amzUKSignInButton),
                "Sign in button visible");
        CommonFunctions.clickButton(driver, PageElements.amzUKSignInButton);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        Assert.assertEquals(driver.getCurrentUrl(), "https://www.amazon.co.uk/?ref_=nav_ya_signin&");
    }
}

答案 2 :(得分:0)

我们可以通过将BrowserFunctions扩展到除BrowserLauncher.java之外的所有其他类来实现这一目的。

在BrowserFunctions中

执行以下更改。

Response.BinaryWrite

将此类扩展到除BrowserLauncher.java之外的其他类,并删除“WebDriver驱动程序;”。以下是前一个

 public static WebDriver driver; //instead of WebDriver driver;
 //you can make only one before suite in that launchBrowser and navigate URL

谢谢你, 穆拉利

答案 3 :(得分:0)

只需将您的WebDriver声明更改为静态

即可

并且还会更改testng.xml的结构,如下面的示例

中所示
<suite name="SuiteName">
 <test name="Test1">
  <classes>
   <class name="Class1" />
  </classes>
 </test>
 <test name="Test2">
  <classes>
   <class name="Class2" />
  </classes>
 </test>
</suite>

答案 4 :(得分:0)

我的建议与其他人略有不同。我将创建(并且对于我的项目而言)一个数据提供程序类,该类存储Web驱动程序实例(以及其他有意义的数据)。然后,在需要时,只需致电数据提供商并索取Web驱动程序。例如:

public class MyDataProvider {
  public static WebDriver driver;
  ...
 }

public class BrowserFunctions {
  StringBuilder sb = new StringBuilder();

  @BeforeSuite
  public void initialioseBrowser() {
    MyDataProvider.driver = new FirefoxDriver();
  }

  @AfterSuite
  public void closeBrowser() {
    MyDataProvider.driver.quit();
  }
}

让此数据提供者保留Web驱动程序实例的原因应该很明显。我想到两个原因:

  1. 拥有一个集中式数据中心,从中可以获取所有有意义的数据。这样做消除了在测试类中拥有所有这些对象引用的必要。
  2. 关注点分离。您的测试课程应侧重于测试的各个方面。您的数据提供商应该关注数据管理。

我也喜欢有关使用TestNG Guice的@ mfulton26答案。因此,我将对其进行研究。