Annotations not firing in SharedDriver with cucumber-jvm - java

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.

Related

TestNG NullPointer Exception in Extent Report with Selenium and Page Object Model

`# 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

Java Selenium - page object model - webdriver null pointer exception error

Feature file:
Feature: test of a webpage
#desktop
Scenario: Test landing page
Given Customer is on landing page
This is the step definition file:
import io.cucumber.java.Before;
import io.cucumber.java.BeforeAll;
import io.cucumber.java.Scenario;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.assertj.core.api.Assertions;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import pages.Landing Page;
import utils.BasePage;
import utils.ConfigureDriver;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static utils.BasePage.driver;
public class LandingPageStepDefs {
LandingPage landingPage = new LandingPage(driver);
ScenarioContext scenarioContext = new ScenarioContext();
ConfigureDriver configureDriver = new ConfigureDriver();
#Given("Customer is on landing page")
public void customer_is_on_landing_page () {
landingPage.clickConsent();
}
#Before("not #mobile")
public void beforeDesktop(Scenario scenario) {
configureDriver.configureDesktop();
}
This is the LandingPage:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import utils.BasePage;
public class LandingPage extends BasePage {
public LandingPage (WebDriver driver) {
super(driver);
}
public void clickConsent() {
driver.findElement(By.xpath("//*[#id=\"cookie-terms\"]/div/div/button/i")).click();
}
}
This is the BasePage:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.Arrays;
public class BasePage {
public static WebDriver driver;
public BasePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public static WebDriver getDriver() {
return driver;
}
}
This is ConfigureDriver Page
package utils;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class ConfigureDriver {
public void configureDesktop() {
ChromeOptions chromeOptions = new ChromeOptions();
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.page.com/");
}
}
There is null pointer exception in step def here. Could you tell how to get rid of it ? Thanks in advance.
landingPage.clickConsent();
You have to inherit the BasePage class from ConfigureDriver class, also you have to modify the WebDriver initialization line:
public class ConfigureDriver extends BasePage {
public ConfigureDriver(WebDriver driver) {
super(driver);
}
public void configureDesktop() {
ChromeOptions chromeOptions = new ChromeOptions();
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(chromeOptions); // modified this line
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.manage().window().maximize();
driver.get("https://www.page.com/");
}
}
Next time, post your question in brief and clear, also do the correct indentation.

How to call screenshot method from one class to other class?How to take screenshot of home page after navigating in to my code?

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();

There is an error in the public void Setup().The error is The method Setup() is undefined for the type jammytestappium

Below code has an error is at the setup location.Why is this error coming up?? .The error is as follow:
There is an error in the public void Setup().
The error is The method Setup() is undefined for the type jammytestappium.
This was causing harm while executing the code.
My code looks as follows:
package com.example.jamappium;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Driver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.server.handler.FindElement;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.sun.jna.platform.win32.SetupApi;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
public class Jammytestappium {
{
AndroidDriver<WebElement> abcd;
#BeforeClass
public void setup()
{
DesiredCapabilities test=new DesiredCapabilities();
test.setCapability(AndroidMobileCapabilityType.APP_PACKAGE,
"com.veronicapps.veronica.simplecalculator");
test.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY,
"com.veronicapps.veronica.simplecalculator.MainActivity");
test.setCapability(MobileCapabilityType.VERSION, "4.2.2");
test.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator");
abcd = (AndroidDriver) new RemoteWebDriver(new URL(
"http://127.0.0.1:4723/wd/hub"),test);
}
}
Try removing the extra braces after "public class jammytestappium {"

How to identify Max rows in web table using Selenium

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();

Categories

Resources