Cucumber Framework setup - java

I was getting the following error message
The attribute value is undefined for the annotation type Given.
The import cucumber.annotation cannot be resolved
See code:
package annotation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
public class annotation {
WebDriver driver = null;
#Given("^I am on Facebook login page$")
public void goToFacebook() {
driver = new FirefoxDriver();
driver.navigate().to("https://www.facebook.com/");
}
#When("^I enter username as \"(.*)\"$")
public void enterUsername(String arg1) {
driver.findElement(By.id("email")).sendKeys(arg1);
}
#When ("^I enter password as \"(.*)\"$")
public void enterPassword(String arg1) {
driver.findElement(By.id("pass")).sendKeys(arg1);
driver.findElement(By.id("u_0_v")).click();
}
#Then("^Login should fail$")
public void checkFail() {
if(driver.getCurrentUrl().equalsIgnoreCase(
"https://www.facebook.com/login.php?login_attempt=1&lwv=110")) {
System.out.println("Test1 Pass");
} else {
System.out.println("Test1 Failed");
}
driver.close();
}
#Then("^Relogin option should be available$")
public void checkRelogin() {
if(driver.getCurrentUrl().equalsIgnoreCase(
"https://www.facebook.com/login.php?login_attempt=1&lwv=110")){
System.out.println("Test2 Pass");
} else {
System.out.println("Test2 Failed");
}
driver.close();
}
}

Use these import statements
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
Also not a great idea to name a class 'annotation' or a package the same and also use the naming standards. Like classes should begin with capitals.
http://www.oracle.com/technetwork/java/codeconventions-135099.html

Related

java.lang.NullPointerException error on Page Object Model with cucumber

I am getting java.lang.NullPointerException while following Page Object Model with Cucumber. I am not sure what I am doing wrong here, please help me on this
Below is my Test Base Class:
package com.qa.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class TestBase {
public static WebDriver driver;
public static Properties prop;
//public WebDriver initializeWebDriver() throws IOException
public static void initializeWebDriver() throws IOException
{
prop = new Properties();
FileInputStream fis = new FileInputStream("D:\\Automation\\WebAutomation\\src\\main\\java\\com\\qa\\config\\config.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
//Execute in Chrome
if(browserName.equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
driver=new ChromeDriver();
//driver.manage().window().maximize();
}
//Execute in FireFox
else if(browserName.equals("Firefox"))
{
System.setProperty("webdriver.gecko.driver","D:\\Drivers\\geckodriver-v0.19.1-win64(1)");
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.get(prop.getProperty("appURL"));
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
return driver;
}
}
Below is my login page Objects Class
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.util.TestBase;
public class LoginPage extends TestBase {
public LoginPage() {
/*super(driver);
this.driver=driver;*/
PageFactory.initElements(driver, this);
}
// Login Page Title
public String validateLoginPageTitle() {
return driver.getTitle();
}
// Welcome text
#FindBy(css=".login-form > h2:nth-child(1)")
WebElement header;
public String loginPageHeaderText() {
return header.getText();
}
}
Below is my Step Def
package com.qa.stepdefinations;
import java.io.IOException;
import org.testng.Assert;
import com.qa.pages.LoginPage;
import com.qa.util.TestBase;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginStepDef extends TestBase {
LoginPage LoginPage = new LoginPage();
#Given("^I launch browser and access the GE URL$")
public void i_launch_browser() throws IOException {
TestBase.initializeWebDriver();
}
#Then("^I am on Login Page$")
public void i_am_on_login_page() {
String expectedLoginPageTile = prop.getProperty("LoginPage_Title");
String actualLoginPageTitle = LoginPage.validateLoginPageTitle();
Assert.assertEquals(actualLoginPageTitle, expectedLoginPageTile);
}
#Then("^I verify header text is displaying$")
public void i_verify_header_text_is_displaying() {
String expectedHeaderText = prop.getProperty("LoginPage_Expected_Header");
String actualdHeaderText = LoginPage.loginPageHeaderText();
Assert.assertEquals(actualdHeaderText, expectedHeaderText);
}
}
The script is working fine for LoginPage.validateLoginPageTitle(); however, I am not sure why it is not working for the next step i.e. LoginPage.loginPageHeaderText();
It seems issue is with your locator, check if it is correct.
#FindBy(css="<b><em>.login-form > h2:nth-child(1)</em></b>")
WebElement header;

Missing return statement, how can I fix?

Goal: I have a class called "InvokeChromeTest" I'm extending to another class called "Base" to access chromedriver and data.properties. When running my code, I get the error:
Error:(22, 3) java: missing return statement
I am unsure how to fix this. Here is my sample code as follows. Please let me know what I can do to fix.
src/test/java/loginPage/InvokeChromeTest
package loginPage;
import credentials.ProfileCredentials;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import resources.Base;
public class InvokeChromeTest extends Base {
#Test
public WebDriver initializeDriver() {
driver = initializeDriver();
driver.get(dataProperties.getProperty("url"));
ProfileCredentials p = new ProfileCredentials(driver);
p.getAuthorize().click();
p.getApiKey().sendKeys("testKey");
p.getAuthCred().click();
p.getCloseAuth().click();
}
#AfterTest
public void teardown() {
driver.close();
}
}
src/main/java/resources/Base
package resources;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Base {
public WebDriver driver;
protected Properties dataProperties;
public WebDriver initializeDriver() {
// Create global property file
dataProperties = new Properties();
InputStream dataPropertiesInputStream = null;
try{
dataPropertiesInputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
dataProperties.load(dataPropertiesInputStream);
} catch (IOException e) {
e.printStackTrace();
}
String browserName = dataProperties.getProperty("browser");
System.out.println(browserName);
if (browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
src/main/java/credentials/ProfileCredentials
package credentials;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class ProfileCredentials {
WebDriver driver;
public ProfileCredentials(WebDriver driver) {
this.driver = driver;
}
private By authorize = By.xpath("//button[#class='btn authorize unlocked']");
private By apikey = By.xpath("//div[#class='wrapper']//section//input");
private By authorizecred = By.xpath("//button[#class='btn modal-btn auth authorize button']");
private By closeauth = By.xpath("//button[#class='btn modal-btn auth btn-done button']");
public WebElement getAuthorize() {
return driver.findElement(authorize);
}
public WebElement getApiKey() {
return driver.findElement(apikey);
}
public WebElement getAuthCred() {
return driver.findElement(authorizecred);
}
public WebElement getCloseAuth() {
return driver.findElement(closeauth);
}
}
I figured out the problem. "Base" and "InvokeChromeTest" had the same method name. This is why it was recursive.

Selenium + JUnit, Assertion error of proper page loaded

I've written a code using Selenium WD and JUnit that should check if proper page is loaded and the table of this page is not null
Besides assertion, to make sure that proper page is loaded (checking if URL contains specified text), I've put "if-else" statement in "waitUntilPageLoaded" method.
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GuruSearch
{
#Test
static void checkDemoLogin()
{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pansa\\Documents\\Webdrivers\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 10);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(FirefoxDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The "if-else" statement in "waitUntilPageLoaded" method returns "OK", but TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"))
throws AssertionError, although the text appears in the page.
Why there is AssertionError thrown?
As you are using the JUnit annotations, the annotated method shouldn't be static. I have modified your code a bit, try the below:
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.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.TestCase;
public class GuruSearch
{
#Test
public void checkDemoLogin()
{
System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 30);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(WebDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The above code is printing 'OK' and Assert condition also passing. And I think, it doesn't matter if we give upper/lower case in the contains. It will match both the cases.
I don't have Firefox in my system so I have checked with Chrome, you change the browser and try... I hope it helps...

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).

JUnit runner class unable to execute #before

below is the project structure:
project structure
Before After class
Test Runner class:
package runnerPackage;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions( plugin = {"html:target/cucumber-html-report",
"json:target/cucumber.json",
"pretty:target/cucumber-pretty.txt",
"usage:target/cucumber-usage.json"
},
features="classpath:MyFirstApp.feature",glue={"stepDefinitions"},tags=
{"#sceneOne1"})
public class TestRunner {
}
Feature file :
#tag
Feature: Test HDFC
#sceneOne1
Scenario: Test HDFC
Given I open HDFC Bank home page and click on 'Login' button
***********************************************
Step Definition :
package stepDefinitions;
import pages.MyFirstMethod;
import cucumber.api.java.en.Given;
public class MyFirstStepDefinition {
MyFirstMethod m=new MyFirstMethod();
#Given("^I open HDFC Bank home page and click on 'Login' button$")
public void iOpenHDFCBankHomePageAndClickOnLoginButton() throws
Throwable {
m.clickOnElement();
}
}
**********************************************
Before After class:
package runnerPackage;
import org.openqa.selenium.chrome.ChromeDriver;
import pages.ConfigReadFile;
import pages.PageInstances;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class BeforeAfter extends PageInstances{
#Before
public static void runBefore(Scenario scenario)
{
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32_2.26\\chromedriver.exe");
System.out.println("reached here");
driver=new ChromeDriver();
System.out.println(ConfigReadFile.URL);
driver.get(ConfigReadFile.URL);
}
#After
public static void runAfter()
{
System.out.println("do noting");
}
}
**********************************************************
Page Instances:
package pages;
import org.openqa.selenium.WebDriver;
public class PageInstances {
protected static WebDriver driver;
}
Method:
package pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.interactions.Actions;
public class MyFirstMethod extends PageInstances{
public void clickOnElement()
{
Actions action=new Actions(driver);
action.moveToElement(driver.findElement(By.xpath(".//*[#id='cee_closeBtn']/img[#alt='Close']"))).click();
action.perform();
//driver.findElement(By.xpath(".//*[#id='cee_closeBtn']/img[#alt='Close']")).click();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.findElement(By.id("loginsubmit")).click();
System.out.println(driver.getCurrentUrl());
//loginButton.click();
}
}
Configuration xml:
<ConfigurationFile.xml>
<url>some random url</url>
</ConfigurationFile.xml>
Configuration Read File :
package pages;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
public class ConfigReadFile {
public static final String URL;
static {
File f=new File("file path");
DocumentBuilderFactory
docbuildFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = docbuildFactory.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Document doc = null;
try {
doc = builder.parse(f);
} catch(Exception es)
{
}
URL=doc.getElementsByTagName("url").item(0).getTextContent();
System.out.println(URL);
}
}
I want to open chrome browser and hdfc link for each secnario so I have annotated it with #before
should mention glue={"stepDefinitions","runnerPackage"} so that it loads hooks class

Categories