Cannot instantiate class (Selenium) - java

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

Related

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.

Error - "Cannot invoke "org.openqa.selenium.WebElement.sendKeys(java.lang.CharSequence[])" because "this.UserName" is null

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.

NoSuchElementException in Selenium when testing login using Java

I am working on a Selenium testing framework tutorial of John Sonmez and ran into problem trying to perform the very first test. The test part consists of two methods: 1. LoginPage.GoTo(); which opens wordpress login page and 2. LoginPage.LoginAs("admin").Login(); which inserts username and clicks continue.
What happens when I run the test is wordpress loginpage opens and after 2 seconds blank Chrome browser opens and JUnit displays NoSuchElementException. The author of tutorial solved this problem adding some WebDriverWait and switchTo.ActiveElement.getAttribute() to LoginPage.GoTo(); method. However he is coding in C# and offers no solution for Java I'm coding in. I tried to apply WebDriverWait also but the problem is still there. Can anyone please suggest me how to solve this problem using WebDriverWait in Java.
LoginTest
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import wordpressAutomation.Driver;
import wordpressAutomation.LoginPage;
public class LoginTest extends Driver {
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
LoginPage.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
}
LoginPage
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;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public static LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}
public class LoginCommand extends Driver {
private String username;
private String password;
public LoginCommand(String username) {
this.username = username;
}
public LoginCommand WithPassword(String password) {
this.password = password;
return this;
}
public void Login() {
WebElement login = openBrowser().findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
openBrowser().findElement(By.xpath("//button[#type = 'submit']")).click();
}
}
public class Driver {
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\KatarinaOleg\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
After opening the page, where you get the NoSuchElementException you can add in something like this.
FluentWait<WebDriver> webDriverWait = new WebDriverWait(driver, 25).pollingEvery(5, TimeUnit.SECONDS);
webDriverWait.until(ExpectedConditions.visibilityOf(webElement));
Just add in whatever element you want to use as your check to make sure the page has loaded
you have called the Openbrowser multiple times in Login Method from LoginCommand Class.So, It will be unnecessarily create different driver instance. So, your code needs to be modified as below along with explicit wait (Driver Class also needs to be changed as below)
Login Method from LoginCommand Class:
public void Login() {
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='usernameOrEmail']")));
WebElement login = driver.findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
driver.findElement(By.xpath("//button[#type = 'submit']")).click();
}
Driver Class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Driver {
WebDriver driver;
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
Edit: (dmin_user_can_login() method in LoginTest class)
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
l.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
LoginPage Class:
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;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}

How to pass called WebDriver driver from #BeforeMethod to #Test in TestNG Webdriver Java

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;
}
}

Cannot get selenium webdriver Java script to run

Hi I'm new to webdriver I'm trying to get a script to run. When I run the script it opens the browser and enters the log in details but the #Test part does not. I've tried using css locator x path etc. but nothing I've tried works. Has anyone any ideas or advice that could help?
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://zzzz";
public WebDriver driver = new FirefoxDriver();
#BeforeTest
public void login() {
driver.get(baseUrl);
WebElement id = driver.findElement(By.id("z_username"));
id.sendKeys("todd");
WebElement pass = driver.findElement(By.id("z_password"));
pass.sendKeys("todd");
WebElement button = driver.findElement(By.name("login"));
button.submit();
}
#Test
public void createSub() {
driver.findElement(By.linkText("Customers")).click();
}
#AfterTest
public void terminateBrowser() {
driver.quit();
}
}
You were missing closing } and the selector for customers element may be the reason of failure as well
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://zzzz";
public WebDriver driver = new FirefoxDriver();
#BeforeTest
public void login() {
driver.get(baseUrl);
WebElement id = driver.findElement(By.id("z_username"));
id.sendKeys("todd");
WebElement pass = driver.findElement(By.id("z_password"));
pass.sendKeys("todd");
WebElement button = driver.findElement(By.name("login"));
button.submit();
}
#Test
public void createSub() {
driver.findElement(By.xpath("//*[.='Customers']")).click();
}
#AfterTest
public void terminateBrowser() {
driver.quit();
}
}

Categories

Resources