使用Selenium将测试结果写入Excel

时间:2015-10-21 14:23:18

标签: java excel selenium apache-poi testng

我已经对这个问题进行了大量的研究,尝试了很多不同的方法,但是没有一个方法可以做到我喜欢的,或者在我自己的代码中实现它们的解释真的很模糊。 / p>

我需要将测试结果(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();
                }

            }
        }

    }

第二个测试,invalidCredentialsOne,永远不会写入excel,无论是通过还是失败。

Java对我来说也是新手,所以请原谅我在那里遇到的任何格式/行话/错误。我非常豁达地建议,我正在努力改进。

1 个答案:

答案 0 :(得分:2)

以下是我看到的结构:

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)您使用此工厂的测试类。然后在@BeforeClass注释中就没有必要了。您在这些类中编写测试。并且在每次测试结束时,您都会进行断言(如果测试结果失败或未成功)。要检查测试是否通过,请使用Assert.true(); 示例:我在登录时使用wrokg凭据,ifrt:错误密码将出现。

解决方案:您创建了一个Assert.true(errorMessagePresent)

3)您的输出编写器类 - 使其可以进行测试

3)如果测试通过 - 你使用缓冲读取器将你想要的字符串添加到输出中,否则你会抛出异常