我想 运行 与 TestNG 不同的 classes 特定方法但是每次它打开一个新的 window 当我在每个 class 中包含 beforeclass

I want to run different classes particular method from TestNG but everytime it opens a new window when i include beforeclass in each class

我想 运行 与 TestNG 不同的 classes 特定方法但是每次它打开一个新的 window 当我在每个 class 之前包含 class ] 所以我现在已经从添加和注销 class 中排除了 beforeclass 所以它可以使用相同的浏览器来 运行 休息方法但它不起作用

第一个class是登录名class,如下

public class LoginWeb {
    public WebDriver driver;
    WebDriverWait wait;
    LoginScreen loginExcel;
    @BeforeClass
    public void beforeClass (){
        System.setProperty("webdriver.chrome.driver", "D:\chromedriver.exe");
        driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("http://10.7.1.180/views/index.html#/login");
        System.out.println(driver.getTitle());
    }

    @Test (description = "Valid Credentials!")
    public void LoginWithValidWebExcelEmailAndPass() throws IOException, BiffException  {
        loginExcel= new LoginScreen(driver);
        FileInputStream fi = new FileInputStream("D:\Programs\New\Sourcesmartdata.xls");
        Workbook w = Workbook.getWorkbook(fi);
        Sheet s = w.getSheet(0);
        int z = s.getRows();
        System.out.println("no of rows------------------------:"+z);
        String email = s.getCell(0, 1).getContents();
        System.out.println("Email -----------------"+email);
        loginExcel.EnterEmail(email);
        String password= s.getCell(1, 1).getContents();
        System.out.println("Password------------------- "+password);
        loginExcel.EnterPassword(password);
        loginExcel.ClickToLogin();
        wait= new WebDriverWait(driver, 10);
        WebElement GetLogo = wait.until(ExpectedConditions.visibilityOf(loginExcel.TopRightMenu));
        String str= GetLogo.getText();
        System.out.println("Text------------"+str);
        Assert.assertEquals(str, "Source Smart");  
    }
}

第二个 class 是在此处添加我之前排除的商品 class 就好像我在 class 之前添加它会打开一个新的 window 并且这里的登录脚本是没写

public class AddCommoditiesWeb{
    WebDriver driver;
    WebDriverWait wait;
    AddCommodities addcommodity;

    @Test (description="Add Multiple Commodities!")  
    public void AddMultipleNewCommodities () throws Exception, Exception{
        addcommodity = new AddCommodities(driver);
        addcommodity.MenuCommodities();     //click left menu to open manage commodities page
        FileInputStream fi = new FileInputStream("D:\Programs\New\Sourcesmartdata.xls");
        Workbook w = Workbook.getWorkbook(fi);
        Sheet s = w.getSheet(1);
        int z=s.getRows();
        System.out.println("no of rows------------------------:"+z);
        for(int row=1; row <2; row++){
            Thread.sleep(5000);
            addcommodity.ClickAddCommodities();  // click add commodity button
            String commodityname = s.getCell(0, row).getContents();
            System.out.println("commodityname -----------------"+commodityname);
            //enterdefinecommodityTxtBox.sendKeys(commodityname);
            addcommodity.Enterdefinecommodity(commodityname);
            String grade= s.getCell(1, row).getContents();
            System.out.println("grade------------------- "+grade);
            //entergradeTxtBox.sendKeys(grade);
            String unit= s.getCell(2, row).getContents();
            System.out.println("unit------------------- "+unit);
            //enterunitTxtBox.sendKeys(unit);
            String minprice= s.getCell(3, row).getContents();
            System.out.println("min price------------------- "+minprice);
            //enterminpriceTxtBox.sendKeys(minprice);
            String maxprice= s.getCell(4, row).getContents();
            System.out.println("max price------------------- "+maxprice);
            //entermaxpriceTxtBox.sendKeys(maxprice);
            addcommodity.EnterAddCommoditiesData(grade,unit,minprice,maxprice);
        }
        wait=new WebDriverWait(driver,10);
        WebElement commodityname= wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/div[4]/div/section[2]/div[4]/d-expand-collapse[1]/div/div/div[1]/h4/a")));        
        String commoditynamejustadded= commodityname.getText();
        System.out.println("name--------------"+commoditynamejustadded);
        assertEquals(commoditynamejustadded, "Rice");
    }
}

TestNG代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Login check">
    <classes>
      <class name="SourceSmartWeb.LoginWeb"/>
      <class name = "SourceSmartWeb.AddCommoditiesWeb">
      <methods>
      <include name="AddMultipleNewCommodities"/>
      </methods>
      </class>
      <class name ="SourceSmartWeb.LogoutWeb"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

注销class:

public class LogoutWeb{
    WebDriver driver;
    //  @BeforeClass
    //  public void beforeClass (){
    //      System.setProperty("webdriver.chrome.driver", "D:\chromedriver.exe");
    //      driver=new ChromeDriver();
    //      driver.manage().window().maximize();
    //      driver.get("http://10.7.1.180/views/index.html#/login");
    //      System.out.println(driver.getTitle());
    //      super.beforeClass();
    //          
    //  }


    @Test                                                                                                       
    public void Logout() throws InterruptedException {
        LogoutScreen logout=new LogoutScreen(driver);
        logout.ClickToLogout();
    }

    @AfterClass
    public void exit(){
        driver.quit();
    }
}

它所做的是打开浏览器登录,然后什么都不做。我怎样才能让它在同一个浏览器上完成其余的活动,就像我在 class 之前添加一样,在第二个 class 它打开一个新的浏览器,然后我没有登录代码。请指导

根据您的说法,您基本上需要为每个 <test> 标记生成一个浏览器,然后在所有测试 class 中共享该浏览器。但是您不能使用 @BeforeTest@AfterTest 注释,因为您需要将继承引入图片中,并且由于这些方法每个 <test> 只执行一次,您将开始看到 NullPointerException.

所以这个想法基本上是利用 TestNG 侦听器来进行此 webdriver 实例化和清理,并让您的测试 classes/methods 只是从辅助方法中查询它们。

这是一些示例代码,显示了所有这些操作。

监听器的外观如下

package com.rationaleemotions.Whosebug.qn46239358;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;

public class WebdriverSpawner extends TestListenerAdapter {
    private static final String WEBDRIVER = "webdriver";

    @Override
    public void onStart(ITestContext testContext) {
        testContext.setAttribute(WEBDRIVER, createDriver());
    }

    @Override
    public void onFinish(ITestContext testContext) {
        getWebDriverFromContext(testContext).quit();
    }

    public static RemoteWebDriver getCurrentWebDriver() {
        ITestResult result = Reporter.getCurrentTestResult();
        if (result == null) {
            throw new IllegalStateException("Please invoke this from within a @Test annotated method");
        }
        ITestContext context = result.getTestContext();
        return getWebDriverFromContext(context);
    }

    private static RemoteWebDriver getWebDriverFromContext(ITestContext context) {
        Object object = context.getAttribute(WEBDRIVER);
        if (!(object instanceof RemoteWebDriver)) {
            throw new IllegalStateException("Encountered problems in retrieving the webdriver instance");
        }
        return (RemoteWebDriver) object;

    }

    private static RemoteWebDriver createDriver() {
        return new ChromeDriver();
    }
}

现在使用上面的监听器的测试 classes 看起来像这样(我故意保持简单,只打开一个 URL,但是如果你 运行 他们你会注意到一个浏览器打开多个 URLs。所以只有一个浏览器实例)

package com.rationaleemotions.Whosebug.qn46239358;

import org.testng.annotations.Test;

public class LoginWeb {
    @Test(description = "Valid Credentials!")
    public void LoginWithValidWebExcelEmailAndPass() {
        System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.google.com"));
    }
}
package com.rationaleemotions.Whosebug.qn46239358;

import org.testng.annotations.Test;

public class LogoutWeb {
    @Test
    public void Logout() throws InterruptedException {
        System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.facebook.com"));
    }
}
package com.rationaleemotions.Whosebug.qn46239358;

import org.testng.annotations.Test;

public class AddCommoditiesWeb {

    @Test(description = "Add Multiple Commodities!")
    public void AddMultipleNewCommodities() {
        System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.yahoo.com"));
    }

    @Test
    public void anotherTestMethod() {
        System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.ndtv.com"));
    }
}

PageLoader 实用程序 class 看起来像这样

package com.rationaleemotions.Whosebug.qn46239358;

import org.openqa.selenium.remote.RemoteWebDriver;

public final class PageLoader {

    private PageLoader() {
        //Utility class defeat instantiation
    }
    public static String loadAndGetTitle(String url) {
        RemoteWebDriver driver = WebdriverSpawner.getCurrentWebDriver();
        driver.get(url);
        return driver.getTitle();
    }
}

这是套件 xml 的样子:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46216357_Suite" verbose="2">
    <listeners>
        <listener class-name="com.rationaleemotions.Whosebug.qn46239358.WebdriverSpawner"/>
    </listeners>

    <test name="Login_check">
        <classes>
            <class name="com.rationaleemotions.Whosebug.qn46239358.LoginWeb"/>
            <class name="com.rationaleemotions.Whosebug.qn46239358.AddCommoditiesWeb">
                <methods>
                    <include name="AddMultipleNewCommodities"/>
                </methods>
            </class>
            <class name="com.rationaleemotions.Whosebug.qn46239358.LogoutWeb"/>
        </classes>
    </test>
</suite>

所以这里 @Test class 中的 none 显式调用 driver.quit()。 Webdriver 清理由侦听器管理。

只有当您想要在同一个浏览器上运行进行多项测试时,此模型才会起作用。

另一方面,您可以 NEVER 运行 您的 @Test 方法并行,因为现在您所有的测试都共享相同的浏览器。