Unable to use locators in #Test Junit Selenium web driver - java

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
}

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.

java unit test with selenium getting nullpointer exception for #inject function

I am trying to unit test Sign On method in selenium. My Sign On method is injecting other pages which is taking webdriver in turn.
SignOn.java
import ...
#PageObject
public class SignOn {
#Inject
BasePage basepage
public void signOn(driver,user,password){
basepage.clickhamburgermenu() #This line is not instantiated when
unit testing but works fine when just running this file.
}
BasePage.java
import ...
public class BasePage {
Map<String, String> data;
WebDriver driver;
#Inject
public BasePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void clickHamburgerMenu() {
if(driver.findElements(By.cssSelector(hamburgerMenu)).size() > 0)
{
WebElement burgerMenu = driver.findElement(By.cssSelector(hamburgerMenu));
if(burgerMenu.isDisplayed()){burgerMenu.click();}
}
}
SignOntest.java
import ...
public class signOnTest{
#BeforeMethod
public void setUp() {
webDriver = new ChromeDriver();
signOn = new SignOn();
}
#Test
public void testSignOn() {
webDriver.get("www.facebook.com");
SignOn.SignOn(webDriver,"user","password");
}
}
Here, I wanna unit test sign-on method but it fails on basepage initiation. I am not that pro in dependency injection. Anything helps.

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

Page object in testng error (java.lang.NullPointerException) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to implement the concept of Page Object using TestNG. I created a BrowserFactory class that has the information to initialize the browser.
I also created a class called LogSystemPage that has the information of the screen elements that I need to interact with.
Lastly, I created a test class called ValidateStatusTestNG that "calls" the BrowserFactory and LogSystemPage classes.
When I try to run the test method called logarSystem, the Eclipse console displays the following error message: java.lang.NullPointerException.
Following is the code, the error message and the images.
public class BrowserFactory {
static WebDriver driver;
public static WebDriver startBrowser(String url) {
System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
return driver;
}}
public class LogarSistemaPage {
private static WebDriver driver;
public WebDriver logarSistema(WebDriver driver) {
driver.findElement(By.id("matricula_I")).sendKeys("844502");
driver.findElement(By.id("senha_I")).sendKeys("Pw34Jdt#*");
driver.findElement(By.id("bt_entrar")).click();
return driver;
}}
public class ValidarStatusTestNG {
static WebDriver driver;
#BeforeClass
public void setUp() throws Exception {
BrowserFactory b = new BrowserFactory();
b.startBrowser("http://10.5.9.45/BKOMais_S86825EstrategiaBackOfficeClaroFixo/");
}
#Test
public void logarSistema(){
LogarSistemaPage s = new LogarSistemaPage();
s.logarSistema(driver);
}
#AfterClass
public static void closeBrowser() {
//driver.quit();
}}
driver =b.startBrowser("http://10.5.9.45/BKOMais_S86825EstrategiaBackOfficeClaroFixo/")
You need to assign the return value of method returning driver to driver.
#BeforeClass
public void setUp() throws Exception {
BrowserFactory b = new BrowserFactory();
driver =b.startBrowser("http://10.5.9.45/BKOMais_S86825EstrategiaBackOfficeClaroFixo/");
}
#Test
public void logarSistema(){
LogarSistemaPage s = new LogarSistemaPage();
s.logarSistema(driver);
}
That should do the work.

WebDriver - one instance of driver in many classes

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

Categories