用Selenium将testing结果写入Excel

我在这个问题上做了大量的研究,尝试了很多不同的方法,但是没有一个做我想做的,或者把它们应用到我自己的代码中的解释是非常模糊的。

我需要将testing结果(TestID,预期结果,通过或失败)导出到Excel表格中。 我目前使用TestNG和Apache POI。

我知道如何写一个excel表格,但是我绝对不知道如何写或不能通过或失败。 我目前正在使用一些不完全正常工作的代码 – 有时会写,有时候不会。 我需要最简单,最简单的方法来做到这一点,并有一个很好的解释。

我会告诉你我目前的@ @BeforeClass ,@ @AfterClass和两个@Test块。

@BeforeClass

 @BeforeClass(alwaysRun = true) public void setupBeforeSuite(ITestContext context) throws IOException { //create a new work book workbook = new HSSFWorkbook(); //create a new work sheet sheet = workbook.createSheet("Test Result"); testresultdata = new LinkedHashMap < String, Object[] > (); //add test result excel file column header //write the header in the first row testresultdata.put("1", new Object[] { "Test Step Id", "Action", "Expected Result", "Actual Result" }); } 

@AfterClass

 @AfterClass public void setupAfterSuite(ITestContext context) { //write excel file and file name is TestResult.xls Set<String> keyset = testresultdata.keySet(); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object [] objArr = testresultdata.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if(obj instanceof Date) cell.setCellValue((Date)obj); else if(obj instanceof Boolean) cell.setCellValue((Boolean)obj); else if(obj instanceof String) cell.setCellValue((String)obj); else if(obj instanceof Double) cell.setCellValue((Double)obj); } } try { FileOutputStream out =new FileOutputStream(new File("C:/Users/PathToFile/LoginCombinations.xls")); workbook.write(out); out.close(); System.out.println("Excel written successfully.."); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

@Test块:

 @Test(priority=0) public void successfulLogin() throws InterruptedException { Properties prop = new Properties(); InputStream config = null; InputStream signinpage; try { // First we iterate over and read the config file config = new FileInputStream("C:/Users/PathToFile/src/ConfigFiles/config"); prop.load(config); signinpage = new FileInputStream("C:/Users/PathToFile/src/ObjectRepositories/signinpage"); prop.load(signinpage); // Next we initiate the driver, and navigate to the Web Application driver = new FirefoxDriver(); driver.get(prop.getProperty("url")); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Now we run the first step, "enterValidCredentials" // In this test, this is actually the only step. LoginPage.enterValidCredentials.run(driver); // Assert that we landed on the Product Select page. // assertEquals(driver.findElement(By.xpath(prop.getProperty("tempproductselect"))).getText(), "SELECT PRODUCT"); try{ assertEquals(driver.findElement(By.xpath(prop.getProperty("tempproductselect"))).getText(), "SELECT PRODUCT"); //add pass entry to the excel sheet testresultdata.put("2", new Object[] {1d, "User can login with a valid username and password", "Login successful","Pass"}); } catch(Exception e) { //add fail entry to the excel sheet testresultdata.put("2", new Object[] {1d, "User can login with a valid username and password", "Login successful","Fail"}); } // Write the test result to the sheet. driver.close(); Alert alert = driver.switchTo().alert(); alert.accept(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (config != null) { try { config.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test(priority=1) public void invalidCredentialsOne() throws InterruptedException { Properties prop = new Properties(); InputStream config = null; InputStream signinpage; try { // First we iterate over and read the config file config = new FileInputStream("C:/Users/PathToFile/src/ConfigFiles/config"); prop.load(config); signinpage = new FileInputStream("C:/Users/PathToFile/src/ObjectRepositories/signinpage"); prop.load(signinpage); // Next we initiate the driver, and navigate to the Web Application WebDriver driver; driver = new FirefoxDriver(); driver.get(prop.getProperty("url")); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // Now we run the first step, "invalidCredentialsOne" // In this test, this is actually the only step. LoginPage.invalidCredentialsOne.run(driver); Thread.sleep(5000); try{ assertEquals(driver.findElement(By.xpath(prop.getProperty("failedlogin"))).getText(), "LOG IN"); //add pass entry to the excel sheet testresultdata.put("3", new Object[] {2d, "User should not be able to login with an invalid password", "Login failed","Pass"}); } catch(Exception e) { //add fail entry to the excel sheet testresultdata.put("3", new Object[] {2d, "User should not be able to login with an invalid password", "Login failed","Fail"}); } // Write the test result to the sheet. // After the test, we close the driver. driver.close(); Alert alert = driver.switchTo().alert(); alert.accept(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (config != null) { try { config.close(); } catch (IOException e) { e.printStackTrace(); } } } } 

第二个testing,invalidCredentialsOne,永远不会写入Excel,无论是否通过或失败。

Java对我来说也是新的,所以请原谅任何格式/行话/我在里面的任何错误。 我非常开放的build议,我正在努力改善。

这是我看到的结构:

1)你有一个定义了DriverFactory的部分。

 public class BrowserFactory { public static WebDriver localDriver(Capabilities capabilities) { String browserType = capabilities.getBrowserName(); if (browserType.equals("firefox")) return new FirefoxDriver(capabilities); if (browserType.startsWith("internet explorer")) return new InternetExplorerDriver(capabilities); if (browserType.equals("chrome")) return new ChromeDriver(capabilities); throw new Error("Unrecognized browser type: " + browserType); } 

然后,您可以随时在需要的时候初始化它:例如:

 driver = BrowserFactory.localDriver(DesiredCapabilities.firefox()); 

2)你的testingclass,你在哪里使用这个工厂。 那么在@BeforeClass注解中就不需要了。 你在这些类中编写testing。 在每一个testing结束时,你都会断言(如果testing结果不合格或不合格)。 要检查testing是否通过,请使用Assert.true(); 例如:我在login时使用wrokg凭证,出现allert:Wrong Password。

解决scheme:你创build一个Assert.true(errorMessagePresent)

3)你的输出作家类 – 使其可用于您的testing

3)在testing通过的情况下 – 使用缓冲区读取器将所需的string添加到输出中,否则引发exception