WebDriver - one instance of driver in many classes - java

I have 3 classes like below but when I try to run my test I get NullPointer (TestPage->input1). On debug I spotted that I have a second instantion of driver which is null. Can anyone help me what I did wrong and how to fix it? Shouldn't it work properly?
public class BaseScenario {
protected WebDriver driver;
#BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Ed\\Desktop\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-form/");
}
#AfterMethod
public void TearDown() {
driver.quit();
}
}
'
public class TestsPage {
WebDriver driver;
public TestsPage(WebDriver driver)
{
this.driver=driver;
}
public void input1(){
driver.findElement(By.xpath("//*[#id='content']/form/fieldset/div[1]/input[1]")).sendKeys("Kuba");;
}
public WebElement input2(){
WebElement input2 = driver.findElement(By.xpath("//*[#id='content']/form/fieldset/div[1]/input[2]"));
return input2;
}
}
'
public class Tests extends BaseScenario{
TestsPage pagee = new TestsPage(driver);
#Test
public void TC1() throws Exception {
pagee.input1();
pagee.input2().sendKeys("Chudy");
}
}

Related

Multiple instances of browser opening up when running test through webdriver manager

I am new to Selenium, so basically whenever I ran my test, it would open up the URL which I have mentioned in my test. In my same Test I have also mentioned to fill the username and Password.
But somehow once the browser gets launched and redirect to the URL, it opens up another instance of blank browser failing my script that element not found.
Please help me here.
///////////////////////////////////////////////////////////////////////////
public class TruefillTest extends BaseClass {
public Truefill truefill()
{
WebDriver driver=InitializeDriver();
return new Truefill(driver);
}
#Test
public void userLoginIntoTheSystem()
{
truefill().dashBoard().Url();
truefill().dashBoard().EnterUsername("bjdgfe#swcwr.com");
truefill().dashBoard().EnterPassword("Test1234");
}
///////////////////////////////////////////////
public class Truefill {
private WebDriver driver;
public Truefill(WebDriver driver) {
this.driver=driver;
}
public DashBoardPage dashBoard()
{
return new DashBoardPage(driver);
}
////////////////////////////////////////////////////////////
public class DashBoardPage {
private final WebDriver driver;
By Username= By.xpath("//input[#name='name']");
By Password= By.xpath("//input[contains(#id,'exampleInputPassword1')]");
public DashBoardPage(WebDriver driver) {
this.driver=driver;
}
public void Url()
{
driver.get("https://rahulshettyacademy.com/angularpractice/");
}
public void EnterUsername(String username)
{
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(Username).sendKeys(username);
}
public void EnterPassword(String password)
{
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(Password).sendKeys(password);
}
////////////////////////////////////////////////////////////
public class BaseClass {
WebDriver driver;
public WebDriver InitializeDriver()
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
return driver;
}
}
Each call to the truefill() method initializes a new instance of WebDriver. Since your test is calling it multiple times, it will start a new browser instance on each line. Instead, store the DashboardPage in a local variable:
#Test
public void userLoginIntoTheSystem() {
DashBoardPage dashBoardPage = truefill().dashBoard();
dashBoardPage.Url();
dashBoardPage.EnterUsername("bjdgfe#swcwr.com");
dashBoardPage.EnterPassword("Test1234");
}
You might also want to use a setup method to initialize the Truefill instance, rather than creating it on demand:
private Truefill truefill;
#BeforeEach
public void initializeTruefill() {
WebDriver driver = InitializeDriver();
truefill = new Truefill(driver);
}
#Test
public void userLoginIntoTheSystem() {
DashBoardPage dashBoardPage = truefill.dashBoard();
dashBoardPage.Url();
dashBoardPage.EnterUsername("bjdgfe#swcwr.com");
dashBoardPage.EnterPassword("Test1234");
}
This assumes JUnit 5. If you're using JUnit 4, the annotation is #Before instead of #BeforeEach.

NoSuchElementException using WebDriverWait

I would really like to understand why when approaching locating an element the exact same way as previously failing.
NoSuchElementException : Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[contains(text(),'Add')]"}
I have also tried to use something like the following but it also failed, so in order for me write a good automation code i need to get my knowledge straight with WebDriverWait, so i would appreciate somebody with knowledge to spend some time on this inquiry.
It does locates if i have xpath like this :
//body/div[#id='root']/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div[2]/div[1]
public void clickOnAddVehicleButton() {
wait.until(ExpectedConditions.visibilityOf(addVehicleButton));
vehicles.addVehicleButton.click();
}
I am not new into Java but i am new into automation hence some areas of knowledge is missing, i ha
Base class:
public class BasePage {
protected final WebDriver driver;
protected final WebDriverWait wait;
public BasePage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver,5);
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 10), this);
}
}
The component where that button should be present :
public class Vehicles extends BasePage {
private static Vehicles vehicles;
private Vehicles(WebDriver driver) {
super(driver);
}
#FindBy(xpath = "//span[text(),'Add']")
public WebElement addVehicleButton;
public static Vehicles vehiclesInstance(WebDriver driver) {
return vehicles == null ? vehicles = new Vehicles(driver) : vehicles;
}
public void clickOnAddVehicleButton() {
vehicles.addVehicleButton.click();
}
Function in the service class:
public void addVehicle(String vehicleName, String numberPlate) {
myAccountService.myAccountPage()
.clickOnVehiclesTab();
vehicles.fillInVehicleName(vehicleName)
.fillInVehicleNumberPlate(numberPlate)
.clickOnAddVehicleButton();
}
WebDriverSettings for test :
public class WebDriverSettings {
protected WebDriver driver;
#Before
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
loginToDevEnvironment();
}
And finally my test class where i am calling the service method:
public class VehicleServiceTest extends WebDriverSettings {
private VehiclesService vehiclesService;
#Before
public void setUp(){
super.setUp();
CookieService.cookieServiceInstance(driver).acceptCookies();
HomePageService.homePageServiceInstance(driver).clickOnMyAccountTab();
LoginService.loginServiceInstance(driver).login(loginCorrectData());
HomePageService.homePageServiceInstance(driver).clickOnMyAccount();
vehiclesService = VehiclesService.vehiclesServiceInstance(driver);
}
#Test
public void shouldAddVehicle(){
vehiclesService.addVehicle("test-vehicle","test-test");
Assert.assertEquals(1,vehiclesService.getVehicles().listOfAddedVehicles().size());
}

How to use the same Webdriver from different class

I have 2 Java classes; Main.java and Methods.java. At Main.java, I initialize the chrome webdriver and I want to use the same webdriver for a method at Methods.java. Below are the codes.
Under Main.java
Methods getMethods = new Methods();
#BeforeTest
public void Setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\...\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(PropertiesConfig.getObject("websiteUrl"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void TestCase1()
{
getMethods.method1();
}
#AfterTest
public void QuitTC() {
getMethods.QuitTC(); }
Under Methods.java
public void method1 (){
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
….. }
public void QuitTC() {
driver.quit();
}
My question is how do I called the initialize Webdriver from Main.java and used it at Methods.java?
Any help with be appreciated! Thanks!
You can do something like this in a utility class (say TestUtil.java)
private static WebDriver wd;
public static WebDriver getDriver() {
return wd;
}
and then you can use following line to get the webdriver in any of the classes mentioned and work on it
WebDriver driver = TestUtil.getDriver();
Declare a global variable for driver like this :
WebDriver driver = null;
#BeforeTest
public void Setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\...\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(PropertiesConfig.getObject("websiteUrl"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
Now, you can call method1 from method class like this :
public class Methods{
public Methods(WebDriver driver){
this.driver = driver;
}
public void method1 (){
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
….. }
}
Now once you create the instance of Methods class, constructor would be called and driver reference could be passed.
Try this
Class1 {
public WebDriver driver = null;
public String baseURL="...";
public void openURL() {
System.setProperty("webdriver.chrome.driver", "D:...\\chromedriver.exe");
driver = new ChromeDriver();
driver.get(baseURL);
}
Class2 extends Class1 {
driver.findElement(....);
}

Unable to use locators in #Test Junit Selenium web driver

I am new in JUnit Selenium, and I found problem.
I cannot find elements using locator in #Test method. I dont have predictive search when I type driver. I can if I type into #Before.
E.g I cant type
#Test
..
driver.findElement(By.id("gs_htif0")).sendKeys("blabla");
My class contains -
#Before
public void setUp() throws Exception {
WebDriver driver;
System.setProperty("webdriver.gecko.driver", "C:\\geckodriver.exe");
driver = new FirefoxDriver();
String baseURL = "https://www.google.com";
driver.get(baseURL);
}
#Test
public void test() {
driver.**___PROBLEM___**
}
#After
public void tearDown() throws Exception {
}
That's because you've declared
WebDriver driver;
locally within the setUp method which is also annotated using #Before in your case.
You shall move this to the class level and use further as -
public class SomeTest {
WebDriver driver;
#Before
public void setUp() throws Exception {
...
driver = new FirefoxDriver();
...
driver.get(baseURL);
}
#Test
public void test() {
driver.getTitle(); //just an example
}
.... // other methods
}

TestNG, WebDriver. When I run a suite, 2nd test fails as nullPointerException

I created two tests. Pulled up BeforeSuite and AfterSuite in superclass method.
Tests passes individually but fails when I execute them as a package.
Error NullPointerException at string
driver.get(baseUrl + "test/test/");
public class MyTestBase {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
#BeforeSuite
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://test.com/";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
Code:
private void login() throws InterruptedException {
driver.get(baseUrl + "test/test/");
driver.findElement(By.xpath("//input")).clear();
driver.findElement(By.xpath("//input")).sendKeys("user234");
driver.findElement(By.xpath("//div[2]/div[2]/div/input")).clear();
driver.findElement(By.xpath("//div[2]/div[2]/div/input")).sendKeys("645637");
submitButton();
Thread.sleep(2000);
}
Test 1
`public class AddEquipment extends MyTestBase { }`
Test 2
`public class AddAnotherEquipment extends MyTestBase { }`
Both tests are the same, but with different parameters Equipment and Description fields.
I am at the beginning за learning WebDriver and tried to create something simple.
Code for test 1:
package com.example.tests;
import org.testng.annotations.Test;
public class AddEquipment extends MyTestBase {
#Test
public void testAddEquipment() throws Exception {
GroupData group = new GroupData("Equipment", "Description");
createEquipment(group);
// assert
}
protected void createEquipment(GroupData group) throws InterruptedException {
login();
menuClickEquipment();
clickAddButton();
fillOutForm(group);
submitButton();
logout();
}
private void login() throws InterruptedException {
driver.get(baseUrl + "test/test/");
driver.findElement(By.xpath("//input")).clear();
driver.findElement(By.xpath("//input")).sendKeys("user234");
driver.findElement(By.xpath("//div[2]/div[2]/div/input")).clear();
driver.findElement(By.xpath("//div[2]/div[2]/div/input")).sendKeys("645637");
submitButton();
Thread.sleep(2000);
}

Categories