Файлу TestNG XML не удалось вызвать / создать XSSFWorkbook

#java #xml #selenium-webdriver #apache-poi #testng

#java #xml #selenium-webdriver #apache-poi #testng

Вопрос:

У меня есть гибридная платформа, которая выполняет операции ввода и вывода в файле Excel. Для выполнения операций я использовал Apache POI 3.9.

Когда я запускаю testng.xml файл точно останавливается при создании объекта XSSFWorkbook.

Когда я отлаживаю testng.xml он выполняется хорошо.

Где-то я пропустил логику, любезно помогите мне связаться.

Механизм тестирования

 package runner;
public class TestEngine {


protected static ExtentReports report;
public static ActionKeywords actionKeywords;
private static WebDriver screenDriver;

@BeforeTest

public void browserStartUp(){
System.setProperty("webdriver.chrome.driver",Constant.chromeDriver);
report = new ExtentReports(Constant.reportLocation,true);
}



@Parameters({ "browser" })
@Test
public void runner(String browser) throws Exception,CustomException {

 Path metapath = Paths.get(Constant.filePath Constant.metaDataFileName);
 Path testpath = Paths.get(Constant.filePath Constant.testDataFileName);

 //Check the meta data and test data file is exists.
 if(Files.exists(metapath) amp;amp; Files.exists(testpath)){  

 String executionIndicator=null,testCaseSheet_testCaseID=null,
 testCaseFlow=null,screen_testCaseID=null,
 screenName=null,allScreens[]=null;

 int noOfTestCase,testData_Rows,metaData_Rows,testData_Columns;
 ExcelUtility eUtility = new ExcelUtility();
 noOfTestCase = eUtility.getNumberOfRows(Constant.filePath,    Constant.testDataFileName, Constant.flowSheetName);
 System.out.println("Number of test case" noOfTestCase);                
}
  

Утилита Excel

 public class ExcelUtility {

private File file = null;
private FileInputStream inputStream = null;
private FileOutputStream outputStream = null;
public Workbook workbook =null;

private Sheet sheet = null;
private Row row = null;
private static Cell cell =null;

private int totalRows=0;
private int totalCols=0;

//To get the sheet name from workbook
public Sheet getSheet(String filePath,String fileName,String sheetName) throws Exception{
    try {

         workbook = readWorkbook(filePath, fileName, sheetName); 

         sheet = workbook.getSheet(sheetName);

    }
    catch(Exception ex){
        ex.getStackTrace();
        throw ex;
    }
    return sheet;
}
public void display(){
    System.out.println("Test");
}

public Workbook readWorkbook(String filePath,String fileName,String sheetName) throws Exception{
    try {
        file =    new File(filePath fileName);
        inputStream = new FileInputStream(file);     
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
          if(fileExtensionName.equals(".xlsx")){
             System.out.println("test");
             workbook = new XSSFWorkbook(inputStream);
             System.out.println("testOne");

        }
         else if(fileExtensionName.equals(".xls")){
             workbook = new HSSFWorkbook(inputStream);
        }     
    }
    catch(Exception ex){
        throw ex;
    }
    return workbook;
}

//To get the total number of row in the excel sheet
public int getNumberOfRows(String filePath,String fileName,String sheetName) throws Exception{
try {

     sheet=getSheet(filePath, fileName, sheetName);

     totalRows = sheet.getLastRowNum(); 

    }
    catch(Exception ex){
        throw ex;
    }
 return totalRows;
}
  

TestNG.XML

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Firefox Test">
   <parameter name="browser" value="firefox"/>
    <classes>
      <class name="runner.TestEngine"/>
    </classes>
  </test> <!-- Test --> 
</suite> <!-- Suite -->
  

On Run, in the read workbook method the value testone is not displayed in the console log.

But when I remove the parallel = tests from the suite tag, It works well in one by one order. It fails to work in parallel.

Exception

 org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
    at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:62)
    at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:403)
    at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:207)
    at utility.ExcelUtility.readWorkbook(ExcelUtility.java:57)
    at utility.ExcelUtility.getSheet(ExcelUtility.java:40)
    at utility.ExcelUtility.getNumberOfRows(ExcelUtility.java:73)
    at testEngine.TestEngine.main(TestEngine.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
    at org.testng.SuiteRunner.run(SuiteRunner.java:261)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
    at org.testng.TestNG.run(TestNG.java:1048)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:60)
    ... 31 more
Caused by: java.io.IOException: error: Unexpected end of file after null
    at org.apache.poi.xssf.model.StylesTable.readFrom(StylesTable.java:167)
    at org.apache.poi.xssf.model.StylesTable.<init>(StylesTable.java:92)
    ... 36 more
  

Исключение [После удаления служебного класса Static в Excel]

 org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:41)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:204)
    at utility.ExcelUtility.readWorkbook(ExcelUtility.java:65)
    at utility.ExcelUtility.getSheet(ExcelUtility.java:48)
    at utility.ExcelUtility.existingWriteExcel(ExcelUtility.java:182)
    at testEngine.TestEngine.main(TestEngine.java:213)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:774)
    at org.testng.TestRunner.run(TestRunner.java:624)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
    at org.testng.SuiteRunner.access$000(SuiteRunner.java:39)
    at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:393)
    at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
    at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:178)
    at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:269)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
    ... 25 more
  

Комментарии:

1. Что вы имеете в виду под остановкой? Выдает ли тест исключение? Не могли бы вы создать пример проекта на github?

2. Я получаю исключение типа org.apache.poi. Исключение POIXMLException: java.lang.reflect. Исключение InvocationTargetException

Ответ №1:

Ваш класс ExcelUtility является статическим, поэтому при параллельном выполнении вы получаете одновременную модификацию, потому что один и тот же экземпляр является общим для всех потоков. И именно поэтому он отлично работает без него. Таким образом, решение состоит в том, чтобы сделать ваш класс ExcelUtility без состояния или создать новый экземпляр для каждого потока (например, удалить static или сделать его ThreadLocal).

Комментарии:

1. Я удалил ключевое слово static, и оно начало работать хорошо. Отлично!

2. Я получил другое исключение под названием org.apache.poi. Исключение POIXMLException: org.apache.poi.openxml4j.exceptions. Исключение InvalidFormatException: пакет должен содержать часть типа содержимого [M1.13]

3. Я добавил исключение в вопрос.

4. не могли бы вы добавить обновленную полную версию ExcelUtility?

5. Можем ли мы поговорить через чат. Я добавил обновленный TestEngine и служебный класс Excel.