Selenium通过监听事件实现自动截图
需要继承extends TestListenerAdapter这个类
代码如下
package com.mushishi.selenium.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import com.mushishi.selenium.base.DriverBase;
import com.mushishi.selenium.testCase.login;
public class TestNGListenerScreen extends TestListenerAdapter{
@Override
public void onTestSuccess(ITestResult tr) {
super.onTestSuccess(tr);
}
@Override
public void onTestFailure(ITestResult tr) {
super.onTestFailure(tr);
System.out.println(tr);
takeScreenShot(tr);
}
private void takeScreenShot(ITestResult tr) {
login b = (login) tr.getInstance();
// driver = b.driver;
b.driver.takeScreenShot();
}
@Override
public void onTestSkipped(ITestResult tr) {
super.onTestSkipped(tr);
}
@Override
public void onTestStart(ITestResult result) {
super.onTestStart(result);
}
@Override
public void onStart(ITestContext testContext) {
super.onStart(testContext);
}
@Override
public void onFinish(ITestContext testContext) {
super.onFinish(testContext);
ArrayList<ITestResult> testsToBeRemoved = new ArrayList<ITestResult>();
// collect all id's from passed test
Set<Integer> passedTestIds = new HashSet<Integer>();
for (ITestResult passedTest : testContext.getPassedTests()
.getAllResults()) {
//logger.info("PassedTests = " + passedTest.getName());
passedTestIds.add(getId(passedTest));
}
Set<Integer> failedTestIds = new HashSet<Integer>();
for (ITestResult failedTest : testContext.getFailedTests()
.getAllResults()) {
//logger.info("failedTest = " + failedTest.getName());
int failedTestId = getId(failedTest);
// if we saw this test as a failed test before we mark as to be
// deleted
// or delete this failed test if there is at least one passed
// version
if (failedTestIds.contains(failedTestId)
|| passedTestIds.contains(failedTestId)) {
testsToBeRemoved.add(failedTest);
} else {
failedTestIds.add(failedTestId);
}
}
// finally delete all tests that are marked
for (Iterator<ITestResult> iterator = testContext.getFailedTests()
.getAllResults().iterator(); iterator.hasNext();) {
ITestResult testResult = iterator.next();
if (testsToBeRemoved.contains(testResult)) {
//logger.info("Remove repeat Fail Test: " + testResult.getName());
iterator.remove();
}
}
}
private int getId(ITestResult result) {
int id = result.getTestClass().getName().hashCode();
id = id + result.getMethod().getMethodName().hashCode();
id = id
+ (result.getParameters() != null ? Arrays.hashCode(result
.getParameters()) : 0);
return id;
}
}