0

В этом сценарии я просто хотел выполнить итерацию всей среды один за другим с помощью dataprovider или любым другим способом, который может быть возможен. Пожалуйста, смотрите мои прилагается ЕхчелКак получить URL-адрес от excel до @BeforeTest для разных Env с использованием тестирования DataDriven с помощью TestNG

excel file

Код для одной среды: LTI приведены ниже. Примечание. Тот же код повторяется для всей другой среды, просто изменяя имена классов.

public class LTI_ENV { 

    public WebDriver driver; 
    private String sTestCaseName; 
    private int iTestCaseRow; 

    @BeforeTest 
    public void beforeMethod() throws Exception { 

     DOMConfigurator.configure("log4j.xml"); 
     // Getting the Test Case name, as it will going to use in so many places 
     // The main use is to get the TestCase row from the Test Data Excel sheet 
     sTestCaseName = this.toString(); 
     // From above method we get long test case name including package and class name etc. 
     // The below method will refine your test case name, exactly the name use have used 

     //Here I want to parameterize URL for each test ,is there any method that I can do ??? 
     //My application have 3 module i.e for LTI –Env 
     //1)Account Management (need to check pass?fail) 
     //2)Prep and rating (need to check pass?fail) 
     //3)Risk Eval (need to check pass?fail) 
     sTestCaseName = Utils.getTestCaseName(this.toString()); 
     Log.startTestCase(sTestCaseName); 
     ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData,"Sheet1"); 
     iTestCaseRow = ExcelUtils.getRowContains(sTestCaseName,Constant.Col_TestCaseName); 
     driver = Utils.OpenBrowser(iTestCaseRow); 
     new BaseClass(driver); 
    } 

    @Test(priority=1) 
    public void AccountManagement() throws Exception { 
     try { 
      AccountCreation_Action.Execute(iTestCaseRow); 
      AM_SubmissionLOB_Action.Execute(iTestCaseRow); 
      AM_Classification_Action.Execute(iTestCaseRow);  
      //Verification_Action1.Execute(); 
      if (BaseClass.bResult==true) { 
       ExcelUtils.setCellData("Pass", iTestCaseRow, Constant.Col_ResultStatus); 
      } else { 
       throw new Exception("Test Case Failed because of Verification"); 
      } 
     } catch (Exception e) { 
      ExcelUtils.setCellData("Fail", iTestCaseRow, Constant.Col_ResultStatus); 
      Utils.takeScreenshot(driver, sTestCaseName); 
      // This will print the error log message 
      Log.error(e.getMessage()); 
      // Again throwing the exception to fail the test completely in the TestNG results 
      throw (e); 
     } 
    } 

    @Test(priority=2,dependsOnMethods="AccountManagement") 
    public void PrepandRating() throws Exception { 

     try { 
      GenInfopage_Action.Execute(iTestCaseRow); 
      LocationSchedulePage_Actions.Execute(iTestCaseRow); 
      PolicyCoveragePage_Action.Execute(iTestCaseRow); 
      LocationInfo_Page_Action.Execute(iTestCaseRow); 
      LocationSchedulePage_Actions.Execute(iTestCaseRow); 
      AutoVehicleCoveragePage_Action.Execute(iTestCaseRow); 
      AutoPolicyCoveragePage_Action.Execute(iTestCaseRow); 
      PremiumSummaryPage_Action.Execute(iTestCaseRow); 
      //Verification_Action2.Execute(); 

      if (BaseClass.bResult==true) { 
       ExcelUtils.setCellData("Pass", iTestCaseRow+2, Constant.Col_ResultStatus); 
      } else { 
       throw new Exception("Test Case Failed because of Verification"); 
      } 
     } catch (Exception e) { 
      ExcelUtils[enter image description here][1].setCellData("Fail", iTestCaseRow+2, Constant.Col_ResultStatus); 
      Utils.takeScreenshot(driver, sTestCaseName); 
      Log.error(e.getMessage()); 
      throw (e); 
     } 
    } 

    @Test(priority=3,dependsOnMethods="PrepandRating") 
    public void RiskEval() throws Exception { 
     //will update code for this module 
    } 

    // Its time to close the finish the test case  
    @AfterTest 
    public void afterTest() { 
     // Printing beautiful logs to end the test case 
     Log.endTestCase(sTestCaseName); 
     // Closing the driver 
     driver.quit(); //I need to close all the browser and then will launch again for other environment tests 
    } 
} 

Проблемы, которые я столкнулся являются:

  1. В приведенном выше коде я первый поиск имя случая тест в столбце Excel TestCaseName с помощью Utils.getTestCaseName(this.toString()); Поэтому здесь я могу работать только один среды вовремя.

  2. Я хочу, чтобы запустить тестовые случаи, если мой тест статус прогона RUN/В противном случае Пропущенные

Как написать этот сценарий, используя TestNG? Как и в @BeforeTest, мне нужно получить URL-адрес для каждой тестовой среды.

Ниже Вы найдете рамки, которые я реализовал: http://toolsqa.wpengine.com/selenium-webdriver/selenium-automation-hybrid-framework

+0

Почему вы не переместить эту конфигурацию из файла Excel в чем-то более доступным? – jonrsharpe

+0

На самом деле, это мой ежедневный набор Smoketest ... Для большего удобства для пользователя я хотел сохранить эту контрольную точку (Run/Norun) в файле excel. Я хотел написать набор регрессии таким образом. Есть ли какое-нибудь другое решение для этого ??? –

+0

Я также попытался сохранить все тестовые примеры Xml-файлов (i.e LTI.xml, PTE, .xml, LTQ.xml, INT.xml) в соответствующие строки excel. А затем с помощью dataprovider я взял параметр Run и XML-путь в качестве параметра. –

ответ

0
package TestNG.DataDriven; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.testng.Assert; 
import org.testng.TestNG; 
import org.testng.annotations.DataProvider; 
import org.testng.annotations.Test; 

public class XMLRun { 

    public static XSSFWorkbook book; 
    public static XSSFSheet sheet1; 
    public static int LastRow=1; 

    @Test(dataProvider="XMLFeed") 
    public static void XMLRead(String Status,String XMLPath) throws Exception{ 

     if (Status.equalsIgnoreCase("Run")){ 
      // Create object of TestNG Class 
      TestNG runner=new TestNG(); 
      // Create a list of String 
      List<String> suitefiles=new ArrayList<String>(); 

      // Add xml file which you have to execute 
      suitefiles.add(XMLPath); 
      // now set xml file for execution 
      runner.setTestSuites(suitefiles); 
      // finally execute the runner using run method 
      runner.run(); 
     } else { 
      Assert.fail("Skipped Test"); 
      //sheet1.getRow(LastRow).createCell(4).setCellValue("Not Executed"); 
      //com.ReadExcel.WriteExcel.WriteExcelSheet(LastRow, "NotExecuted", 4); 
      com.ReadExcel.Excelreadwrite.excelwrite("Not Executed", LastRow); 
     } 
     LastRow++; 
    } 

    @DataProvider(name="XMLFeed") 
    public Object[][] getData() 
    { 
     Object[][] obj=new Object[5][]; 

     File file=new File("TestData.xlsx"); 

     try { 
      InputStream is=new FileInputStream(file); 

      book=new XSSFWorkbook(is); 

      sheet1=book.getSheet("Sheet1"); 

      for (int i=0;i<sheet1.getLastRowNum()+1;i++) 
      { 
       obj[i]=new Object[2]; 
       obj[i][0]=sheet1.getRow(i+1).getCell(1). 
       getStringCellValue(); 
       obj[i][1]=sheet1.getRow(i+1).getCell(8). 
       getStringCellValue(); 
       /*String result=login(username,password); 
       sheet1.getRow(i).createCell(2).setCellValue(result);*/ 
      } 
      book.close(); 
      is.close(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return obj; 
    } 
} 

Я использовал этот путь. Он работает нормально, но я хочу, чтобы все это должно присутствовать в одном пакете .. и весь отчет testNG должен быть сгенерирован в течение одного отчета.

Вот мои testcases классы:

Image