April 29, 2011

Capture screenshot on Failure

Capture screenshot....
How to capture screenshot?
How to capture screenshot on Failure?

These are the frequent questions.................It will be good if we capture screenshot if our test fails...
We need to use try and catch block..if try block catches the exception..it will execute the capture screenshot command which is written in catch block..


Below is the sample code how to capture screenshot on failure...........

--------------------------------------------------------------------------
import org.junit.*;


import org.openqa.selenium.server.*;

import com.thoughtworks.selenium.*;

public class Screenshot extends SeleneseTestCase{

public Selenium selenium;

public SeleniumServer seleniumserver;


@BeforeClass
public void setUp() throws Exception {
seleniumserver = new SeleniumServer();
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://");
seleniumserver.start();
selenium.start();
}
@Test
public void testScreenshot() throws Exception
{

try {
selenium.open("http://in.yahoo.com//?p=us");
selenium.windowMaximize();
selenium.click("//li[@id='pa-u_14782488-bd']/a/span[2]");
selenium.waitForPageToLoad("30000");
selenium.type("username", "test");
Thread.sleep(1000);
//the element name for password field is "passwd" But here i changed it to "passd" which is wrong.
//Selenium will capture screen shot after the error
selenium.type("passd", "123");
selenium.click(".save");
selenium.waitForPageToLoad("30000");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
selenium.captureScreenshot("C:\\test\\erro.png");
}

}


@AfterClass
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
}
}

----------------------------------------------------------

Hope this post will be helpful ...................


The screenshot will look like this...



Screenshot....



2 comments:

  1. Hi Naga thank you for this post , it is very useful, I want to know how can we set a timestamp on the captured screen shots. In the above post ,if I run the above method two times the screen shot is overridden , how can I make it happen so that there is a difference between the screen shots.

    ReplyDelete