使用 Selenium 将测试结果写入 Excel
Writing Test Results to Excel using Selenium
我对这个问题做了很多研究并尝试了很多不同的方法,但是 none 其中的方法符合我的要求,或者将它们实现到我自己的代码中的解释非常模糊.
我需要将测试结果(TestID、预期结果、通过或失败)导出到 excel sheet。我目前正在使用 TestNG 和 Apache POI。
我知道如何写入 excel sheet,但我完全不知道如何写入,无论是否通过或失败。我目前正在使用一些不能完全工作的代码——有时它会写,有时不会。我需要最简单易行的方法,并提供很好的解释。
我将向您展示我当前的 @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 对我来说也是新的,所以请原谅我在那里的任何 formatting/lingo/whatever 错误。我很虚心接受建议,我正在努力改进。
这是我看到的结构:
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) 你的测试 classes,你在哪里使用这个工厂。那么就不需要@BeforeClass注解了。您在那些 classes 中编写测试。在每次测试结束时,您都会做出断言(测试结果是否失败)。要检查测试是否通过,请使用 Assert.true();
示例:我在登录时使用 wrokg 凭据,会出现警告:密码错误。
解决方案:你制作一个 Assert.true(errorMessagePresent)
3) 您的输出编写器 class - 使其可用于您的测试
3) 如果测试通过 - 使用缓冲区 reader 添加您想要的字符串到输出,否则抛出异常
我对这个问题做了很多研究并尝试了很多不同的方法,但是 none 其中的方法符合我的要求,或者将它们实现到我自己的代码中的解释非常模糊.
我需要将测试结果(TestID、预期结果、通过或失败)导出到 excel sheet。我目前正在使用 TestNG 和 Apache POI。
我知道如何写入 excel sheet,但我完全不知道如何写入,无论是否通过或失败。我目前正在使用一些不能完全工作的代码——有时它会写,有时不会。我需要最简单易行的方法,并提供很好的解释。
我将向您展示我当前的 @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 对我来说也是新的,所以请原谅我在那里的任何 formatting/lingo/whatever 错误。我很虚心接受建议,我正在努力改进。
这是我看到的结构:
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) 你的测试 classes,你在哪里使用这个工厂。那么就不需要@BeforeClass注解了。您在那些 classes 中编写测试。在每次测试结束时,您都会做出断言(测试结果是否失败)。要检查测试是否通过,请使用 Assert.true(); 示例:我在登录时使用 wrokg 凭据,会出现警告:密码错误。
解决方案:你制作一个 Assert.true(errorMessagePresent)
3) 您的输出编写器 class - 使其可用于您的测试
3) 如果测试通过 - 使用缓冲区 reader 添加您想要的字符串到输出,否则抛出异常