I am trying to integrate testng with testrail but I am having a problem. Below the code is in my BaseTest. If I run testng on BaseTest it works and I see my result in testrail. If I move onboardingtest, changingToTest, and changingToAllListings to its own class, running testng will bomb the #BeforeMethod. I am not sure how to fix it. Can someone help? My guess is something wrong with #BeforeMethod. Maybe it shouldn't be Method m = BaseTest.class.getMethod(method.getName()); I have attached my error as well
package appiumStudio.appiumStudio;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.json.simple.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.*;
import api.APIException;
import api.APIClient;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
import pageObjects.Onboarding;
import pageObjects.Search;
import util.OnboardingFlow;
public class BaseTest {
protected static AndroidDriver<AndroidElement> driver = null;
String PROJECT_ID = "13";
APIClient client = null;
DesiredCapabilities dc = new DesiredCapabilities();
#BeforeSuite
public void createSuite(ITestContext ctx) throws MalformedURLException,IOException, APIException {
dc.setCapability(MobileCapabilityType.UDID, "6bf9c570");
dc.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.test.buyerapp.staging");
dc.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.tet.buyerapp.MainActivity");
driver = new AndroidDriver<AndroidElement>(new URL("http://localhost:4723/wd/hub"), dc);
driver.setLogLevel(Level.INFO);
client = new APIClient("https://test.testrail.io");
client.setUser("qa#test.com");
client.setPassword("password");
Map data = new HashMap();
data.put("include_all",true);
data.put("name","Test Run "+System.currentTimeMillis());
JSONObject c = null;
c = (JSONObject)client.sendPost("add_run/"+PROJECT_ID,data);
Long suite_id = (Long)c.get("id");
ctx.setAttribute("suiteId",suite_id);
driver.resetApp();
}
#BeforeMethod
public void beforeTest(ITestContext ctx,Method method) throws NoSuchMethodException {
Method m = BaseTest.class.getMethod(method.getName());
if (m.isAnnotationPresent(TestRails.class)) {
TestRails ta = m.getAnnotation(TestRails.class);
System.out.println(ta.id());
ctx.setAttribute("caseId",ta.id());
}
}
#TestRails(id="20178")
#Test(priority=1)
public void onboardingtest() throws InterruptedException {
OnboardingFlow.onboarding();
}
#TestRails(id="20176")
#Test(priority = 2)
public void changingToTest() throws InterruptedException {
Search.ToggleAllListings(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='Every available home for sale']")));
Search.SelectTestHomes(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='Self-tour Test homes']")));
Search.ClickGotIt(driver).click();
Thread.sleep(2000);
}
#TestRails(id="20177")
#Test(priority = 3)
public void changingToAllListings() {
Search.ToggleTestHomes(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='Self-tour instantly with app unlock']")));
Search.SelectAllListings(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='All listings']")));
}
#AfterMethod
public void afterTest(ITestResult result, ITestContext ctx) throws IOException, APIException {
Map data = new HashMap();
if(result.isSuccess()) {
data.put("status_id",1);
}
else {
data.put("status_id", 5);
data.put("comment", result.getThrowable().toString());
}
String caseId = (String)ctx.getAttribute("caseId");
Long suiteId = (Long)ctx.getAttribute("suiteId");
client.sendPost("add_result_for_case/"+suiteId+"/"+caseId,data);
}
#AfterClass
public void tearDown() {
driver.resetApp();
}
}
I get this error below whenI move onboardingtest, changingToTest, and changingToAllListings to its own class.
FAILED: beforeTest(org.testng.TestRunner#578524c3, public void searchHomeToggle.ToggleHome.beforeTest(org.testng.ITestContext,java.lang.reflect.Method) throws java.lang.NoSuchMethodException) java.lang.NoSuchMethodException: appiumStudio.appiumStudio.BaseTest.beforeTest()
at java.base/java.lang.Class.getMethod(Class.java:2114) at searchHomeToggle.ToggleHome.beforeTest(ToggleHome.java:23) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:584) at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:172) at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46) at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:804)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:145) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128) at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.testng.TestRunner.privateRun(TestRunner.java:770) at org.testng.TestRunner.run(TestRunner.java:591) at org.testng.SuiteRunner.runTest(SuiteRunner.java:402) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
at org.testng.SuiteRunner.run(SuiteRunner.java:304) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180) at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
at org.testng.TestNG.runSuites(TestNG.java:1032) at org.testng.TestNG.run(TestNG.java:1000) 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)
Related
I am using TestNG and Page Object Model.
I have created some test cases. I see that the first two test cases are working. But, the third test case starts on a new page which is opened by the second test case. I am unable to interact with the new page, and getting a Null Pointer Exception error. Not sure what went wrong.
I have three Java classes Here.
This is my base class:
package MYQC_Reusable_Classes;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
public class MYQC_Base_Class {
public static WebDriver driver = null;
// public static ExtentTest Logger = null;
// public static ExtentReports report = null;
#BeforeSuite
public void initialize() throws IOException {
// report = new ExtentReports("C:\\Users\\fhasan\\Desktop\\ExtentReport"+".html");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\fhasan\\Desktop\\driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();`enter code here`
// add the precondition arguments
options.addArguments("start-maximized", "incognito");
driver = new ChromeDriver(options);
// To maximize browser
driver.manage().window().maximize();
// Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#BeforeMethod
public void timer(){
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#AfterSuite
// Test cleanup
public void TeardownTest() throws InterruptedException {
Thread.sleep(4000);
MYQC_Base_Class.driver.quit();
}
}
This is my page class:
package MYQC_Browser_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 MYQC_Login_Page {
WebDriver driver;
// constructor that will be automatically called as soon as the object of the
// class is created
public MYQC_Login_Page(WebDriver driver) {
this.driver = driver;
}
#FindBy(how = How.ID, using = "loginName")
public static WebElement userNameField;
#FindBy(how = How.ID, using = "loginPassword")
public static WebElement passwordField;
#FindBy(how = How.ID, using = "loginButton")
public static WebElement clickLogin;
//Method to enter username
public void clickUserName() {
userNameField.click();
}
public void enterUserName(String user) {
userNameField.sendKeys(user);
}
public void clickPass() {
passwordField.click();
}
public void enterPassword(String pass) {
passwordField.sendKeys(pass);
}
//Method to click on Login button
public void clickLoginButton() {
clickLogin.click();
}
}
This is my first test case which works fine:
package MYQC_TestCase_Classes;
import MYQC_Browser_Pages.CUST4_MYQC_Login_Selection_Page;
import MYQC_Reusable_Classes.MYQC_Base_Class;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.util.PriorityQueue;
public class TC001_MYQC_Login_Selection_Button_Text extends MYQC_Base_Class {
#Test()
public void MYQC_Login_Button_Text() throws InterruptedException, IOException {
//creating anb object of the CUST4_MYQC_Login_Selection_Page
CUST4_MYQC_Login_Selection_Page go_To_MYQC_Page = PageFactory.initElements(driver, CUST4_MYQC_Login_Selection_Page.class);
// going to the cust4 myqc link
driver.get("https://mmhcustfour.com");
Thread.sleep(3000);
Assert.assertEquals(go_To_MYQC_Page.buttonText(), "Login with Quickcharge Authentication");
//System.out.print( go_To_MYQC_Page.buttonText());
}
}
This is my second test case (on the same page) which also works fine:
package MYQC_TestCase_Classes;
import MYQC_Browser_Pages.CUST4_MYQC_Login_Selection_Page;
import MYQC_Browser_Pages.MYQC_Login_Page;
import MYQC_Reusable_Classes.MYQC_Base_Class;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
public class TC002_MYQC_Login_Selection_Test extends MYQC_Base_Class {
#Test
public void Go_To_MYQC_Login_Page_Test() throws InterruptedException, IOException {
//creating anb object of the CUST4_MYQC_Login_Selection_Page
CUST4_MYQC_Login_Selection_Page go_To_MYQC_Page = PageFactory.initElements(driver, CUST4_MYQC_Login_Selection_Page.class);
//Clicking on the button to go to the MYQC login page
go_To_MYQC_Page.preClickLogin();
// waiting few seconds to get a screenshot of the page
Thread.sleep(2000);
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("C:\\Users\\fhasan\\Desktop\\Selenium Screenshots\\MYQCLogin_Page.png"));
Thread.sleep(2000);
}
}
This is my third test case class: (which creates the error)
package MYQC_TestCase_Classes;
import MYQC_Browser_Pages.MYQC_Login_Page;
import MYQC_Reusable_Classes.MYQC_Base_Class;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TC003_MYQC_Prepaid_Login_Test extends MYQC_Base_Class {
//creating an object of the page
MYQC_Login_Page login_page = PageFactory.initElements(driver,MYQC_Login_Page.class);
#Test
public void MYQC_Login() throws InterruptedException {
Thread.sleep(2000);
login_page.clickUserName();
login_page.enterUserName("***");
Thread.sleep(2000);
login_page.clickPass();
login_page.enterPassword("***");
login_page.clickLoginButton();
}
}
After running the code, I am getting the following error:
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy9.click(Unknown Source)
at MYQC_Browser_Pages.MYQC_Login_Page.clickUserName(MYQC_Login_Page.java:30)
at MYQC_TestCase_Classes.TC003_MYQC_Prepaid_Login_Test.MYQC_Login(TC003_MYQC_Prepaid_Login_Test.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
at org.testng.TestNG.run(TestNG.java:1031)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
your username element is not found on your 3rd test, please do following actions
at MYQC_Browser_Pages.MYQC_Login_Page.clickUserName(MYQC_Login_Page.java:30)
Please add screenshot just before entering username,
Add wait time to load website completely.
still not helpful,
better you should isolate all your test methods.
no static properties
login and logout should be in before method and after method - test method should be independent
use common method for assertions so whenever get failed, automatically add screenshot
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;
Code with errors:
package TestCase;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
public class TestWebBrowser {
//AppiumDriver driver = new IOSDriver();
public static AndroidDriver driver;
public static void main(String[] args) throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
}
The message error is:
The constructor URL(string) is undefined
The constructor AndroidDriver(URL, DesiredCapabilities) is undefined
AndroidDriver is a raw type
I have tried with different versions of java-client and still the problem persists
You need to use an existen constructor like this:
https://appium.github.io/java-client/io/appium/java_client/android/AndroidDriver.html
You need use java.net.URL and not com.gargoylesoftware.htmlunit.javascript.host.URL
#Lorena, hi.
1. Firstly, could You please double check the imports ? Sharing code snippet below with correct ones
package tests.web;
import java.net.MalformedURLException;
import java.net.URL;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileBrowserType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
public class AndroidWebTest {
private static final String ACCESS_KEY = System.getenv(“SEETEST_IO_ACCESS_KEY”);
private static final String CLOUD_URL = “https://cloud.seetest.io:443/wd/hub”;
private static final String TITLE = “Testing Website on Android Chrome with Java”;
private AndroidDriver driver = null;
#Before
public void setUp() throws MalformedURLException {
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(“testName”, TITLE);
dc.setCapability(“accessKey”, ACCESS_KEY);
dc.setBrowserName(MobileBrowserType.CHROME);
driver = new AndroidDriver(new URL(CLOUD_URL), dc);
}
#Test
public void testAppiumOnChrome() {
driver.get(“https://amazon.com”);
System.out.println(driver.getTitle());
if (driver.getCapabilities().getCapability(“device.category”).equals(“TABLET”)) {
driver.findElement(By.xpath(“//*[#name=’field-keywords’]”)).sendKeys(“iPhone”);
driver.findElement(By.xpath(“//*[#text=’Go’]”)).click();
} else {
driver.findElement(By.xpath(“//*[#name=’k’]”)).sendKeys(“iPhone”);
driver.findElement(By.xpath(“//*[#value=’Go’]”)).click();
}
}
#After
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
Please see the Comparing and combining web and mobile test automation drivers article for more details.
If You project is maven-based, could You please also double check the dependencies?
For example, please see latest appium updates here
Appropriate maven repo to check for (latest) java client:
https://mvnrepository.com/artifact/io.appium/java-client
My files and error which iI am getting are as follows:
url_title.properties
username=rakeshm#techved.com
password=123456
chrome_driver_path=D://rakesh//software//selenium browser//chrome 2.28//chromedriver.exe
BrowserFactory class file
package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class BrowserFactory
{
static Properties browserfactory_properties_obj;
static WebDriver driver;
public static WebDriver browser_factory_getter(String browser, String url) throws IOException
{
File browserfactory_file_obj = new File(".\\src\\property_folder\\url_title.properties");
FileInputStream browserfactory_fileinput_obj = new FileInputStream(browserfactory_file_obj);
browserfactory_properties_obj = new Properties();
browserfactory_properties_obj.load(browserfactory_fileinput_obj);
if(browser.equalsIgnoreCase("firefox"))
{
ProfilesIni profile = new ProfilesIni();
FirefoxProfile fire_profile = profile.getProfile("selenium_browser");
driver = new FirefoxDriver(fire_profile);
}
else if(browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver",browserfactory_properties_obj.getProperty("chrome_driver_path"));
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
home_login_elements class file
package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class home_login_elements
{
WebDriver driver;
#FindBy(how=How.CLASS_NAME, using="login")
WebElement login_link_ele;
#FindBy(how=How.ID, using="email")
WebElement username_ele;
#FindBy(how=How.ID, using="passwd")
WebElement password_ele;
#FindBy(how=How.ID, using="SubmitLogin")
WebElement login_submint_ele;
public WebElement login_link()
{
login_link_ele.click();
return login_link_ele;
}
public void login_fun(String username, String password)
{
username_ele.sendKeys(username);
password_ele.sendKeys(password);
login_link_ele.submit();
}
}
login_class class file
package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class login_class
{
WebDriver driver;
Properties login_class_url_title;
public login_class() throws Exception
{
File login_class_url_title_file = new File(".\\src\\property_folder\\url_title.properties");
FileInputStream login_class_url_title_fis = new FileInputStream(login_class_url_title_file);
login_class_url_title = new Properties();
login_class_url_title.load(login_class_url_title_fis);
home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
}
}
Add_to_wishlist testng file(executable file)
package wishlist;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.home_login_elements;
import utilities.login_class;
public class Add_to_wishlist extends home_login_elements
{
WebDriver driver;
#Test
public void first_testcase() throws Exception
{
driver = BrowserFactory.browser_factory_getter("chrome", "http://automationpractice.com/index.php");
login_class obj =new login_class();
driver.findElement(By.xpath("//ul[#class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']/li[3]")).click();
}
}
After executing Add_to_wishlist testng file i am getting following error
Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 6905
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: first_testcase
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.sendKeys(Unknown Source)
at utilities.home_login_elements.login_fun(home_login_elements.java:36)
at utilities.login_class.<init>(login_class.java:20)
at wishlist.Add_to_wishlist.first_testcase(Add_to_wishlist.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
The problem is, you are not in login/sign in page. you have missed to click on sign in link in home page. please call the method login_link before calling the login_fun in the class login_class as given below.
driver=BrowserFactory.driver;
home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
home_login_elements_login_class_obj.login_link();//This is missing in your code
home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
Your login_class doesn't seem to know about your initialized driver, hence it is NULL.
In your case, make these changes:
In login_class change your constructor to take a driver:
public login_class(WebDriver webDriver) throws Exception
{
driver = webDriver;
...
}
In first_testcase():
{
...
login_class obj =new login_class(driver);
...
}
That being said... this is a weird implementation, and I would suggest looking at a few more examples of how others get this set up initially. But if it works for you then that's great :)
For what it's worth, I think the answer provided by #murthi would be sufficient to set the driver properly, and should probably be the accepted answer because it's the simplest way to do what you're asking.
I don't see the in the class you have initialize your element.
public class home_login_elements {
public home_login_elements(WebDriver driver) {
PageFactory.initElements(driver, this);
}
}
Can someone tell me why my page is not being driven using the code below? The page loads but the driver does not drive to click the ticketButton link. I am lost and could use some help. Thanks in advance.
package domainEntities;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ConstantsTest {
WebDriver driver;
public ConstantsTest(WebDriver driver){
this.driver = driver;
}
public WebElement ticketButton() {
WebElement ticketButton = driver.findElement(By.cssSelector("a.ticketButton"));
return ticketButton();
}
}
package test;
import domainEntities.ConstantsTest;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.junit.Assert.fail;
public class TenaciousD{
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
WebDriver driver = new FirefoxDriver();
#Test
public void TenaciousD() throws InterruptedException {
driver.get("http://tenaciousd.com");
ConstantsTest c = new ConstantsTest(driver);
c.ticketButton().click();
Thread.sleep(100000);
}
This is the error its returning:
java.lang.StackOverflowError
at java.io.FileInputStream.<init>(FileInputStream.java:56)
at java.net.SocketInputStream.<init>(SocketInputStream.java:61)
at java.net.AbstractPlainSocketImpl.getInputStream(AbstractPlainSocketImpl.java:415)
at java.net.Socket$2.run(Socket.java:875)
at java.net.Socket$2.run(Socket.java:873)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.Socket.getInputStream(Socket.java:872)
at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:85)
at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:107)
at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:184)
at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:163)
at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:132)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:186)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:151)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.openqa.selenium.remote.HttpCommandExecutor.fallBackExecute(HttpCommandExecutor.java:316)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:295)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:133)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.execute(FirefoxDriver.java:355)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:527)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:307)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:396)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:406)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)
at domainEntities.ConstantsTest.ticketButton(ConstantsTest.java:23)
Your StackOverflow issue is coming from your ticketButton() method.
public WebElement ticketButton() {
WebElement ticketButton = driver.findElement(By.cssSelector("a.ticketButton"));
return ticketButton();
}
You are returning the method instead of the element.
public WebElement ticketButton() {
WebElement ticketButton = driver.findElement(By.cssSelector("a.ticketButton"));
return ticketButton;
}