Unable to take screenshot in Selenium - java

I am trying to capture a screenshot for each failure occurrence and written following code, but this is not working.
public class TestFile {
WebDriver driver = new FirefoxDriver();
#Test
public void Testone(){
driver.get("http://www.google.com/");
}
#AfterMethod(alwaysRun=true)
public void catchExceptions(ITestResult result){
System.out.println("result"+result);
String methodName = result.getName();
System.out.println(methodName);
if(!result.isSuccess()){
try {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile,new File("C:\\screenshot2.png" ));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
This is failing at
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
stack trace:
[TestNG] Running:
C:\Documents and Settings\537310\Local Settings\Temp\testng-eclipse-1576306112\testng-customsuite.xml
result[TestResult name=Testone status=FAILURE method=TestFile.Testone()[pri:0, instance:com.example.tests.TestFile#1b34126] output={null}]
FAILED CONFIGURATION: #AfterMethod catchExceptions([TestResult name=Testone status=FAILURE method=TestFile.Testone()[pri:0, instance:com.example.tests.TestFile#1b34126] output={null}])
net.sf.cglib.core.CodeGenerationException: java.lang.IllegalAccessException-->Class org.openqa.selenium.remote.Augmenter$CompoundHandler can not access a member of class org.openqa.selenium.firefox.FirefoxDriver with modifiers "protected"
at net.sf.cglib.core.ReflectUtils.newInstance(ReflectUtils.java:235)
list of imports:
package com.example.tests;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

The stacktrace you shared is not the stacktrace, but I think the testng log. The example you provided actually works. I just made the test fail, because in the #AfterMethod a screenshot is taken only if the test fails: if(!result.isSuccess())
Then when I ran the example again, I got:
java.io.FileNotFoundException: C:\screenshot2.png (Access is denied)
Then I changed the location of the picture to be on D: where the permissions are correct, and it worked end to end, I can see the screenshot.
Cheers
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class TestFile {
WebDriver driver = new FirefoxDriver();
#Test
public void Testone() {
driver.get("http://www.google.com/");
assert false;
}
#AfterMethod(alwaysRun = true)
public void catchExceptions(ITestResult result) {
System.out.println("result" + result);
String methodName = result.getName();
System.out.println(methodName);
if (!result.isSuccess()) {
try {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\screenshot2.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}

Hi sinisa229 mihajlovski,
Your script is working properly. but there is a slight change in your script. If i won't comment the line "assert false", it is giving error.

Try This :
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
In place of
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Related

Take a screen shot and copy through FileUtils in Selenium WebDriver and java [duplicate]

This question already has answers here:
FileUtils not showing suggestion to import predefined class for Screenshot functionality in selenium WebDriver
(5 answers)
Closed 4 years ago.
When I try to get screen shots with following code it is showing error.
FileUtils.copyFile(source, new File("*./Screenshots/facebook.png"));
error message
but when i try the following code it is okay.
FileHandler.copy(source,new File("*./Screenshots/facebook.png"));
Why is that?
full code is below
package sample.code;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.testng.annotations.Test;
public class ScreenShot {
#Test
public void facebookScreenShot() throws IOException {
WebDriver driver= new ChromeDriver();
driver.get("http://www.facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='u_0_m']")).sendKeys("screenshot");
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileHandler.copy(source,new File("*./Screenshots/facebook.png"));
driver.quit();
}
}
By using Robot class ,you can take screenshot.Following is the code to take screenshot.
import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class CaptureScreenshot {
public static void main(String[]args) throws IOException, HeadlessException, AWTException
{
// This code will capture screenshot of current screen
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
// This will store screenshot on Specific location
ImageIO.write(image, "png", new File("C:\\Users\\Screenshot\\CurrentScreenshot.png"));
}
}

Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of:

When I replace selenium-server-standalone-2.53.0 by the selenium-server-standalone-3.1.0 in %Jmeter%lib folder then I'm getting this error:
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.io.File; import java.io.FileReader; import java.io.FileWriter; impor . . . ''
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsESRv.CSVWriter;
Boolean result=true;
public WebDriver driver;
try
{
System.setProperty("webdriver.chrome.driver","Projects\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://something.com/registration/");
WebDriverWait wait = new WebDriverWait(driver, 20000);
String uname= bsh.args[0];
String pass= bsh.args[1];
// Logged In
driver.findElement(By.xpath("//*[contains(#id,'menu-item')]//*[text()='Log In']")).click();
driver.findElement(By.id("username")).sendKeys(new String[] {uname});
driver.findElement(By.id("password")).sendKeys(new String[] {pass});
driver.findElement(By.xpath("//*[#id='woocommerce-login-nonce']/following-sibling::*[#name='login']")).click();
// Logged Out
driver.findElement(By.xpath("//*[#id='masthead']//*[text()='Sign out']")).click();
}
catch (Exception ex)
{
ex.printStackTrace();
IsSuccess = false;
ResponseCode = "500";
ResponseMessage = ex.getMessage();
log.error(ex.getMessage());
System.err.println(ex.getMessage());
}
catch (Throwable thex)
{
System.err.println(thex.getMessage());
}
finally
{
driver.quit();
}
IsSuccess=result;
return result;
Code is written in Beanshell Sampler in Jmeter.
Replacing just only one Selenium library is not enough, you need to upgrade other dependencies as well
Install clean JMeter
Download http://selenium-release.storage.googleapis.com/3.1/selenium-java-3.1.0.zip file and unpack all the .jars somewhere to JMeter Classpath (JMeter's "lib" folder is fine)
Restart JMeter to pick the .jars up
In order to see the "normal" stacktrace amend your catch block to look like:
catch (Exception ex) {
log.error("Something went wrong", ex);
}
Consider switching to JSR223 Sampler and Groovy language as Groovy is more Java-compliant and has much better performance. See Apache Groovy - Why and How You Should Use It for more detailed explanation.

Click method in the code is skipping when executed the runner class

I have created the base class in page package which is under src/test/java/Stepdefinations/pages. Created the Account class(page object) in page package. Created Account steps class(step defination file), Runner class in stepdefination package.
When I executed the runner class, I'm able to open the browser but the click method is selenium base class is not happening.
//Selenium base class:
package Stepdfinations.pages;
import java.io.File;
import java.net.URL;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
public class SeleniumBaseclass
{
Properties prop;
public HttpURLConnection connection = null;
String currenturl;
protected WebDriver driver;
public SeleniumBaseclass (WebDriver driver)
{
this.driver=driver;
}
public void Property() throws Exception
{
File f= new File("C:\\Users\\watareuman9\\workspace\\Cucumberproject\\src\\test\\resources\\data\\config.property");
FileInputStream fis = new FileInputStream(f);
prop=new Properties();
prop.load(fis);
System.setProperty("webdriver.chrome.driver", getChromespath());
driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(getAppurl());
Thread.sleep(500);
}
public String getChromespath()
{
return prop.getProperty("ChromePath");
}
public String getAppurl()
{
return prop.getProperty("URL");
}
//click method
public void click(String objstr,WebElement objname)
{try
{
Thread.sleep(5000);
objname.click();
System.out.println("'"+objstr+"'"+"is clickde");
}
catch(Exception e)
{
getHttpResponse();
}
}
public void getCurrenturl()
{
String currenturl=driver.getCurrentUrl();
}
public void getHttpResponse()
{
try
{
getCurrenturl();
URL url=new URL(currenturl);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
if(connection.getResponseCode()==200)
{
System.out.println(currenturl +"-"+connection.getResponseMessage());
}
else if(connection.getResponseCode()==connection.HTTP_NOT_FOUND)
{
System.out.println(currenturl +"-"+connection.getResponseMessage());
}
}
catch(Exception e)
{
e.getMessage();
}
}
public void getQuitdriver()
{
driver.close();
}
}
//Account class(page objects)
package Stepdfinations.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class Account extends SeleniumBaseclass
{
public Account(WebDriver driver)
{
super(driver);
this.driver=driver;
}
#FindBy(how = How.XPATH, using = "//*[#id='bodyContent']/div/div[1]/a[1]/u")
private WebElement login_button;
public void clickLoginButton()
{
click("login_button",login_button);
}
}
//Accountsteps(Step defination file)
package Stepdfinations;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.By;
import Stepdfinations.pages.Account;
import Stepdfinations.pages.SeleniumBaseclass;
public class Acoountsteps
{
WebDriver driver;
Account act;
#Given("^I navigated to the Login page$")
public void i_navigated_to_the_Login_page() throws Throwable
{
act=new Account(driver);
act.Property();
}
#When("^I click on the New Account link$")
public void i_click_on_the_New_Account_link() throws Throwable
{
act.clickLoginButton();
}
}
//Runner class
package Stepdfinations;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(features="src/test/resources/features")
public class Runner
{
}
Few things you can look into:
Check your x-path (you can use FireBug for it)
Try debug your code - Is debugger landing to you Test or not.
Possibly you need to mention the Test Class or Test Method into your runner class (For example in testNG, if code is run through testNG runner, you need to mention the Test or class into the xml file that testNG use what to execute and what to not).

Automation screenshot

I'm currently working on an automation project, I've created this simple program to report testing information and to take screenshots.
package ReportTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import ReportTest.Utitlity;
public class ReportTest {
ExtentReports report;
ExtentTest logger;
WebDriver driver;
#Test
public void verifyBlogTitle()
{
report =new ExtentReports("C:\\Users\\reganc3\\desktop\\report\\LearnAutomation.html");
logger=report.startTest("VerifyBlogTitle");
driver = new FirefoxDriver();
driver.manage().window().maximize();
logger.log(LogStatus.INFO, "Browser started");
driver.get("http://www.learn-automation.com");
logger.log(LogStatus.INFO, "Application is up and running");
String title = driver.getTitle();
Assert.assertTrue(title.contains("Selenium"));
logger.log(LogStatus.PASS, "Title Verified");
}
#AfterMethod
public void tearDown(ITestResult result)
{
if(result.getStatus()==ITestResult.FAILURE)
{
String screenshot_path = Utitlity.captureScreenshot(driver, result.getName());
logger.log(LogStatus.FAIL, "TitleVerification", screenshot_path);
}
report.endTest(logger);
report.flush();
driver.get("C:\\Users\\reganc3\\desktop\\report\\LearnAutomation.html");
}
}
Here is my Utilitys class which is being called to take the screenshot
package ReportTest;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import java.util.*;
public class Utitlity {
public static String captureScreenshot(WebDriver driver, String screenshotName)
{
try
{
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
String dest = " C:\\Users\\reganc3\\desktop\\ " +screenshotName+ ".png";
File destination=new File(dest);
FileUtils.copyFile(source, destination);
System.out.println("Screenshot taken");
return dest;
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
return e.getMessage();
}
}
}
I am getting the following error
**Exception while taking screenshot null
I'm quite new to Selenium and TestNG so I'm basically looking for someone to shed some light on this and give me some pointers in the right direction and to understand what is actually happening with my code that's throwing this error.
Thank you In advance.
I'm currently using this method to take screenshots in my tests:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public void takeScreenShot(WebDriver driver, String methodName) {
File screenshotFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshotFile,new
File("Screenshots\\"+methodName+" "+GetTimeStampValue()+".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
and this method to get a TimeStamp:
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
public String GetTimeStampValue()throws IOException{
Calendar cal = Calendar.getInstance();
Date time=cal.getTime();
String timestamp=time.toString();
String systime=timestamp.replace(":", "-");
return systime;
}
I was using the wrong version of ExtentReport for the code I had.
The code I was using was for a newer up to date version of ExtentReport and the maven dependency I had was pointing to an older version. The code itself worked perfectly when I updated the dependency to the newest version.
Robot r=new Robot();
r.keyPress(KeyEvent.VK_PRINTSCREEN);
r.keyRelease(KeyEvent.VK_PRINTSCREEN);

Appium driver null pointer exception

I am new to Appium and just getting started, I have been following an example and using a basic Contacts apk on Android tablet to start against. The code I have is pretty much copied from the example I am following but when I try to run the test I get a null pointer exception. I did some debugging and find that the driver = null is why I am getting this exception. I looked around and found some code that I thought might help but it hasn't.
The code I have is
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import java.net.MalformedURLException;
import java.net.URL;
public class addContact {
AppiumDriver driver;
#Before
public void setUp () throws Exception {
new DesiredCapabilities();
DesiredCapabilities capabilities = DesiredCapabilities.android();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,"AndroidTestDevice");
try
{
driver = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
}
catch (MalformedURLException e)
{
System.out.println("URL init error");
}
}
#After
public void tearDown () throws Exception {
driver.quit();
}
#Test
public void addNewContact (){
System.out.println (driver);
WebElement addContactButton = driver.findElementById("com.example.android.contactmanager:id/addContactButton");
addContactButton.click();
}
}`
The exception I get is :
java.lang.NullPointerException
at addContact.addNewContact(addContact.java:49)
and the line this occurs in is :
WebElement addContactButton = driver.findElementById("com.example.android.contactmanager:id/addContactButton");
The reason it showing as null pointer because you are using "testng" annotation for "Tests" and "junit" annotation for "Before and after". Change import org.testng.annotations.Test; to import org.junit.Test; and run it as junit test.
This should work, just tested it on my side.

Categories