Adding Screenshot to TestNg report

7,445 views
Skip to first unread message

Web User

unread,
May 11, 2012, 2:05:27 PM5/11/12
to seleniu...@googlegroups.com
Hello

I am using maven , testNg and webdriver to write my selenium test case.

i added this method to add screenshot after method if it fails

@AfterMethod
    public void setScreenshot(ITestResult result) {
        if (!result.isSuccess()) {
            try {
                 SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");

                WebDriver returned = new Augmenter().augment(webDriver);
                if (returned != null) {
                    File f = ((TakesScreenshot) returned)
                            .getScreenshotAs(OutputType.FILE);
                    try {
                        FileUtils.copyFile(f, new File(SCREENSHOT_FOLDER
                                + result.getName()+"_"+formater.format(Calendar.getInstance().getTime()) + SCREENSHOT_FORMAT));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (ScreenshotException se) {
                se.printStackTrace();
            }
        }
    }


Now i want to add this screenshot as a part to test ng , which maven plugin or code i need to use to that i can see screenshot as part of my test ng report.

Thanks For help.

Frank Escobar

unread,
May 11, 2012, 2:21:22 PM5/11/12
to seleniu...@googlegroups.com
I don't know if you mean at this:
With this plugin with the command mvn clean install, automatically executes testng.xml and in the folder \target\surefire-reports\index.html you can see the screen shoots (link: reporter output)

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/com/configurations/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>

Tell me if is right.



--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/KMfT7rq3Q8oJ.
To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.



--

Frank Escobar | QA Analyst
GlobalLogic Inc. | Innovation by Design
ARGENTINA | CHILE | CHINA | GERMANY | INDIA | ISRAEL | UKRAINE | UK | USA
Av. Corrientes 485 piso 6 | Buenos Aires, 1043
Office: +54.11.5533.8300 x 1018 | Mobile: +54.9.11.4394.3121

www.globallogic.com
www.globallogic.com/email_disclaimer.txt


Web User

unread,
May 11, 2012, 2:27:10 PM5/11/12
to seleniu...@googlegroups.com
I am also doing the same thing but my screenshots are not attached with reports .

i have my testng reports in target/surefire-reports/index.html
and i am getting my screenshot at target/screenshot .

How can i link the both ?????? so that i can see screenshot as part of index.html.

Whats this (link: reporter output) ????? i feel i am missing this part . How can i implement this .

Thanks for quick response.
To post to this group, send email to selenium-users@googlegroups.com.
To unsubscribe from this group, send email to selenium-users+unsubscribe@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Frank Escobar

unread,
May 11, 2012, 2:36:40 PM5/11/12
to seleniu...@googlegroups.com
ohhh you need add Reporter.log("")

example:

@Test
public void testLoginCorrect() {
.............................
}

@AfterMethod(alwaysRun = true)
public void afterMethod(ITestResult result) throws Exception {
if (!result.isSuccess()) 
takeScreenShoot(driver, result.getMethod());
// Quit environment.
driver.quit();
}

public void takeScreenShoot(WebDriver driver, ITestNGMethod testMethod) throws Exception {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
String nameScreenshot = testMethod.getXmlTest().getParameter("browser").toUpperCase() + "_" + testMethod.getTestClass().getRealClass().getSimpleName() + "_" + testMethod.getMethodName();
String path = getPath(nameScreenshot);
FileUtils.copyFile(screenshot, new File(path));
Reporter.log("<a href=" + path + " target='_blank' >" + this.getFileName(nameScreenshot) + "</a>");
}

private String getFileName(String nameTest) throws IOException {
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy_hh.mm.ss");
Date date = new Date();
return dateFormat.format(date) + "_" + nameTest + ".png";
}

private String getPath(String nameTest) throws IOException {
File directory = new File(".");
String newFileNamePath = directory.getCanonicalPath() + "\\target\\surefire-reports\\screenShots\\" + getFileName(nameTest);
return newFileNamePath;
}
Add this imports:
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.ITestNGMethod;
import org.testng.Reporter;

Tell me if is right.

To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/EPiUUkt15a4J.

To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Web User

unread,
May 11, 2012, 3:10:35 PM5/11/12
to seleniu...@googlegroups.com
i added this reporter log , but i am not able to see any screenshot in my target folder. ia m wondering is i need to start this reporter log somewhere ???

i just added this method with after method anotation .

Frank Escobar

unread,
May 11, 2012, 3:14:27 PM5/11/12
to seleniu...@googlegroups.com
Can I see the test??
Remember that test must fail.

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/NfJiB9pvAeIJ.

To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Web User

unread,
May 11, 2012, 3:44:03 PM5/11/12
to seleniu...@googlegroups.com
Here is the test

@Test(enabled =true)
    public void testBlanklogin() throws TimeoutException {
        try {
            System.out.println("testBlanklogin");
            webDriver.findElement(By.name("username")).clear();
            webDriver.findElement(By.name("password")).clear();
            webDriver.findElement(By.cssSelector("button.action")).click();
           
            webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
          //Assert check for user name  at buttom bar

        } catch (Error e) {
            verificationErrors.append(e.toString());
        }

        /** It should Show the error message as username/password required **/
    }

Its failing as i am entering as blank user .

i am running it through maven sure fire plugin like thi s.


<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.10</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                    <skip>true</skip>
                    <properties>
                        <user.username></user.username>
                        <user.password></user.password>
                        <site.url></site.url>
                        <grid2.url></grid2.url>
                        <browser.name></browser.name>
                        <browser.version></browser.version>
                        <browser.platform></browser.platform>
                    </properties>
                </configuration>
                <executions>
                    <execution>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>test</goal>
                        </goals>
                        <configuration>

                            <skip>false</skip>

                        </configuration>
                    </execution>
                </executions>
            </plugin>

and i have a base class which is extend by every test.

Here is the base class.


public class TestBase {

    private static final String SCREENSHOT_FOLDER = "target/screenshots/";
    private static final String SCREENSHOT_FORMAT = ".png";
    protected WebDriver webDriver;

    protected String websiteUrl;
    protected String gridHubUrl;
    protected Browser browser;
    protected StringBuffer verificationErrors = new StringBuffer();

    @BeforeSuite(alwaysRun = true)
    public void init(ITestContext context) {
   
     
        browser = new Browser();

        webDriver = WebDriverFactory.getInstance(gridHubUrl, browser, username,
                password);
        webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }
   
//    @AfterMethod
//    public void setScreenshot(ITestResult result) {
//        if (!result.isSuccess()) {
//            try {
//                 SimpleDateFormat formater = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss");
//
//                WebDriver returned = new Augmenter().augment(webDriver);
//                if (returned != null) {
//                    File f = ((TakesScreenshot) returned)
//                            .getScreenshotAs(OutputType.FILE);
//                    try {
//                        FileUtils.copyFile(f, new File(SCREENSHOT_FOLDER
//                                + result.getName()+"_"+formater.format(Calendar.getInstance().getTime()) + SCREENSHOT_FORMAT));
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            } catch (ScreenshotException se) {
//                se.printStackTrace();
//            }
//        }
//    }
//   
    @AfterMethod(alwaysRun = true)
    public void afterMethod(ITestResult result) throws Exception {
    if (!result.isSuccess())
    takeScreenShoot(webDriver, result.getMethod());

   
    }
   
    public void takeScreenShoot(WebDriver driver, ITestNGMethod testMethod) throws Exception {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        String nameScreenshot = browser.getName().toUpperCase() + "_" + testMethod.getTestClass().getRealClass().getSimpleName() + "_" + testMethod.getMethodName();

        String path = getPath(nameScreenshot);
        FileUtils.copyFile(screenshot, new File(path));
        Reporter.log("<a href=" + path + " target='_blank' >" + this.getFileName(nameScreenshot) + "</a>");
        }

        private String getFileName(String nameTest) throws IOException {
        DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy_hh.mm.ss");
        Date date = new Date();
        return dateFormat.format(date) + "_" + nameTest + ".png";
        }

        private String getPath(String nameTest) throws IOException {
        File directory = new File(".");
        String newFileNamePath = directory.getCanonicalPath() + "\\target\\surefire-reports\\screenShots\\" + getFileName(nameTest);
        return newFileNamePath;
        }

    @AfterSuite(alwaysRun = true)
    public void tearDown() {
        System.out.println("Inside Test Base");

        webDriver.quit();

        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }

    }

}

i am still missing some link up???

To post to this group, send email to selenium-users@googlegroups.com.
To unsubscribe from this group, send email to selenium-users+unsubscribe@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Frank Escobar

unread,
May 11, 2012, 3:51:53 PM5/11/12
to seleniu...@googlegroups.com
Maybe the try/catch, ry to remove it.

@Test(enabled =true)
    public void testBlanklogin() throws TimeoutException {
            System.out.println("testBlanklogin");
            webDriver.findElement(By.name("username")).clear();
            webDriver.findElement(By.name("password")).clear();
            webDriver.findElement(By.cssSelector("button.action")).click();
            
            webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
          //Assert check for user name  at buttom bar 

To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/Kwwv6aEzvFMJ.

To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Web User

unread,
May 11, 2012, 4:13:53 PM5/11/12
to seleniu...@googlegroups.com


I debug it and found out its name issue , so fixed that .

Now in reporter log has the link for screenshot but its not actually creating the screenshots inside the target\\surefire-reports\\screenshots.

No idea why ???

Any pointer for debug ??



On Friday, May 11, 2012 11:05:27 AM UTC-7, Web User wrote:

Frank Escobar

unread,
May 11, 2012, 4:32:30 PM5/11/12
to seleniu...@googlegroups.com
You must to verify in which folder inside of you project are created that screenshoot. Sometimes the folder is created outside of target folder in a folder named "test-output". Try with that.


--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/l5fHXtnuhOYJ.

To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Web User

unread,
May 11, 2012, 5:22:33 PM5/11/12
to seleniu...@googlegroups.com

I changed the path and now i am able to get the screenshot at target\surefire\screenshot but still the refis not working .

i was looking at Reporter.log("<a href=" + path + " target='_blank' >" + this.getFileName(nameScreenshot) + "</a>");

Can you please specify me that what target is doing as my path is matching the where the screenshot is there .

Thanks for help.

On Friday, May 11, 2012 11:05:27 AM UTC-7, Web User wrote:
On Friday, May 11, 2012 11:05:27 AM UTC-7, Web User wrote:
Screen Shot 2012-05-11 at 2.17.12 PM.png

Frank Escobar

unread,
May 11, 2012, 11:20:44 PM5/11/12
to seleniu...@googlegroups.com
You can see the path in the console, if you put the next line after of "Reporter.log"

Reporter.log("<a href=" + path + " target='_blank' >" + this.getFileName(nameScreenshot) + "</a>"); 

System.out.println("<a href=" + path + " target='_blank' >" + this.getFileName(nameScreenshot) + "</a>");



--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/hvv7tPeKVlAJ.

To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Frank Escobar

unread,
May 14, 2012, 4:00:10 PM5/14/12
to seleniu...@googlegroups.com
What's happens?

Mike Riley

unread,
May 14, 2012, 7:43:01 PM5/14/12
to seleniu...@googlegroups.com
It will probably help you figure it out if you put that expression into a string so you can see what it looks like put together.  I have a feeling your anchor tag is wrong in some small way.

here is what mine ends up looking like when I look at the HTML in the report:
<img alt="" src="file:///V:\QA\Selenium\selenium/..\..\Reports\mriley\Netbeans\ViewOptions/ScreenSnapshot0.PNG">

Mike

Web User

unread,
May 15, 2012, 12:33:56 PM5/15/12
to seleniu...@googlegroups.com
Thanks Frank , I was able to fix it on weekend and its running in my local but jenkin machine still have some issues because os space bar , might be able to resolve soon.

Thanks for your help.



On Friday, May 11, 2012 11:05:27 AM UTC-7, Web User wrote:
On Friday, May 11, 2012 11:05:27 AM UTC-7, Web User wrote:

Frank Escobar

unread,
May 15, 2012, 1:18:17 PM5/15/12
to seleniu...@googlegroups.com
You're welcome!

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/bBsmXzfOz0QJ.

To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Mike Riley

unread,
Jun 13, 2012, 4:33:23 PM6/13/12
to seleniu...@googlegroups.com
Did you do something like this?

File file;
String str = System.getProperty("user.dir") + "/"; // Current dir
file = ((TakesScreenshot) augmentedDriver).getScreenshotAs(
OutputType.FILE);
FileUtils.copyFile(file, new File(filename));
Reporter.log("<img src=\"file:///" + str + filename + "\" alt=\"\"/><br />");

Mike

On Wednesday, June 13, 2012 7:12:59 AM UTC-7, falak pandya wrote:
Hi,

I want to add link in my Report.
I used Reporter.log, but its simple adding the passed content as a text in ReportNG generated report.

Can you have idea how can i add link to report?
You're welcome!


To post to this group, send email to selenium-users@googlegroups.com.
To unsubscribe from this group, send email to selenium-users+unsubscribe@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

falak pandya

unread,
Jun 15, 2012, 4:53:37 AM6/15/12
to seleniu...@googlegroups.com
I am using selenium.
following code i have used to take screen shot and to add its link in report

String filepath=System.getProperty("user.dir")+"\\ScreenShots\\"+filename+".png";
selenium.captureScreenshot(filepath); 
Reporter.log("screenshot saved at "+filepath+"<file://ScreenShots//%22"+filename+"%22.png>");
Reporter.log("<a href='../"+filename+".png'> <img src='../"+filename+".png' hight='100' width='100'/> </a>");

Even I have tried with code u mentioned.
but in both case link not getting added in Report. 
All thing written in reporter log, shows as text in report.

Mike Riley

unread,
Jun 15, 2012, 1:09:31 PM6/15/12
to seleniu...@googlegroups.com
In my experience that should have written it as HTML into the log, but you don't want to have it as an anchor tag (you aren't linking to anything here), and just leave it as an img tag.  If you use the Reporter.log(String, boolean) variation you don't seem to get it as HTML.  I would check the HTML to be sure it isn't in there.  I would also leave the size attributes out of there (or at least spell height correctly), because the image may not be that size, and if you look at my code you will see that I used double quotes that were escaped with a backslash for the src argument.

One other thing a lot of people make a mistake with is putting "\\" in pathnames for files with Java.  That does work on Windoze, but means it will not work on any other OS!  Java will convert a "/" in a pathname on Windoze (actually the OS takes it as an alternative to "\", I believe") and you only need one, plus it now works on other OS platforms!

Mike

Krishnan Mahadevan

unread,
Jun 15, 2012, 1:14:32 PM6/15/12
to seleniu...@googlegroups.com
Or even better.., use File.separator and let java figure out the appropriate  way of separating directory names based on the OS flavor. 
To view this discussion on the web visit https://groups.google.com/d/msg/selenium-users/-/4owBmLxx7mEJ.
To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en-US.


--
Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/

MS

unread,
Jul 31, 2012, 4:35:42 PM7/31/12
to seleniu...@googlegroups.com
I am using Reporter.log(String). but the hyperlink is displayed as plain text on my reports. I am using Mac OSX. I would highly appreciate if anyone could help.

Thanks,
Manpreet Singh

somesh bansal

unread,
Aug 1, 2012, 7:05:45 AM8/1/12
to seleniu...@googlegroups.com
HI,

I am too facing the same problem, link is not getting generated displays TEXT always

Tried both <a> and <img> tags but no success

Somesh

Mike Riley

unread,
Aug 8, 2012, 10:11:52 PM8/8/12
to seleniu...@googlegroups.com
I have posted the code I use in this group.  Search for "logException(" and you should be able to find it.

Mike
You're welcome!


To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.

Mike Riley

unread,
Aug 16, 2012, 5:37:03 PM8/16/12
to seleniu...@googlegroups.com
Can you show the code?

Be sure you are putting the image file in the correct directory so the link points to it.  I was using a relative path based on where my test code ran.

Mike

On Monday, August 13, 2012 3:19:29 PM UTC-7, Venkat Ramanan K wrote:
Hi Mike,

Can you please explain the logic of adding the screenshot as link?

I have added it in the reporter.log(), but still I view it as a text. When I viewed the source code of "Reporter-Output.html" - the html tags was encoded i.e <a> as &lt;a&gt;.

Can you please let me know how to make it work?? Thanks in advance.

Reply all
Reply to author
Forward
0 new messages