I am trying to add the failed methodName to the screenshot that is taken when a failure occurs while running selenium using java. Ive tried multiple solutions around the net but they all wind up returning the methodName of the rule class or methodName. I am not sure how to make it so the screenshot file name returns 'shouldFail_date.png'.
package test;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ScreenShotRule extends TestWatcher {
private WebDriver browser;
public ScreenShotRule(WebDriver browser) {
this.browser = browser;
}
#Override
protected void failed(Throwable e, Description description) {
TakesScreenshot takesScreenshot = (TakesScreenshot) browser;
File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
File destFile = getDestinationFile();
try {
FileUtils.copyFile(scrFile, destFile);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
#Override
protected void finished(Description description) {
browser.close();
}
private File getDestinationFile() {
Throwable t = new Throwable();
String callerMethodName = t.getStackTrace()[1].getMethodName();
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy");
String userDirectory = "screenshots/" + dateFormat.format(new Date()) + "/";
new File(userDirectory).mkdirs();
String absoluteFileName = userDirectory callerMethodName + dateFormat.format(new Date()) + ".png";
return new File(absoluteFileName);
}
}
package test;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotTest {
private WebDriver browser = new FirefoxDriver();
#Rule
public ScreenShotRule screenShootRule = new ScreenShotRule(browser);
#Test
public void shouldFail() {
browser.get("http://www.google.com");
By link = By.partialLinkText("I do not expect to find a link with this text");
browser.findElement(link);
}
}
You can use one of the efficient selenium testing-frameworks - ISFW that is based on testng and provides descriptive reporting with the need you have. Here are some of the snapshots
Overview
Detail Report
Related
I have created maven project, written some selenium testcases using java, basically I want to login on azure portal & I want to test Resource Group(Name, location & tags). I m using data driven framework. I m taking Test Data & expected data from excel file(.xlsx file), comparing it with Actual value & writing status(pass/fail) & actual data in same excel file. so for that I have written login testcase inside login class & written another testcase which is Resource Group test script inside resource group class, now I want to run both test script which is login & resource group, first the login will run & then resource group test script, resource group test script depends upon login test script.
so anybody can tell how we can do this.
# login test script
package frameworkvalidator;
import FrameworkValidator_Constants.Congig;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.maven.plugins.surefire.report.*;
import frameworkvalidator.TakeScreenshot;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Login {
public WebDriver driver;
#Test
public static void login() throws Exception
{ WebDriverManager.chromedriver().setup();
///System.setProperty("webdriver.chrome.driver",FrameworkValidator_Constants.Congig.chrome_driver_path);
WebDriver driver = new ChromeDriver();
// this.driver= new ChromeDriver();
driver.manage().window().maximize();
// driver.navigate().to(FrameworkValidator_Constants.Congig.baseUrl);
driver.get(FrameworkValidator_Constants.Congig.baseUrl);
try {
Thread.sleep(1000, 500);
driver.findElement(By.id("i0116")).sendKeys(FrameworkValidator_Constants.Congig.username);
Thread.sleep(2000, 1000);
driver.findElement(By.id("idSIButton9")).click();
Thread.sleep(2000, 1000);
driver.findElement(By.id("i0118")).sendKeys(FrameworkValidator_Constants.Congig.password);
Thread.sleep(2000, 1000);
driver.findElement(By.id("idSIButton9")).click();
Thread.sleep(2000, 1000);
driver.findElement(By.id("idSIButton9")).click();
Thread.sleep(2000, 1000);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,"C:\\sjava\\screenshots\\login.png" );
String actualUrl="https://portal.azure.com/#home";
String expectedUrl= driver.getCurrentUrl();
Assert.assertEquals(expectedUrl,actualUrl);
//driver.close();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test Resource Group
package Validation;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
//import drivers.DriverManager;
//import drivers.DriverManagerFactory;
//import org.selenium.enums.DriverType;
//import org.selenium.listeners.AnnotationTransformer;
//import org.selenium.listeners.ListenerClass;
//import org.selenium.listeners.MethodInterceptor;
//import org.selenium.reports.ExtentLogger;
//import org.selenium.utils.CookieUtils;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Listeners;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import FrameworkValidator_Constants.Locator_Constants;
import FrameworkValidator_Constants.Congig;
import frameworkvalidator.Xlsx_Reader;
import frameworkvalidator.Login;
public class Test_ResourceGroup {
Xlsx_Reader reader =new Xlsx_Reader(FrameworkValidator_Constants.Congig.Excels_file_path);
String sheetname="RG";
//public static WebDriver driver;
WebDriver driver = new ChromeDriver();
public Test_ResourceGroup(){
}
#org.junit.Test
public void Resource_group_search() throws InterruptedException {
driver.findElement(By.linkText("Resource groups")).click();
Thread.sleep(3000, 1000);
String test_result = reader.getCellData(sheetname,"TEST DATA", 2);
Thread.sleep(4000, 2000);
driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_SEARCH)).sendKeys(test_result);
Thread.sleep(4000, 2000);
driver.findElement(By.linkText("test_result")).click();
Thread.sleep(4000, 2000);
}
#org.testng.annotations.Test
public void ResourceGroupName() throws Exception{
String resourceGroupNameElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_NAME_XPATH)).getText();
String expectedResult = reader.getCellData(sheetname,"EXPECTED RESULT",2);
if( resourceGroupNameElement== expectedResult) {
String status= "passed";
}
else {
String status="failed";
}
String status = writer.writeCellData(sheetname,"PASSED/FAILED/SKIP",2);
String actualData = writer.writeCellData(sheetname,"ACTUAL DATA",2);
// Highlighting element & Taking screenshot
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].style.background='yellow'", resourceGroupNameElement);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,FrameworkValidator_Constants.Congig.Screenshot_folder_path + "T001" );
}
#Test
public void ResourceGroupLocation() throws Exception{
String resourceGroupLocationElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_LOCATION_XPATH)).getText();
String expectedResult = reader.getCellData(sheetname,"EXPECTED RESULT",3);
if( resourceGroupLocationElement== expectedResult) {
String status= "passed";
}
else {
String status="failed";
}
String status = writer.writeCellData(sheetname,"PASSED/FAILED/SKIP",3);
String actualData = writer.writeCellData(sheetname,"ACTUAL DATA",3);
//Highlighting element & Taking screenshot
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].style.background='yellow'", resourceGroupLocationElement);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,FrameworkValidator_Constants.Congig.Screenshot_folder_path + "T002" );
}
#Test
public void ResourceGroupTag() throws Exception{
String resourceGroupTagElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Locator_Constants.RESOURCE_GROUP_TAGS_XPATH)).getText();
String expectedResult = reader.getCellData(sheetname,"EXPECTED RESULT",4);
if( resourceGroupTagElement== expectedResult) {
String status= "passed";
}
else {
String status="failed";
}
String status = writer.writeCellData(sheetname,"PASSED/FAILED/SKIP",4);
String actualData = writer.writeCellData(sheetname,"ACTUAL DATA",4);
//Highlighting element & Taking screenshot
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].style.background='yellow'", resourceGroupTagElement);
frameworkvalidator.TakeScreenshot.takeSnapShot(driver,FrameworkValidator_Constants.Congig.Screenshot_folder_path + "T003" );
}
public static void Test_ResourceGroupMain() throws Exception {
Test_ResourceGroup demo= new Test_ResourceGroup();
demo.Resource_group_search();
demo.ResourceGroupName();
demo.ResourceGroupLocation();
demo.ResourceGroupTag();
//Test_ResourceGroup.
//Test_ResourceGroup.ResourceGroupName();
//Test_ResourceGroup.ResourceGroupLocation();
//Test_ResourceGroup.ResourceGroupTag();
//driver.close();
}
}
How to call screenshot method from one class to other class?
How to take screenshot home page after logging in to my code?
Below are the classes:-
Properties class:
package basepackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.io.FileHandler;
public class PropertiesClass extends BaseClass {
public static String propfile(String username) throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\pushk\\eclipse-workspace\\com.org.swag\\config.prop");
prop.load(fis);
return prop.getProperty(username);
}
public static void loginscreenshot() throws Exception {
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileHandler.copy(file, new File("C:\\Users\\pushk\\eclipse-workspace\\com.org.swag\\Screenshots.png"));
}
LoginPageClass:
package com.org.swag.Page;
import org.openqa.selenium.support.PageFactory;
import com.org.swag.pageobject.LoginPageObjects;
import basepackage.BaseClass;
import basepackage.PropertiesClass;
public class LoginPage extends BaseClass {
public void loginpage() throws Exception {
LoginPageObjects lpo = PageFactory.initElements(driver, LoginPageObjects.class);
lpo.username.sendKeys(PropertiesClass.propfile("username"));
lpo.password.sendKeys(PropertiesClass.propfile("password"));
lpo.loginsubmit.click();
lpo.menu.click();
lpo.logout.click();
}
}
Simply call the static screenshot method from another class (which imports basepackage.PropertiesClass) at the desired step. In your code, add the call after logging in:
LoginPageObjects lpo = PageFactory.initElements(driver, LoginPageObjects.class);
lpo.username.sendKeys(PropertiesClass.propfile("username"));
lpo.password.sendKeys(PropertiesClass.propfile("password"));
lpo.loginsubmit.click();
PropertiesClass.loginscreenshot();
lpo.menu.click();
lpo.logout.click();
I am using PhantomJs Driver for Headless Testing , I am getting below exception
Sample code:
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestLogin {
WebDriver d;
#BeforeMethod
public void launh_Browser() {
System.setProperty("phantomjs.binary.path", "D:\\Selenium\\driver\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
d=new PhantomJSDriver(caps);
}
#Test
public void guru_banking_login_excel() throws Exception {
d.get("http://www.demo.guru99.com/V4/");
d.findElement(By.name("uid")).sendKeys("TestUser");
d.findElement(By.name("password")).sendKeys("testpwd");
d.findElement(By.name("btnLogin")).click();
try{
Alert alt = d.switchTo().alert();
String actualBoxMsg = alt.getText(); // get content of the Alter Message
assertEquals(actualBoxMsg,"User or Password is not valid");
alt.accept();
}
catch (NoAlertPresentException Ex){
String hometitle=d.getTitle();
assertEquals(hometitle,"Guru99 Bank Manager HomePage");
}
d.quit
}
Error Observed :
Exception : org.openqa.selenium.UnsupportedCommandException: Invalid Command Method - {"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","
I am trying to handle popup using phantomjs as a driver
Please help on This .........
Thanks in Advance..!!!!
You have to take care of a lot of points here in your code :
While working with PhantomJS when you mention System.setProperty use the following code lines instead :
File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
DesiredCapabilities type of objects must be initiated with reference to DesiredCapabilities class only. So change to :
DesiredCapabilities caps = new DesiredCapabilities();
While using assertEquals use Assert.assertEquals as follows :
Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
//
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
As you are using TestNG, for Assert, use org.testng.Assert; instead of static org.testng.Assert.assertEquals; as an import :
import org.testng.Assert;
You need to wrap up the line d.quit() within a separate TestNG Annotated function too as follows :
#AfterMethod
public void tearDown() {
d.quit();
}
Here is your own code block which executes successfully :
package headlessBrowserTesting;
import java.io.File;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class PhantomJS_webdriver_binary
{
WebDriver d;
#BeforeMethod
public void launh_Browser() {
File src = new File("C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.setProperty("phantomjs.binary.path", src.getAbsolutePath());
DesiredCapabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
d=new PhantomJSDriver(caps);
}
#Test
public void guru_banking_login_excel() throws Exception {
d.get("http://www.demo.guru99.com/V4/");
d.findElement(By.name("uid")).sendKeys("TestUser");
d.findElement(By.name("password")).sendKeys("testpwd");
d.findElement(By.name("btnLogin")).click();
try{
Alert alt = d.switchTo().alert();
String actualBoxMsg = alt.getText();
Assert.assertEquals(actualBoxMsg,"User or Password is not valid");
alt.accept();
}
catch (NoAlertPresentException Ex){
String hometitle=d.getTitle();
Assert.assertEquals(hometitle,"Guru99 Bank Manager HomePage");
}
}
#AfterMethod
public void tearDown() {
d.quit();
}
}
I am trying to read csv files for my login test case in selenium, I have done this part in the fast (i.e: Code worked for fetching data from csv), But for this code some how I am not able to get what is wrong. Please help me in solving this one..I a writing this code in the Base file, and that method I will be calling in some other file.
Below is one code file, where that Error is displayed.
Note: I have made the line where the error "The constructor CSVReader(FileReader) is undefined" is displayed
package com.gptoday.com.gptoday.testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import com.gargoylesoftware.htmlunit.javascript.host.file.FileReader;
import java.io.Reader;
import com.opencsv.CSVReader;
public class Base {
public WebDriver driver;
#BeforeMethod
public void BaseSetup(){
ProfilesIni prof = new ProfilesIni();
FirefoxProfile ffProfile= prof.getProfile ("vishvesh");
ffProfile.setAcceptUntrustedCertificates(true);
ffProfile.setAssumeUntrustedCertificateIssuer(false);
String BaseUrl = "https://www.gptoday.com";
System.setProperty("webdriver.gecko.driver", "G:/Workplace/AutomationSetupFiles/Geckdriver/geckodriver.exe");
driver = new FirefoxDriver (ffProfile);
driver.get(BaseUrl);
}
#AfterMethod
public void afterTest() {
System.out.println("Success");
}
public void CheckCurrentURL(WebDriver driver){
String actual_url;
actual_url=driver.getCurrentUrl();
}
public void csv(){
String csvpath = "G:/Workplace/Test Automation Project";
CSVReader reader = **new CSVReader(new FileReader(csvpath))**;
String[] cell=new String[1000];
while ((cell = reader.readNext())!=null)
{
System.out.println("After while loop");
System.out.println("After for loop");
String name = cell[0];
System.out.println("name displayed = "+name );
String email = cell[1];
System.out.println("email displayed ="+email );
String message = cell[2];
System.out.println("message displayed="+message);
//driver.findElement(username).sendKeys(name);
//driver.findElement(password).sendKeys(email);
}
}
}
import "java.io.FileReader" and the error should go.
This is driving me nuts. I'm running a test framework using cucumber-jvm and trying to get it to take screenshots.
I have looked at the java-webbit-websockets-selenium example that's provided and have implemented the same method of calling my webdriver using the SharedDriver module.
For some reason, my #Before and #After methods are not being called (I've put print statements in there). Can anyone shed any light?
SharedDriver:
package com.connectors;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.Scenario;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import java.util.concurrent.TimeUnit;
public class SharedDriver extends EventFiringWebDriver {
private static final WebDriver REAL_DRIVER = new FirefoxDriver();
private static final Thread CLOSE_THREAD = new Thread() {
#Override
public void run() {
REAL_DRIVER.close();
}
};
static {
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
}
public SharedDriver() {
super(REAL_DRIVER);
REAL_DRIVER.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
REAL_DRIVER.manage().window().setSize(new Dimension(1200,800));
System.err.println("DRIVER");
}
#Override
public void close() {
if(Thread.currentThread() != CLOSE_THREAD) {
throw new UnsupportedOperationException("You shouldn't close this WebDriver. It's shared and will close when the JVM exits.");
}
super.close();
}
#Before()
public void deleteAllCookies() {
manage().deleteAllCookies();
System.err.println("BEFORE");
}
#After
public void embedScreenshot(Scenario scenario) {
System.err.println("AFTER");
try {
byte[] screenshot = getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (WebDriverException somePlatformsDontSupportScreenshots) {
System.err.println(somePlatformsDontSupportScreenshots.getMessage());
}
}
}
Step file:
package com.tests;
import com.connectors.BrowserDriverHelper;
import com.connectors.SharedDriver;
import com.connectors.FunctionLibrary;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.runtime.PendingException;
import org.openqa.selenium.*;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.support.events.EventFiringWebDriver;
/**
* Created with IntelliJ IDEA.
* User: stuartalexander
* Date: 23/11/12
* Time: 15:18
* To change this template use File | Settings | File Templates.
*/
public class addComponentsST {
String reportName;
String baseUrl = BrowserDriverHelper.getBaseUrl();
private final WebDriver driver;
public addComponentsST(SharedDriver driver){
this.driver = driver;
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#Given("^I have navigated to the \"([^\"]*)\" of a \"([^\"]*)\"$")
public void I_have_navigated_to_the_of_a(String arg1, String arg2) throws Throwable {
// Express the Regexp above with the code you wish you had
assertEquals(1,2);
throw new PendingException();
}
CukeRunner:
package com.tests;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#Cucumber.Options(tags = {"#wip"}, format = { "pretty","html:target/cucumber","json:c:/program files (x86)/jenkins/jobs/cucumber tests/workspace/target/cucumber.json" }, features = "src/resources/com/features")
public class RunCukesIT {
}
Put SharedDriver in the same package as RunCukesIT, i.e. com.tests.
When using the JUnit runner, the glue becomes the unit test package (here com.tests), and this is where cucumber-jvm will “scan” the classes for annotations.