Null pointer exception while taking screenshot in selenium POM with extent report - selenium

A null pointer exception is thrown While trying to take screenshot when the scenario fails. I have an actions class in which i have defiled the capture screenshot method.
public static String capture(WebDriver driver) throws NullPointerException, IOException {
File scrFile;
scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("D:\\Dinu\\SeleniumReports\\Test" + System.currentTimeMillis() + ".jpeg");
String filepath = Dest.getAbsolutePath();
org.openqa.selenium.io.FileHandler.copy(scrFile, Dest);
return filepath;
}
Extent reports are implemented using Itestlisterner interface. Below given code for which implements the screenshot method given:
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(result.getThrowable());
try {
String screenshotPath = actions.capture(driver);
test.get().addScreenCaptureFromPath(screenshotPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And am getting the below error: Please help in resolving the same.

public static String getScreenhot(WebDriver driver, String screenshotName) throws Exception {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
//after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/"+screenshotName+dateName+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
#AfterMethod
public void getResult(ITestResult result) throws IOException{
if(result.getStatus() == ITestResult.FAILURE){
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getName());
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getThrowable());
//To capture screenshot path and store the path of the screenshot in the string "screenshotPath"
//We do pass the path captured by this mehtod in to the extent reports using "logger.addScreenCapture" method.
String screenshotPath = ExtentReportsClass.getScreenshot(driver, result.getName());
//To add it in the extent report
logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
// ending test
//endTest(logger) : It ends the current test and prepares to create HTML report
extent.endTest(logger);
}

Related

I am not able to attach screenshots to extent reports. What is the solution?

#AfterMethod
public void getResult(ITestResult result) throws Exception{
if(result.getStatus() == ITestResult.FAILURE)
{
extentlogger.log(Status.FAIL, MarkupHelper.createLabel(result.getThrowable() +
" - Test Case Failed", ExtentColor.RED));
try {
// get path of captured screenshot using custom failedTCTakeScreenshot method
String screenshotPath = takeSnapShot(result);
extentlogger.fail("Test Case Failed Snapshot is below " +
extentlogger.addScreenCaptureFromPath(screenshotPath));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The above code is the code I'm using after method in TestNG. Am I doing anything wrong?enter image description here
You don't have any method named as takeSnapShot or its not declared as public:
Create a method in base class with below content or just directly add below code in the aftermethod hook by replacing takeSnapShot step:
//Convert web driver object to TakeScreenshot
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
//Call getScreenshotAs method to create image file
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
//Move image file to new destination
File DestFile=new File(fileWithPath);
//Copy file at destination
FileUtils.copyFile(SrcFile, DestFile);

Extent Report in Jenkins is displaying blank icon for attached screenshots

I have generated a runnable jar of my project, and running it on other machine through jenkins.
Jar file executing successfully and generating extent report also,
but there is a blank icon on the place of screenshots.
I have searched on google but did not find any relevant solution to solve my problem.
I am using Intellij IDE and opening the extent report by using the option of "Open in Browser".
When there are more than two screenshots attached(like in above case) with the extent report, it is showing blank icon and showing error when opening the image in new tab.
(When opening the extent report by going into the folder where it is actually saved in the system, it is working as expected).
My code:
#BeforeTest
public void setExtent() {
extent = new ExtentReports(System.getProperty("user.dir")+ "/test-output/Login.html", true);
System.out.println("KKKKKKK");
extentTest = extent.startTest("Start the Execution");
extent.addSystemInfo("Host Name", "Live Contract");
extent.addSystemInfo("User Name", "Shivam Goyal");
extent.addSystemInfo("Environment", "Develop");
extentTest.log(LogStatus.INFO, "Test Execution started");
}
public static String getScreenshot(WebDriver driver, String screenshotName) {
String dateName = new SimpleDateFormat("ddMMyyyyhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir")+ "/test-output/"+ screenshotName + dateName + ".png";
File destination = new File(path);
try {
FileUtils.copyFile(src, destination);
}
catch(IOException e){
System.out.println("Capture Failed" +e.getMessage());
}
return path;
}
#Test
public void openURL() throws IOException, InterruptedException, HeadlessException, UnsupportedFlavorException {
System.out.println("test openWeb");
extentTest = extent.startTest("LC1_1.1 - Verify the Login Panel of \"Berater\".");
try {
//Accept All cookies
driver.findElement(By.className(property.getProperty("LiveContractCookies"))).click();
//Test case LC1_1.1 Open the given URL in Browser (Aufruf der entsprechenden URL im Browser)
boolean Homescreen = driver.findElement(By.name(property.getProperty("BeraterLoginPanelName1"))).isDisplayed();
Thread.sleep(3000);
Assert.assertTrue(Homescreen);
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
#Test
public void checkEntryFields() throws InterruptedException {
extentTest = extent.startTest("LC1_1.2 - Verify the Entry fields on Berater's login panel");
try {
driver.findElement(By.className(property.getProperty("LiveContractCookies"))).click();
WebElement username = driver.findElement(By.name(property.getProperty("username_fieldName")));
WebElement password = driver.findElement(By.name(property.getProperty("password_fieldName")));
username.click();
username.sendKeys("Test123");
password.click();
password.sendKeys("9876554");
Thread.sleep(1000);
System.out.println(username.getText());
String usnm = username.getAttribute("value");
String pass = password.getAttribute("value");
System.out.println("Something happening");
Assert.assertEquals("Test123", usnm);
Assert.assertEquals("98765", pass);
}
catch(Exception e){
e.printStackTrace();
}
}
#AfterMethod
public void tearDown(ITestResult result) {
if(result.getStatus() == ITestResult.FAILURE){
extentTest.log(LogStatus.FAIL, "Test Case Failed is" +result.getName());
extentTest.log(LogStatus.FAIL, "Test Case Failed is" +result.getThrowable());
String screenshotPath = Login.getScreenshot(driver, result.getName());
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));
}
else if(result.getStatus() == ITestResult.SKIP){
extentTest.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
else if(result.getStatus() == ITestResult.SUCCESS){
extentTest.log(LogStatus.PASS, "Test Case Passed is "+result.getName());
}
extent.endTest(extentTest);
//extent.flush();
driver.quit();
//tempDriver.quit();
//tempDriver.quit();
}
#AfterTest
public void endReport() {
try{
extent.flush();
}
catch(Exception e){
e.getMessage();
}
//extent.close();
}

Getting sscreenshot attached for failed test to allure report in format: datetime-classsname-testname selenium, testng, allure

I am using testng, maven, allure in my framework. Currently my screenshots for failed test are saved in surefire-reports/screenshots as :
datetime-classname-methodname
eg: 09-22-2017_01.13.23_ClassName_Methodname.png
Here is code for this :
#AfterMethod
protected void screenShotIfFail(ITestResult result) throws IOException {
if (!result.isSuccess()) {
takeScreenShot(result.getMethod());
}
}
private void takeScreenShot(String name) throws IOException {
String path = getRelativePath(name);
File screenShot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenShot, new File(path));
String filename = makeScreenShotFileName(name);
System.out.println("Taking Screenshot! " + filename);
Reporter.log("<a href=" + path + " target='_blank' >" + filename
+ "</a>");
}
private void takeScreenShot(ITestNGMethod testMethod) throws IOException {
String nameScreenShot = testMethod.getTestClass().getRealClass()
.getSimpleName()
+ "_" + testMethod.getMethodName();
takeScreenShot(nameScreenShot);
}
private String makeScreenShotFileName(String name) {
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy_hh.mm.ss");
Date date = new Date();
return dateFormat.format(date) + "_" + name + ".png";
}
private String getRelativePath(String name) throws IOException {
Path path = Paths.get(".", "target", "surefire-reports", "screenShots",
makeScreenShotFileName(name));
File directory = new File(path.toString());
return directory.getCanonicalPath();
}
For getting attached to allure reports, i tried #Attachment like this :
#Attachment(value = "filename", type = "image/png")
private byte[] takeScreenShot(String name) throws IOException {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
Screenshot is getting attached to allure report, but how can i get it in same format as in surefire reports.
Thanks !!
You can pass a custom name directly into method annotated with #Attachment:
#Attachment(value = "{name}", type = "image/png")
private byte[] takeScreenShot(String name) throws IOException {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
The only difference between Allure 1 and Allure 2 is in value parameter. For Allure 1 use the following syntax:
value = "{0}"
Where {0} is reference to the first method's parameter (its index).
For Allure 2, use the following:
value = "{name}"
In this case {name} is the name of a method's parameter.

How to test login page with multiple webpage(present in notepad) using selenium web driver Java?

I am testing like 100 url everything is working good. my problem is when the test starts it get web url from notepad then open the url here my process is to check the login or not in some case if the for example 10th url shows 404 error the test terminate here it cant process further urls. Any solution for this process...
my codes
public class File {
#Test(dataProvider="testdata")
public void sum(String url)
{
System.out.println(url);
}
#DataProvider
public Object[][] testdata(){
int count=20;
Object[][] obj = new Object[count][1];
for(int i=0;i<=count;i++)
{
String fileName = "E:\\ework\\Web\\bin\\Websearch\\test.txt";
try {
String line = null;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
String[] abs={line};
int size = abs.length;
for(int j=0;j<=size;j++)
{
obj[i][0]=abs[j];
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
`}
return obj;
}
}
thank you.:)
If you are using framework like TestNG then look at DataProviders for the same.
Use Try{} Catch(Exception e){} block. Insert your assertion in try block and once the assertion fails then try to capture the exception in some list or other data structure and after all urls are processed then iterate over the exception list and report it in your Reports or logs.

Unable to add screenshot in ReportNG HTML report

I am trying to take a screenshot for failure methods and also want to put the same in my Report, I am able to take the screenshot but unable to show the same in HTML report. Following is my code, friends any clue on this ?
public class SB1 {
private static Logger logger = Logger.getLogger(SB1.class);
WebDriver driver = new FirefoxDriver();
#Test
public void Testone() {
driver.get("http://www.google.com/");
assert false;
}
public void catchExceptions(ITestResult result) {
System.out.println("result" + result);
String methodName = result.getName();
System.out.println(methodName);
if (!result.isSuccess()) {
try {
String failureImageFileName = new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(failureImageFileName));
String userDirector = System.getProperty("user.dir") + "/";
Reporter.log("<a href=\""+ userDirector + failureImageFileName +"\"><img src=\"file:///" + userDirector
+ failureImageFileName + "\" alt=\"\""+ "height='100' width='100'/> "+"<br />");
Reporter.setCurrentTestResult(null);
} catch (IOException e1) {
e1.printStackTrace();
}
}
Have you set ESCAPE_PROPERTY to false? This is what you will have to do if you want reportng to post the screenshot -
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
and in your setUp-
System.setProperty(ESCAPE_PROPERTY, "false");
I tried this. It seems like if you set the System Property to false, it removes the escaping from the ENTIRE log... From what I can tell, the report is generated after the test, with whatever the system property is set to at the time. I want to insert the screenshot (which worked with above code) but I do not want to remove the other formatting (br tags).
You can use following code.
Reporter.log("<br>Chrome driver launched for ClassOne</br>");
Or you can use customize method, where you do not need to append the br tag everytime, use following customized method.
public void customLogReport(String testCaseDescription) throws Exception{
try{
Reporter.log("<br>" + testCaseDescription + "</br>");
}catch(Exception e){
e.printStackTrace();
}
}