Hello All,I wrote some code to access table value from website to Excel.but problem is that i don't find a solution to counting row available in my table.So please suggest me if any solution so i can resolve my problem.
My Code is:
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import jxl.Workbook;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label;
public class ExportinExcel {
public static WebDriver driver;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
driver=new FirefoxDriver();
driver.navigate().to("http://www.indianrail.gov.in/tatkal_Scheme.html");
driver.manage().timeouts().implicitlyWait(100, TimeUnit.MILLISECONDS);
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
driver.quit();
}
#Test
public void test() throws IOException, RowsExceededException, WriteException {
//fail("Not yet implemented");
// Given the path where to store Excel.
File FExcel = new File("D:\\software\\Excel\\createExcel"+hashCode()+".xls");
/* Create a Workbook. */
WritableWorkbook workbookexcel= Workbook.createWorkbook(FExcel);
/* Create a Worksheet. */
workbookexcel.createSheet("Data", 0);
WritableSheet writeablesheet= workbookexcel.getSheet(0);
/* Add Content in row and column and here coumn value increment each time. */
// jxl.write.Label Data1 = new jxl.write.Label(row,column, driver.findElement(By.xpath(".//tr[1]/td[1]/p/b/span")).getText());
int i=0;int j;int x=1; int y;
while(i<3)
{ j=0;
for(;j<3;)
{
**// Here i have to entered Manually Number of data as 7 which i need dynamically.**
for(y=1;y<=7;y++)
{
jxl.write.Label Data1 = nw jxl.write.Label(i, j, driver.findElement(By.xpath(".//tr["+y+"]/td["+x+"]/p/b/span")).getText());
writeablesheet.addCell(Data1);
j++;
}x++;
}i++;
}
System.out.print("11");
workbookexcel.write();
workbookexcel.close();
}
}
There you go:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
...
WebDriver driver = new FirefoxDriver();
driver.get("http://www.indianrail.gov.in/tatkal_Scheme.html");
WebElement table = driver.findElement(By.className("MsoNormalTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
int numOfRows = rows.size();
Related
`# Error:**
java.lang.NullPointerException: Cannot invoke "com.aventstack.extentreports.ExtentTest.log(com.aventstack.extentreports.Status, String)" because "testCases.uTest_Method.test" is null
at testCases.uTest_Method.exit_method(uTest_Method.java:93)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
... Removed 32 stack frames
this is the class i created for google search
Google_Search_Page
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
public class Google_Search_Page {
WebDriver driver;
By g_search_text=By.xpath("//*//input[#name='q']");
By utest=By.xpath("//*//h3[text()='uTest - The Professional Network for Testers']");
public Google_Search_Page(WebDriver driver)
{
this.driver=driver;
}
public void google_search(String key_text)
{
driver.manage().window().maximize();
driver.findElement(g_search_text).sendKeys(key_text,Keys.ENTER);
}
public void clickutest()
{
driver.findElement(utest).click();
}
}
this the class i created for next page functions
uTest_Home_Page.java
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class uTest_Home_Page {
WebDriver driver;
By bat_text=By.xpath("//*[#id=\"mainContent\"]/div[1]/div[2]/div/a");
public uTest_Home_Page(WebDriver driver)
{
this.driver=driver;
}
public void click_become_a_tester()
{
driver.findElement(bat_text).click();
}
}
this is Test case i created with extend report
uTest_Method.java
package testCases;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
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.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
import commonFunctions.Common_Functions;
import pageObjects.Google_Search_Page;
import pageObjects.uTest_Home_Page;
public class uTest_Method {
WebDriver driver;
String base_url = "https://www.google.com";
ExtentHtmlReporter reporter;
ExtentReports extent;
ExtentTest test;
#BeforeTest
public void launch_test()
{
reporter=new ExtentHtmlReporter("./uTest_Report/report1.html");
reporter.config().setDocumentTitle("uTest_Automation_Report");
reporter.config().setReportName("Functional_Test");
reporter.config().setTheme(Theme.DARK);
extent =new ExtentReports();
extent.attachReporter(reporter);
extent.setSystemInfo("Host_Name", "localhost");
extent.setSystemInfo("OS", "Windws10");
extent.setSystemInfo("Tester_Name", "PRAJIN");
extent.setSystemInfo("Browser_Name", "Chrome");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get(base_url);
}
#BeforeMethod
public void start_method()
{
}
#Test (priority = 0)
public void uTest_google()
{
Google_Search_Page ob1=new Google_Search_Page(driver);
ob1.google_search("uTest");
ob1.clickutest();
}
#Test (priority = 1)
public void uTest_Home()
{
uTest_Home_Page ob1=new uTest_Home_Page(driver);
ob1.click_become_a_tester();
}
#AfterMethod
public void exit_method(ITestResult result) throws IOException
{
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(Status.FAIL, "TestCase Failed is "+result.getName());
test.log(Status.FAIL, "TestCase Failed is "+result.getThrowable());
}
else if(result.getStatus()==ITestResult.SKIP)
{
test.log(Status.SKIP, "TestCase Skipped is "+result.getName());
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
test.log(Status.PASS, base_url);
}
}
#AfterTest
public void exit_test()
{
extent.flush();
//driver.quit();
}
}`
looks ExtentTest test; is not initialized. something like
test = report.startTest("ExtentDemo");
this link has example https://www.browserstack.com/guide/extent-reports-in-selenium
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();
}
}
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 new to selenium and java and trying to build a program and facing multiple issues. Listed is the code below for Parent Class.
Login Method error.
Void is an valid type error on Syntax error on token "(".
Even though i tried to change, still i face an error
package MyfirstMavenProject.Myfirstgmailtest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginClass {
//Open the Browser
public void BrowserOpen (String args[]) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
//Get the URL
driver.navigate().to("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1#identifier");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Identifies the gmail and password
public void Login (String args[]) {
WebElement emailfield = driver.findElement(By.id("Email"));
emailfield.sendKeys("abc.com");
driver.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#type='password']"))).sendKeys("abc");
driver.findElement(By.id("signIn")).click();
}
}
}
Child Class is where i am getting error on argument. Need info as to what argument should i pass. I am trying to use the Login method created in the above class
package MyfirstMavenProject.Myfirstgmailtest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ComposeEmailClass extends LoginClass {
//Method to identify the compose email
public void ComposeEmail (String args[]){
WebDriver ComposeEmail = new FirefoxDriver();
ComposeEmail.findElement(By.className("T-I J-J5-Ji T-I-KE L3")).click();
}` public static void main (String args[]){
ComposeEmailClass ClickCompose = new ComposeEmailClass();
ClickCompose.Login(args);`\\Need more info`
ClickCompose.ComposeEmail(args);
}FireFox.Quit;
}
Use following code:
There are lots of syntax error present in your code.
Login Class: Corrected
package MyfirstMavenProject.Myfirstgmailtest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginClass
{
WebDriver driver =null;
//Open the Browser
public void BrowserOpen (String args[])
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
//Get the URL
driver.navigate().to("https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1<mpl=default<mplcache=2&emr=1&osid=1#identifier");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
//Identifies the gmail and password
public void Login (String args[])
{
WebElement emailfield = driver.findElement(By.id("Email"));
emailfield.sendKeys("youremail#gmail.com");
driver.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//* [#type='password']"))).sendKeys("password");
driver.findElement(By.id("signIn")).click();
}
}
ComposeEmailClass: Corrected
package MyfirstMavenProject.Myfirstgmailtest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ComposeEmailClass extends LoginClass
{
//Method to identify the compose email
public void ComposeEmail(String args[])
{
WebDriver ComposeEmail = new FirefoxDriver();
ComposeEmail.findElement(By.className("T-I J-J5-Ji T-I-KE L3")).click();
}
public static void main(String args[])
{
ComposeEmailClass ClickCompose = new ComposeEmailClass();
ClickCompose.BrowserOpen(args);
ClickCompose.Login(args);
ClickCompose.ComposeEmail(args);
}
}
You have to Call ClickCompose.BrowserOpen(args); before ClickCompose.Login(args);
and String[] args is not required in your method declaration .
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.