У меня были такие же проблемы, как и у вас.
Но теперь я могу делать снимки экрана и создавать PDF-файлы.
Я использовал: http://code.google.com/p/selenium-java-evidence
Пример кода такой:
Тестовый класс:
public class MantisTest {
/**
* Create a Selenium attribute
*/
static Selenium selenium = null;
/**
* Create a SeleniumServer attribute
*/
SeleniumServer server = null;
/**
* Create a list to put each evidence
*/
List<SeleniumEvidence> evidence = null;
/**
* String that will be showed if a exception occurs
*/
String exception = null;
/**
* Constructor of the class
*/
public MantisTest() {
}
/**
* Execute all code bellow and override the setup method in JUnit test case
*/
@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
// create a new instance of selenium to interact with the page
selenium = new DefaultSelenium("localhost", 4444, "*firefox3",
"http://www.mantisbt.org/");
// create a new instance of selenium server to init the server
server = new SeleniumServer();
// create a new instance of the selenium evidence list
evidence = new ArrayList<SeleniumEvidence>();
// init the selenium server
server.start();
// init the selenium
selenium.start();
}
/**
* The test case
*
* @throws Exception
*/
@Test
public void testLogin() throws Exception {
/*
* The code need a try-catch block to catch the evidence when a error
* occurs
*/
try {
selenium.windowMaximize();
selenium.open("/demo/login_page.php");
//selenium.captureScreenshot("screen-shots/"
// + System.currentTimeMillis() + ".jpg");
evidence.add(new SeleniumEvidence(
"Access the first page and click in 'Login Anonysmously'",
selenium.captureEntirePageScreenshotToString("")));
Assert.assertEquals("Login", selenium.getText("//td[1]"));
Assert.assertEquals(selenium.getTitle(), "MantisBT DEMO site9");
} catch (Exception e) {
/*
* Here is necessary catch one evidence and the exception string
*/
evidence.add(new SeleniumEvidence("An exception occured", selenium
.captureEntirePageScreenshotToString("screen-shots/"
+ System.currentTimeMillis() + ".png")));
exception = e.fillInStackTrace().getMessage();
} finally {
// In the finally block the report is created
GenerateEvidenceReport.generatePDFEvidence(evidence,
"ExampleEvidence", "Elias Nogueira",
"Selenium Evidence Test", exception);
}
}
/**
* The test case
*
* @throws Exception
*/
@Test
public void testLogin2() throws Exception {
/*
* The code need a try-catch block to catch the evidence when a error
* occurs
*/
try {
selenium.windowMaximize();
selenium.open("/demo/login_page.php");
//selenium.captureScreenshot("screen-shots/"
// + System.currentTimeMillis() + ".jpg");
evidence.add(new SeleniumEvidence(
"Access the first page and click in 'Login Anonysmously'",
selenium.captureEntirePageScreenshotToString("")));
Assert.assertEquals("Login", selenium.getText("//td[1]"));
Assert.assertEquals(selenium.getTitle(), "MantisBT DEMO site9");
} catch (Exception e) {
/*
* Here is necessary catch one evidence and the exception string
*/
evidence.add(new SeleniumEvidence("An exception occured", selenium
.captureEntirePageScreenshotToString("screen-shots/"
+ System.currentTimeMillis() + ".png")));
exception = e.fillInStackTrace().getMessage();
} finally {
// In the finally block the report is created
GenerateEvidenceReport.generatePDFEvidence(evidence,
"ExampleEvidence", "Elias Nogueira",
"Selenium Evidence Test", exception);
}
}
/**
* Execute all the code below when test case get completed
*/
@AfterClass(alwaysRun = true)
public void tearDown() {
selenium.stop();
server.stop();
}
}
testng.xml
<suite verbose="0" name="Default suite">
<listeners>
<listener class-name="com.googlecode.seleniumjavaevidence.test.ReportListener" />
</listeners>
<test verbose="2" name="Default test" preserve-order="false">
<classes>
<class name="com.googlecode.seleniumjavaevidence.test.MantisTest" />
</classes>
</test>
</suite>
Класс слушателя
<code>package com.googlecode.seleniumjavaevidence.test;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import org.testng.internal.Utils;
import org.testng.reporters.HtmlHelper;
/**
* This class implements an HTML reporter for individual tests.
*/
public class ReportListener extends TestListenerAdapter {
private static final Comparator<ITestResult> NAME_COMPARATOR= new NameComparator();
private static final Comparator<ITestResult> CONFIGURATION_COMPARATOR= new ConfigurationComparator();
private ITestContext m_testContext = null;
private File file = new File("screen-shots");
@Override
public void onTestFailure(ITestResult result) {
Reporter.setCurrentTestResult(result);
System.out.println(file.getAbsolutePath());
Reporter.log("123456789");
Reporter
.log("<a href=\"../../screen-shots/failure/"+ result.getName() + ".png\"><img src=\"../../screen-shots/failure/"+ result.getName() + ".png\" alt=\"Selenium Screenshot\" title=\"Selenium Screenshot\" width=\"200\" height=\"200\"><br></a>");
Reporter.log("987654321");
// Reporter.log("screenshot saved at " + file.getAbsolutePath()
// + "\\reports\\" + result.getName() + ".jpg");
// Reporter.log("<a href='"+file.getAbsolutePath() +"\\failure\\"+
// result.getName() + ".jpg' hight='100' width='100'/> </a>");
MantisTest.selenium.captureScreenshot(file.getAbsolutePath()
+ "\\failure\\" + result.getName() + ".png");
Reporter.setCurrentTestResult(null);
}
@Override
public void onStart(ITestContext context) {
m_testContext = context;
}
@Override
public void onFinish(ITestContext context) {
generateLog(m_testContext,
null /* host */,
m_testContext.getOutputDirectory(),
getConfigurationFailures(),
getConfigurationSkips(),
getPassedTests(),
getFailedTests(),
getSkippedTests(),
getFailedButWithinSuccessPercentageTests());
}
private static String getOutputFile(ITestContext context) {
return context.getName() + ".html";
}
public static void generateTable(StringBuffer sb, String title,
Collection<ITestResult> tests, String cssClass, Comparator<ITestResult> comparator)
{
sb.append("<table width='100%' border='1' class='invocation-").append(cssClass).append("'>\n")
.append("<tr><td colspan='4' align='center'><b>").append(title).append("</b></td></tr>\n")
.append("<tr>")
.append("<td><b>Test method</b></td>\n")
.append("<td><b>Instance</b></td>\n")
.append("<td width=\"10%\"><b>Time (seconds)</b></td>\n")
.append("<td width=\"30%\"><b>Exception</b></td>\n")
.append("</tr>\n");
if (tests instanceof List) {
Collections.sort((List<ITestResult>) tests, comparator);
}
// User output?
String id = "";
Throwable tw = null;
for (ITestResult tr : tests) {
sb.append("<tr>\n");
// Test method
ITestNGMethod method = tr.getMethod();
sb.append("<td title='").append(tr.getTestClass().getName()).append(".")
.append(tr.getName())
.append("()'>")
.append("<b>").append(tr.getName()).append("</b>");
// Test name
String testName = method.getTestClass().getTestName();
if (testName != null) {
sb.append("<br>").append("Test class:" + testName);
}
// Method description
if (! Utils.isStringEmpty(method.getDescription())) {
sb.append("<br>").append("Test method:").append(method.getDescription());
}
Object[] parameters = tr.getParameters();
if (parameters != null && parameters.length > 0) {
sb.append("<br>Parameters: ");
for (int j = 0; j < parameters.length; j++) {
if (j > 0) sb.append(", ");
sb.append(parameters[j] == null ? "null" : parameters[j].toString());
}
}
//
// Output from the method, created by the user calling Reporter.log()
//
{
List<String> output = Reporter.getOutput(tr);
if (null != output && output.size() > 0) {
sb.append("<br/>");
// Method name
String divId = "Output-" + tr.hashCode();
sb.append("\n<a href=\"#").append(divId).append("\"")
.append(" onClick='toggleBox(\"").append(divId).append("\", this, \"Show output\", \"Hide output\");'>")
.append("Show output</a>\n")
.append("\n<a href=\"#").append(divId).append("\"")
.append(" onClick=\"toggleAllBoxes();\">Show all outputs</a>\n")
;
// Method output
sb.append("<div class='log' id=\"").append(divId).append("\">\n");
for (String s : output) {
sb.append(s).append("<br/>\n");
}
sb.append("</div>\n");
}
}
sb.append("</td>\n");
// Instance
Object instance = tr.getInstance();
String instanceString = instance != null ? instance.toString() : " ";
sb.append("<td>").append(instance).append("</td>");
// Time
long time = (tr.getEndMillis() - tr.getStartMillis()) / 1000;
String strTime = new Long(time).toString();
sb.append("<td>").append(strTime).append("</td>\n");
// Exception
tw = tr.getThrowable();
String stackTrace = "";
String fullStackTrace = "";
id = "stack-trace" + tr.hashCode();
sb.append("<td>");
if (null != tw) {
String[] stackTraces = Utils.stackTrace(tw, true);
fullStackTrace = stackTraces[1];
stackTrace = "<div><pre>" + stackTraces[0] + "
";
sb.append (StackTrace);
// ссылка JavaScript
sb.append ("
")
.append («Нажмите, чтобы показать все кадры стека»). append (« \ n»)
.append ("
")
.append ( "
" + fullStackTrace + "
")
.append ( "
")
;
}
. Sb.append ( " \ п") добавить ( " \ п");
}
sb.append ( "
\ п");
}
приватная статическая строка String arrayToString (массив String []) {
StringBuffer result = new StringBuffer ("");
for (int i = 0; i \ n" +
".log {display: none;} \ n" +
".stack-trace {display: none;} \ n" +
" \ n" +
" \ n" +
"<! - \ n" +
"функция flip (e) {\ n" +
"current = e.style.display; \ n" +
"if (current == 'block') {\ n" +
"e.style.display = 'none'; \ n" +
"вернуть 0; \ n" +
"} \ n" +
"else {\ n" +
"e.style.display = 'block'; \ n" +
"возврат 1; \ n" +
"} \ n" +
"} \ n" +
"\ n" +
"function toggleBox (szDivId, elem, msg1, msg2) \ n" +
"{\ n" +
"var res = -1;" +
"if (document.getElementById) {\ n" +
"res = flip (document.getElementById (szDivId)); \ n" +
"} \ n" +
"else if (document.all) {\ n" +
"// так работают старые версии msie \ n" +
"res = flip (document.all [szDivId]); \ n" +
"} \ n" +
"if (elem) {\ n" +
"if (res == 0) elem.innerHTML = msg1; еще elem.innerHTML = msg2; \ n" +
"} \ n" +
"\ n" +
"} \ n" +
"\ n" +
"function toggleAllBoxes () {\ n" +
"if (document.getElementsByTagName) {\ n" +
"d = document.getElementsByTagName ('div'); \ n" +
"for (i = 0; i <d.length; i ++) {\ n" +
"if (d [i] .className == 'log') {\ n" +
"flip (d [i]); \ n" +
"} \ n" +
"} \ n" +
"} \ n" +
"} \ n" +
"\ n" +
"// -> \ n" +
" \ n" +
"\ П";
открытый статический void generateLog (ITestContext testContext,
Струнный хост,
String outputDirectory,
Коллекция failedConfs,
Коллекция skippedConfs,
Коллекция пройденных тестов,
Коллекция failTests,
Коллекция skippedTests,
Сборник процент тестов)
{
StringBuffer sb = new StringBuffer ();
sb.append ( " \ п \ п")
.append (" TestNG:") .append (testContext.getName ()). append (" \ n")
.append (HtmlHelper.getCssString ())
.append (головка)
.append ( " \ п")
.append ( " \ п");
Дата startDate = testContext.getStartDate ();
Date endDate = testContext.getEndDate ();
long duration = (endDate.getTime () - startDate.getTime ()) / 1000;
Int прошло =
testContext.getPassedTests (). size () +
. TestContext.getFailedButWithinSuccessPercentageTests () размер ();
int failed = testContext.getFailedTests (). size ();
int skipped = testContext.getSkippedTests (). size ();
Строка hostLine = Utils.isStringEmpty (хост)? "": "
Удаленный хост: " + хост
+ " \ n ";
С.Б.
.append ("
"). append (testContext.getName ()). append ("
")
.append ("
Файл свойств: | "). append (m_testRunner.getPropertyFileName ()). append (" |
Тесты пройдены / Не пройдены / Пропущены: | "). append (пройден) .append ("/").append (не удалось) .append ("/"). append (пропущено) .append (" |
запущено"on: | "). append (testContext.getStartDate (). toString ()). append (" |
Общее время: | "). append (duration) .append ("секунд (") .append (endDate.getTime () - startDate.getTime ()).append ("мс) |
Включенные группы: | "). append (arrayToString (testContext).getIncludedGroups ())). append (" |
Исключенные группы: | ").append (arrayToString (testContext.getExcludedGroups ())). append (" |
\ n "); sb.append ("
***** Изменено ******* (Наведите курсор на имя метода, чтобы увидеть имя класса теста) \ n "); if (testContext.getFailedConfigurations (). size ()> 0) {generateTable (sb," FAILED CONFIGURATIONS ", failedConfs," failed ", CONFIGURATION_COMPARATOR);} if (testContext.getSkippedConfigurations (). size ()> 0) {generateTable (sb, «SKIPPED CONFIGURATIONS», skippedConfs, «skipped», CONFIGURATION_COMPARATOR);} if (fail> 0) {generateTable (sb, «FAILED TESTS», testContext.getFailedTests (). GetAllResults ()., GetAllResults ()failed ", NAME_COMPARATOR);} if (testContext.getFailedButWithinSuccessPercentageTests (). size ()> 0) {generateTable (sb," НЕПРАВИЛЬНЫЕ ИСПЫТАНИЯ, НО В СООТВЕТСТВИИ С УСПЕХОМ PERCENTAGE ", процентным тестам," процентам ", NAME_COMTESTESTECTESTOR) (%() .size ()> 0) {generateTable (sb, "PASSED TESTS", sentTests, ",40 ", NAME_COMPARATOR);} if (skippedTests.size ()> 0) {generateTable (sb," SKIPPED TESTS ", skippedTests, "skipped", NAME_COMPARATOR);} sb.append (" \ n "); Utils.writeFile (outputDirectory, getOutputFile (testContext), sb.toString ());} частный статический void ppp (String)s) {System.out.println ("[TestHTMLReporter]" + s);} закрытый статический класс NameComparator реализует Comparator {public int Compare (ITestResult o1, ITestResult o2) {String c1 = o1.getMethod (). getMethodName ();String c2 = o2.getMethod (). GetMethodName ();return c1.compareTo (c2);}} частный статический класс ConfigurationComparator реализует Comparator {public int Compare (ITestResult o1, ITestResult o2) {ITestNGMethod tm1 = o1.getMethod ();ITestNGMethod tm2 = o2.getMethod ();возврат annotationValue (tm2) - annotationValue (tm1);} private static int annotationValue (метод ITestNGMethod) {if (method.isBeforeSuiteConfiguration ()) {return 10;} if (method.isBeforeTestConfiguration ()) {return 9;} if (method.isBeforeClassConfiguration ()) {return 8;} if (method.isBeforeGroupsConfiguration ()) {return 7;} if (method.isBeforeMethodConfiguration ()) {return 6;} if (method.isAfterMethodConfiguration ()) {return 5;} if (method.isAfterGroupsConfiguration ()) {return 4;} if (method.isAfterClassConfiguration ()) {return 3;} if (method.isAfterTestConfiguration ()) {return 2;} if (method.isAfterSuiteConfiguration ()) {return 1;} return 0;}}}