Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用SeleniumWebDriver、SeleniumGrid和testNG运行并行测试_Java_Selenium_Testng_Remotewebdriver_Selenium Grid2 - Fatal编程技术网

Java 使用SeleniumWebDriver、SeleniumGrid和testNG运行并行测试

Java 使用SeleniumWebDriver、SeleniumGrid和testNG运行并行测试,java,selenium,testng,remotewebdriver,selenium-grid2,Java,Selenium,Testng,Remotewebdriver,Selenium Grid2,这是我在SO的第一篇帖子;我是一个新手Selenium用户,具有Java初学者技能 向您介绍我们的工作背景;我们正在使用页面对象模型。我们所有的测试都使用一个数据提供程序方法,该方法根据调用/使用数据提供程序的测试用例名称从“.xlsx”文件中获取数据 但是,我们不确定是否已按其应有的方式声明了我们的ThreadLocal。而且,我们不确定我们的getDriver()方法的声明是否正确。另一个问题是,我们不确定是否应该在设置和拆卸方法中使用“@BeforeTest”/“@posterest”或“

这是我在SO的第一篇帖子;我是一个新手Selenium用户,具有Java初学者技能

向您介绍我们的工作背景;我们正在使用页面对象模型。我们所有的测试都使用一个数据提供程序方法,该方法根据调用/使用数据提供程序的测试用例名称从“.xlsx”文件中获取数据

但是,我们不确定是否已按其应有的方式声明了我们的ThreadLocal。而且,我们不确定我们的getDriver()方法的声明是否正确。另一个问题是,我们不确定是否应该在设置拆卸方法中使用“@BeforeTest”/“@posterest”“@BeforeClass”/“@AfterClass”

遇到以下问题:

  • 一个测试失败,后续测试也失败
  • 有时提取的测试数据不准确(抛出的列数据比预期的多)

  • 这是我们的CONFIGTESTBASE类:

    公共类ConfigTestBase{
    私有静态ThreadLocal threadedDriver=null;
    私有静态XSSFSheet ExcelWSheet;
    私有静态XSSF工作簿ExcelWBook;
    专用静态XSSFCell小区;
    私有静态XSSFRow行;
    私有静态最终字符串路径_TestData=GlobalConstants.testDataFilePath;
    私有静态最终字符串文件_TestData=GlobalConstants.testDataFileName;
    @参数({“objectMapperFile”})
    @套房前
    public void setupSuite(字符串objectMapperFile)引发异常{
    GlobalConstants.objectMapperDefPath=新文件(objectMapperFile).getAbsolutePath();
    新的Common().OverrideSSLHandshakeException();
    }
    @参数({“browserName”})
    @课前
    公共无效设置(字符串browserName)引发异常{
    threadedDriver=新的ThreadLocal();
    DesiredCapabilities=新的DesiredCapabilities();
    if(browserName.toLowerCase()包含(“firefox”)){
    capabilities=DesiredCapabilities.firefox();
    Capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS,true);
    setBrowserName(“firefox”);
    setPlatform(Platform.WINDOWS);
    }
    if(browserName.toLowerCase()包含(“ie”)){
    System.setProperty(“webdriver.ie.driver”,“C:\\selenium\\IEDriverServer.exe”);
    capabilities=DesiredCapabilities.internetExplorer();
    setCapability(InternetExplorerDriver.import通过忽略安全域来引入片状结构,true);
    capabilities.setCapability(InternetExplorerDriver.FORCE\u CREATE\u进程,false);
    功能。setBrowserName(“internet explorer”);
    setPlatform(Platform.WINDOWS);
    }
    如果(browserName.toLowerCase()包含(“chrome”)){
    System.setProperty(“webdriver.chrome.driver”,“C:\\selenium\\chromedriver.exe”);
    能力=DesiredCapabilities.chrome();
    Capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS,true);
    能力。setBrowserName(“chrome”);
    setPlatform(Platform.WINDOWS);
    }
    if(browserName.toLowerCase().contains(“safari”)){
    SafariOptions=new SafariOptions();
    options.setUseCleanSession(true);
    capabilities=DesiredCapabilities.safari();
    能力。设置能力(SafariOptions.CAPABILITY,选项);
    能力。setBrowserName(“safari”);
    setPlatform(Platform.WINDOWS);
    }
    set(新的RemoteWebDriver(新的URL(GlobalConstants.GRIDHUB),功能));
    }
    受保护的静态RemoteWebDriver getDriver(){
    RemoteWebDriver=null;
    试一试{
    driver=threadedDriver.get();
    }捕获(例外e){
    e、 printStackTrace();
    }
    返回驱动器;
    }
    @下课
    public void tearDown()引发异常{
    getDriver().quit();
    }
    //此方法用于设置文件路径,若要打开Excel文件,请将Excel路径和Sheetname作为参数传递给此方法
    公共void setExcelFile(字符串路径、字符串名称)引发异常{
    试一试{
    //打开Excel文件
    FileInputStream ExcelFile=新的FileInputStream(路径);
    //访问所需的测试数据表
    ExcelWBook=新XSSF工作簿(ExcelFile);
    ExcelWSheet=ExcelWBook.getSheet(SheetName);
    }捕获(例外e){
    投掷(e);
    }
    }
    //这种方法是从Excel单元格中读取测试数据,在这种情况下,我们将参数传递为Row num和Col num
    @抑制警告(“静态访问”)
    公共字符串getCellData(int RowNum,int ColNum)引发异常{
    试一试{
    单元格=空;
    Cell=ExcelWSheet.getRow(RowNum).getCell(ColNum);
    Cell.setCellType(Cell.Cell\u TYPE\u字符串);
    返回Cell.getStringCellValue();
    }捕获(例外e){
    返回“”;
    }
    }
    //此方法是在Excel单元格中写入,Row num和Col num是参数
    @抑制警告(“静态访问”)
    public void setCellData(字符串textValue、int RowNum、int ColNum)引发异常{
    试一试{
    Row=ExcelWSheet.getRow(RowNum);
    Cell=Row.getCell(ColNum,Row.RETURN\u BLANK\u AS\u NULL);
    if(单元格==null){
    Cell=Row.createCell(ColNum);
    Cell.setCellValue(textValue);
    }否则{
    Cell.setCellValue(textValue);
    }
    //常量变量测试数据路径和测试数据文件名
    FileOutputStream fileOut=新的FileOutputStream(路径\测试数据+文件\测试数据);
    ExcelWBook.wr
    
    public class ConfigTestBase {
    
        private static ThreadLocal<RemoteWebDriver> threadedDriver = null;
        private static XSSFSheet ExcelWSheet;
        private static XSSFWorkbook ExcelWBook;
        private static XSSFCell Cell;
        private static XSSFRow Row;
        private static final String Path_TestData = GlobalConstants.testDataFilePath;
        private static final String File_TestData = GlobalConstants.testDataFileName;
    
        @Parameters({"objectMapperFile"})
        @BeforeSuite
        public void setupSuite(String objectMapperFile) throws Exception {
            GlobalConstants.objectMapperDefPath = new File(objectMapperFile).getAbsolutePath();
            new Common().OverrideSSLHandshakeException();
        }
    
        @Parameters({"browserName"})
        @BeforeClass
        public void setup(String browserName) throws Exception {
    
            threadedDriver = new ThreadLocal<>();
    
            DesiredCapabilities capabilities = new DesiredCapabilities();
    
            if (browserName.toLowerCase().contains("firefox")) {
                capabilities = DesiredCapabilities.firefox();
                capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
                capabilities.setBrowserName("firefox");
                capabilities.setPlatform(Platform.WINDOWS);
            }
    
            if (browserName.toLowerCase().contains("ie")) {
                System.setProperty("webdriver.ie.driver","C:\\selenium\\IEDriverServer.exe");
                capabilities = DesiredCapabilities.internetExplorer();
                capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
                capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, false);
                capabilities.setBrowserName("internet explorer");
                capabilities.setPlatform(Platform.WINDOWS);
            }
    
            if (browserName.toLowerCase().contains("chrome")) {
                System.setProperty("webdriver.chrome.driver","C:\\selenium\\chromedriver.exe");
                capabilities = DesiredCapabilities.chrome();
                capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
                capabilities.setBrowserName("chrome");
                capabilities.setPlatform(Platform.WINDOWS);
            }
    
            if (browserName.toLowerCase().contains("safari")) {
                SafariOptions options = new SafariOptions();
                options.setUseCleanSession(true);
                capabilities = DesiredCapabilities.safari();
                capabilities.setCapability(SafariOptions.CAPABILITY, options);
                capabilities.setBrowserName("safari");
                capabilities.setPlatform(Platform.WINDOWS);
            }
    
            threadedDriver.set(new RemoteWebDriver(new URL(GlobalConstants.GRIDHUB), capabilities));
    
        }
    
        protected static RemoteWebDriver getDriver(){
            RemoteWebDriver driver = null;
    
            try {
                driver = threadedDriver.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return driver;
        }
    
        @AfterClass
        public void tearDown() throws Exception {
            getDriver().quit();
        }
    
        //This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
        public void setExcelFile(String Path,String SheetName) throws Exception {
            try {
                // Open the Excel file
                FileInputStream ExcelFile = new FileInputStream(Path);
    
                // Access the required test data sheet
                ExcelWBook = new XSSFWorkbook(ExcelFile);
                ExcelWSheet = ExcelWBook.getSheet(SheetName);
            } catch (Exception e) {
                throw (e);
            }
        }
    
        //This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
        @SuppressWarnings("static-access")
        public String getCellData(int RowNum, int ColNum) throws Exception{
            try{
                Cell = null;
                Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
                Cell.setCellType(Cell.CELL_TYPE_STRING);
                return Cell.getStringCellValue();
            } catch (Exception e) {
                return "";
            }
        }
    
        //This method is to write in the Excel cell, Row num and Col num are the parameters
        @SuppressWarnings("static-access")
        public void setCellData(String textValue,  int RowNum, int ColNum) throws Exception    {
            try{
                Row  = ExcelWSheet.getRow(RowNum);
                Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
                if (Cell == null) {
                    Cell = Row.createCell(ColNum);
                    Cell.setCellValue(textValue);
                } else {
                    Cell.setCellValue(textValue);
                }
    
                // Constant variables Test Data path and Test Data file name
                FileOutputStream fileOut = new FileOutputStream(Path_TestData + File_TestData);
                ExcelWBook.write(fileOut);
                fileOut.flush();
                fileOut.close();
            } catch (Exception e) {
                throw (e);
            }
        }
    
        @DataProvider(name="getDataFromFile")
        public Object[][] getDataFromFile(Method testMethod, ITestContext context) throws Exception {
    
            String[][] tabArray;
            int intCounter;
            int intRowCount = 0;
            int intRowCounter = 0;
            int intColCount = 0;
            int intColCounter;
            int intColDataCount = 0;
            int intColDataCounter = 0;
            String temp;
    
            String testName = testMethod.getName();
            String banner = context.getCurrentXmlTest().getParameter("banner");
            setExcelFile(Path_TestData + File_TestData, banner);
    
            //get number of data to be returned
            for(intCounter=0;intCounter<ExcelWSheet.getLastRowNum()+1;intCounter++){
                if(getCellData(intCounter, 1).equals(testName)) {
                    if (intColCount == 0) {
                        intColCount = ExcelWSheet.getRow(intCounter).getLastCellNum() - 2;
                    }
                    intRowCount++;
                }
            }
    
            if(intRowCount == 0){
                System.out.println("\n*** Data for '" + testName + "' was not found.");
                throw new AssertionError("Data for '" + testName + "' was not found.");
            }
    
            for(intCounter=0;intCounter<ExcelWSheet.getLastRowNum()+1;intCounter++){
                if(getCellData(intCounter, 1).equals(testName)) {
                    for(intColCounter=2;intColCounter<intColCount+2;intColCounter++) {
                        temp = getCellData(intCounter,intColCounter);
                        if(temp != null && !temp.isEmpty()){
                            intColDataCount++;
                        }
                    }
                    //to exit FOR loop
                    intCounter = ExcelWSheet.getLastRowNum()+1;
                }
            }
    
            //set data array dimension
            tabArray = new String[intRowCount][intColDataCount];
    
            for(intCounter=0;intCounter<ExcelWSheet.getLastRowNum()+1;intCounter++){
                if(getCellData(intCounter, 1).equals(testName)) {
                    intRowCounter++;
                    for(intColCounter=2;intColCounter<intColCount+2;intColCounter++) {
                        temp = getCellData(intCounter,intColCounter);
                        if(temp != null && !temp.isEmpty()){
                            tabArray[intRowCounter-1][intColDataCounter] = getCellData(intCounter,intColCounter);
                            intColDataCounter++;
                        }
                    }
                }
            }
    
            return tabArray;
    
        }
    
    }
    
    public class Google6 extends ConfigTestBase {
    
        private Generic generic = null;
        private HomePage homePage = null;
    
        @BeforeMethod
        public void MethodInit(ITestResult result) throws Exception {
            generic = new Generic(getDriver());
            homePage = new HomePage(getDriver());
        }
    
        @Test(dataProvider="getDataFromFile")
        public void Google6(String execute, String url, String searchString) throws Exception {
    
            if(execute.toUpperCase().equals("YES")) {
    
                //navigate to application page
                generic.navigateToURL(url);
    
                //search
                homePage.search(searchString);
    
            } else {
                generic.log("Execute variable <> 'YES'. Skipping execution...");
                throw new SkipException("Execute variable <> 'YES'. Skipping execution...");
            }
    
        }
    }
    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    
    <suite name="Full Test Suite - Firefox" parallel="classes" thread-count="5" verbose="1">
        <parameter name="objectMapperFile" value="mom.objectdef.properties" />
    
        <test name="Regression - Firefox">
            <parameter name="browserName" value="firefox" />
            <parameter name="banner" value="SAMPLE" />
            <classes>
                <class name="com.company.automation.web.app.testsuites.Google1" />
                <class name="com.company.automation.web.app.testsuites.Google2" />
                <class name="com.company.automation.web.app.testsuites.Google3" />
                <class name="com.company.automation.web.app.testsuites.Google4" />
                <class name="com.company.automation.web.app.testsuites.Google5" />
                <class name="com.company.automation.web.app.testsuites.Google6" />
            </classes>
        </test>
    
    </suite>
    
    private static ThreadLocal<RemoteWebDriver> threadedDriver = new ThreadLocal<>();
    
    public class CSVDataReader {
        private static final char DELIMITER = ',';
        private static final char QUOTE_CHAR = '\"';
        private static final char ESCAPE_CHAR = '\\';
    
        private static List<String[]> read(String filePath, boolean hasHeader) throws IOException {
            CSVReader reader;
    
            if (hasHeader) {
                // If file has a header, skip the header (line 1)
                reader = new CSVReader(new FileReader(filePath), DELIMITER, QUOTE_CHAR, ESCAPE_CHAR, 1);
            } else {
                reader = new CSVReader(new FileReader(filePath), DELIMITER, QUOTE_CHAR, ESCAPE_CHAR);
            }
    
            List<String[]> rows = reader.readAll();
            reader.close();
    
            return rows;
        }
    
        public static String [][] readCSVFileToString2DArray(String filePath, boolean hasHeader) throws IOException {
            List<String[]> rows = read(filePath, hasHeader);
    
            // Store all rows/columns in a two-dimensional String array, then return it
            String [][] csvData = new String[rows.size()][];
    
            int r = 0;
            for (String[] row : rows) {
                csvData[r++] = row;
            }
    
            return csvData;
        }
    }