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);
Related
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).
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.
I'm writing a Java servlet using Selenium + PhantomJS to log into Alipay (it's like Chinese version of Paypal). I want to get the authentication code by taking screenshot of the login page. My code is as below:
package com.alipay.login.test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.Constants;
public class alipayGetAuthCodeServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public byte[] takeScreenshot() throws IOException {
TakesScreenshot takesScreenshot = (TakesScreenshot) Constants.driver;
return takesScreenshot.getScreenshotAs(OutputType.BYTES);
}
public BufferedImage createElementImage(WebElement webElement)
throws IOException {
Point location = webElement.getLocation();
Dimension size = webElement.getSize();
System.out.println(location + " / " + size);
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(takeScreenshot()));
/*BufferedImage croppedImage = originalImage.getSubimage(
location.getX(),
location.getY(),
size.getWidth(),
size.getHeight());*/
return originalImage; // here I return the full screenshot for testing
}
protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takeScreenshot", true);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "F:\\phantomjs-2.0.0-windows\\bin\\phantomjs.exe");
Constants.driver = new PhantomJSDriver(caps);
Constants.driver.get("https://auth.alipay.com/login/index.htm");
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
Constants.img = Constants.driver.findElement(By.id("J-checkcode-img")).getAttribute("src");
} catch (Exception e1) {
}
if (!Constants.img.equals("")) {
BufferedImage captcha = createElementImage(Constants.driver.findElement(By.id("J-checkcode-img")));
response.setContentType("image/jpeg");
try {
ImageIO.write(captcha, "jpeg", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
When I run my servlet, the screenshot I get is like this: http://i.stack.imgur.com/rBxI9.png
However, if I use ChromeDriver instead of PhantomJSDriver, the screenshot would be like this: http://i.stack.imgur.com/UgaB4.jpg, which is what the login page should be like.
So the screenshot taken by PhantomJSDriver has wrong color (I have no idea about this), wrong size (seems that I can handle this) and most importantly, no authentication code. I have checked the html source code returned by both drivers and found that the div of auth code in PhantomJS has a class of "ui-form-item fn-hide" while the counterpart has a class of "ui-form-item". Is it because the server of Alipay examines what browser I'm using and returns different pages accordingly?
Also I cannot login with only username and password using PhantomJS so I guess I do need an auth code.
Sorry for this long question and thanks in advance for any help!
I downloaded the code below and used it for some tests and u=it ran yesterday but since today the code stopped working. My tests are failing now which was not happening before. It throws up an error saying org.openqa.selenium.ElementNotVisibleException: element is not currently visible so cannot interact with element.
package org.openqa.selenium.example;
//import org.openqa.selenium.browserlaunchers.locators.GoogleChromeLocator;
//import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
//import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.net.UrlChecker;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class KongaUrlTest
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://www.konga.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testFirefoxWebdriver() throws Exception
{
driver.get(baseUrl);
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();
try
{
assertEquals("Phones & Tablets | Konga Nigeria", driver.getTitle());
System.out.println(driver.getTitle());
}
catch (Error e)
{
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception
{
System.out.println(driver.getCurrentUrl());
driver.quit();
}
}
There's a blocking dialog being displayed. It's probably displayed each time Selenium opens a new browser and navigates to that site. Close that dialog first:
driver.get(baseUrl);
try
{
driver.findElement(By.cssSelector(".fancybox-close")).click();
}
catch { }
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();
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);