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.
Related
I've run into the following error."Cannot instantiate class co.edureka.tests.FBLoginTest". Below I've posted the entire error console. I'm trying to use POM (Page Obeject Model) for Selenium. I'm believe the issue has to do with me creating too many drivers... I've been digging through online resources, but haven't found anything that resolves my issue.
FBLoginPage.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class FBLoginPage {
WebDriver driver;
public FBLoginPage(WebDriver driver) {
this.driver=driver;
}
#FindBy(how=How.XPATH, using="/html/body/div[1]/div[1]/div[1]/div/div/div/div[2]/div/div[1]/form/div[1]/div[1]/input")
public WebElement emailTextBox;
#FindBy(how=How.XPATH, using="//input[#type='password'][#name='pass']") WebElement passwordTextBox;
#FindBy(how=How.XPATH, using="//input[#type='submit'][#value='Log In']") WebElement signinButton;
// Defining all the user actions (Methods) that can be performed in the Facebook home page
// This method is to set Email in the email text box
public void setEmail(String strEmail) {
emailTextBox.sendKeys(strEmail);
}
public void setPassword(String strPassword) {
passwordTextBox.sendKeys(strPassword);
}
// This method is to click on Login Button
public void clickOnLoginButton() {
signinButton.click();
}
}
FBHomePage.java
package co.edureka.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class FBHomePage {
WebDriver driver;
public FBHomePage(WebDriver driver) {
this.driver=driver;
}
#FindBy(how=How.XPATH, using="//div[text()='Account Settings']") WebElement profileDropdown;
#FindBy(how=How.LINK_TEXT, using="Log Out") WebElement logoutLink;
// Defining all the user actions (Methods) that can be performed in the Facebook home page
public void clickOnProfileDropdown() {
profileDropdown.click();
}
public void clickOnLogoutLink() {
logoutLink.click();
}
}
TestBase.java
package co.edureka.tests;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
public class TestBase {
public static WebDriver driver;
#BeforeSuite
public void initialize() throws IOException{
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
}
#AfterSuite
public void TeardownTest()
{
TestBase.driver.quit();
}
}
FBLoginTest.java
package co.edureka.tests;
import java.time.Duration;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import co.edureka.pages.FBHomePage;
import co.edureka.pages.FBLoginPage;
public class FBLoginTest extends TestBase {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
#Test
public void init() throws Exception{
//driver.get("https://www.facebook.com");
FBLoginPage loginpage = PageFactory.initElements(driver, FBLoginPage.class);
wait.until(ExpectedConditions.titleContains("Facebook"));
loginpage.setEmail("432547#gmail.com");
loginpage.setPassword("ashish.bakshi#selenium");
loginpage.clickOnLoginButton();
FBHomePage homepage = PageFactory.initElements(driver, FBHomePage.class);
homepage.clickOnProfileDropdown();
homepage.clickOnLogoutLink();
}
}
Error Console Results
[RemoteTestNG] detected TestNG version 7.4.0
org.testng.TestNGException:
Cannot instantiate class co.edureka.tests.FBLoginTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.InstanceCreator.instantiateUsingDefaultConstructor(InstanceCreator.java:193)
at org.testng.internal.InstanceCreator.createInstanceUsingObjectFactory(InstanceCreator.java:113)
at org.testng.internal.InstanceCreator.createInstance(InstanceCreator.java:79)
at org.testng.internal.objects.SimpleObjectDispenser.dispense(SimpleObjectDispenser.java:25)
at org.testng.internal.objects.GuiceBasedObjectDispenser.dispense(GuiceBasedObjectDispenser.java:30)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:112)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:165)
at org.testng.TestClass.getInstances(TestClass.java:122)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:102)
at org.testng.TestClass.init(TestClass.java:94)
at org.testng.TestClass.<init>(TestClass.java:59)
at org.testng.TestRunner.initMethods(TestRunner.java:463)
at org.testng.TestRunner.init(TestRunner.java:339)
at org.testng.TestRunner.init(TestRunner.java:292)
at org.testng.TestRunner.<init>(TestRunner.java:223)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.ITestRunnerFactory.newTestRunner(ITestRunnerFactory.java:55)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:659)
at org.testng.SuiteRunner.init(SuiteRunner.java:173)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:107)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1300)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1276)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1125)
at org.testng.TestNG.runSuites(TestNG.java:1063)
at org.testng.TestNG.run(TestNG.java:1031)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:79)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:23)
... 29 more
Caused by: java.lang.IllegalArgumentException: Input must be set
at org.openqa.selenium.internal.Require.nonNull(Require.java:59)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:97)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:77)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:46)
at co.edureka.tests.FBLoginTest.<init>(FBLoginTest.java:15)
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
... 32 more
If anyone has any suggestions I would appreciate it.
To solve this issue you should move the WebDriverWait initialization to the init or any other method in FBLoginTest.java like below.
package co.edureka.tests;
import java.time.Duration;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import co.edureka.pages.FBHomePage;
import co.edureka.pages.FBLoginPage;
public class FBLoginTest extends TestBase {
WebDriverWait wait;
#BeforeMethod
public void init() {
wait = new WebDriverWait(driver, Duration.ofSeconds(30));
}
#Test
public void testLogin() throws Exception {
driver.get("https://www.facebook.com");
FBLoginPage loginpage = PageFactory.initElements(driver, FBLoginPage.class);
wait.until(ExpectedConditions.titleContains("Facebook"));
loginpage.setEmail("432547#gmail.com");
loginpage.setPassword("ashish.bakshi#selenium");
loginpage.clickOnLoginButton();
FBHomePage homepage = PageFactory.initElements(driver, FBHomePage.class);
homepage.clickOnProfileDropdown();
homepage.clickOnLogoutLink();
}
}
`# 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 am a newbie in Java and Selenium.
Below are my java classes for POM, Driver Utilites and Test Case.
When I run the Test Case as TestNG test, I have :
FAILED: verifyLogin
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence[])" because "this.userName" is null.
Please help me out. Let me know if further info is needed.
Thanks in advance.
<----------------------------------------POM-------------------------------------------------->
package com.inetBankingV1.pageObjects;
import org.openqa.selenium.WebDriver;
import com.inetBankingV1.utilities.callBrowserDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage {
WebDriver driver;
#FindBy(how=How.LINK_TEXT, using="Log in")
WebElement logUser;
#FindBy(how=How.NAME, using="username")
WebElement userName;
#FindBy(how=How.NAME, using="password")
WebElement passWord;
//constructor
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
public void loginCheck(String uname,String passwd)
{
userName.sendKeys(uname);
passWord.sendKeys(passwd);
logUser.click();
}
}
<----------------------------------------Driver------------------------------------------------>
package com.inetBankingV1.utilities;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class callBrowserDriver {
public WebDriver startApplication(String browser, String baseURL, WebDriver driver)
{
if(browser.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.gecko.driver", "./Drivers/geckodriver.exe");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability("marionette", true);
driver = new FirefoxDriver(firefoxOptions);
}
if(browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
driver=new ChromeDriver();
}
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to(baseURL);
return driver;
}
}
<--------------------------------------Test Case----------------------------------------------->
package com.inetBankingV1.testCases;
import com.inetBankingV1.utilities.callBrowserDriver;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import com.inetBankingV1.pageObjects.LoginPage;
public class TC2_VerifyLogin {
WebDriver driver;
callBrowserDriver browserDriver=new callBrowserDriver();
#Test
public void verifyLogin()
{
driver=browserDriver.startApplication("chrome","https://demosite.com/",this.driver);
LoginPage login=new LoginPage(driver);
login.loginCheck("admin","Password");
}
}
See if this works:-
#FindBy(how=How.ID, using="inline-search-submit")
WebElement logUser;
#FindBy(how=How.NAME, using="user")
WebElement userName;
#FindBy(how=How.NAME, using="pass")
WebElement passWord;
The issue is resolved after initialising the webelements of the POM class using initElements:
LoginPage login=PageFactory.initElements(driver, LoginPage.class);
Use below line in your constructor
PageFactory.initElements( driver, this);
----------------------------------------------
public LoginPage(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements( driver, this);
}
This should solve your problem.
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 .
I have this class SignIn:
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import pageObject.devSplashScreenPage;
import utility.BrowserType;
import utility.Constant;
import appModule.SignIn_Action;
public class SignIn {
public WebDriver driver;
#BeforeMethod
#Parameters("browser")
public void SetUp(String browser) {
BrowserType.Execute(driver, browser);
}
#Test
public void signIn() {
// Call Sign In function
SignIn_Action.Execute(driver, Constant.StudentUsername, Constant.StudentPassword);
}
#AfterMethod
public void Teardown() {
driver.quit();
}
}
Where I am calling this code below which chooses the specific browser by the parameter that is passed. It works perfectly fine, it picks up the right browser and executes.
package utility;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserType {
#Test
public static void Execute(WebDriver driver, String browser) {
// Set Browsers
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("chrome")) {
{System.setProperty("webdriver.chrome.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/chromedriver.exe");}
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("ie")) {
{System.setProperty("webdriver.ie.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/IEDriverServer.exe");}
driver = new InternetExplorerDriver();
{DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
iecapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);}
}
// Implicit Wait and Maximize browser
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Navigate to URL
driver.get(Constant.URL);
}
}
So everything executes perfectly fine in #BeforeMethod, the issue I have is the test stops because the driver doesn't pass from #BeforeMethod to #Test.
How can I get the driver that is initiated by running BrowserType.class into the #Test Sign_in.class. I guess how can i return the driver properly from browsertype and call it in Sign_in #Test.
Thanks
You should make your Execute function return the driver:
public static WebDriver Execute(String browser) {
...
return driver;
}
In your test:
public void SetUp(String browser) {
driver = BrowserType.Execute(browser);
}
Solved like this:
BrowserType.java:
package utility;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class BrowserType {
#Test
public static WebDriver Execute(String browser) {
// Set Browsers
WebDriver driver = null;
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("chrome")) {
{System.setProperty("webdriver.chrome.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/chromedriver.exe");}
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("ie")) {
{System.setProperty("webdriver.ie.driver","C:/Users/elsid/Desktop/Eclipse/Selenium/IEDriverServer.exe");}
driver = new InternetExplorerDriver();
{DesiredCapabilities iecapabilities = DesiredCapabilities.internetExplorer();
iecapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);}
}
// Implicit Wait and Maximize browser
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// Navigate to URL
driver.get(Constant.URL);
return driver;
}
SignIn.java class:
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import pageObject.devSplashScreenPage;
import utility.BrowserType;
import utility.Constant;
import appModule.SignIn_Action;
public class SignIn {
public WebDriver driver;
#BeforeMethod
#Parameters("browser")
public void SetUp(String browser) {
driver = BrowserType.Execute(browser);
}
#Test
public void signIn() {
// Call Sign In function
SignIn_Action.Execute(driver, Constant.StudentUsername, Constant.StudentPassword);
}
#AfterMethod
public void Teardown() {
driver.quit();
}
}
The way your doing things can be greatly improved.
public class BrowserTest extends TestBase{
#Test(dataProvider="test1")
public static void execute(WebDriverHelper helper, String browser) {
// Set Browsers
driver.get(url);
Just pass the driver object (coming from the DataProvider). I assume your generating the driver instance within the DataProvider method since your test method is already parameterized and takes the driver.
public class TestBase {
private WebDriver driver;
...
#BeforeMethod
#Parameters("browser")
public void setUp(Object[] params) {
driver = (WebDriverHelper)params.get(1);
browserName = (String)params.get(2);
this.setTestName( params.get(0) + "-" + browserName;
driver.navigateTo(startUrl);
}
This code I show above wont compile but what I am trying to convey here is that you need to use the optional TestNG arg to the #BeforeMethod method, which is Object[] , and it gives you access to objects passed to test methods, BEFORE the test method is called, such as getting access to a "driver helper" created in the DataProvider factory, and then doing some Capabilities setup on that before the test is ran.
#DataProvider(name = "test1")
public Object[][] createData1() {
return new Object[][] {
{ "Cedric", new WebDriverHelper(), "firefox" },
{ "Anne", new WebDriverHelper(), "chrome"}
};
}
public class TestSuiteDriver {
private static WebDriver driver;
#BeforeClass
public static void setUp(){
System.setProperty("webdriver.chrome.driver", "/Users/Kimberleyross/chromedriver");
driver = new ChromeDriver();
}
public static WebDriver getDriver() {
return TestSuiteDriver.driver;
}
}