Selenium Cucumber Java BDD Framework 7 - Page Factory | Step by Step
Вставка
- Опубліковано 11 гру 2024
- QUIZ - forms.gle/khk3...
FREE TUTORIAL - automationstep...
Today we will learn:
1 - What is Page Factory
2 - How to implement Page Factory
3 - Useful Tips
What is Page Factory
A simple and easier implementation of Page Object Model in Selenium
Selenium’s inbuilt and optimized Page Object Model concept
As POM, has separation of objects and tests
Uses annotation @FindBy to find WebElements
@FindBy can use id, name, css, xpath, tagName, linkText, partialLinkText etc
Uses method initElements to initialize web elements
on calling initElements method all objects on that page gets initialized
Demo How to implement Page Factory Model
Step 1 - Create a class for each page
Step 2 - Create locators of all objects to be used in that page using @FindBy
Step 3 - Create methods or actions to be performed on the objects
Step 4 - Create constructor to get driver instance and
initialize Elements using method initElements
public LoginPage_PF(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, LoginPage_PF.class);
}
Step 5 - Update Test Scripts to refer methods from PageFactory class
Step 6 - Run and validate
Useful Tips 1
@CacheLookup
CacheLookup can be used to instruct the InitElements() method to cache the element once its located and so that it will not be searched over and over again whenever calling it from any method
@FindBy(id = "name")
@CacheLookup
WebElement txt_username;
This works well with a basic web application, but not recommended if you have Ajax applications where DOM changes on user actions.
In case you get StaleElementExceptions, avoid using this.
Useful Tips 2
In Ajax applications to handle loading time for element and to avoid
‘No Element Exception’, we can use
AjaxElementLocatorFactory Class
timeout for a WebElement can be assigned to the Object page class with the help of AjaxElementLocatorFactory
AjaxElementLocatorFactory factory = new AjaxElementLocatorFactory(driver, 30);
PageFactory.initElements(factory, Login_PF.class);
The above code will wait for maximum of 30 seconds until the elements specified by annotations is loaded.
If the element is not found in the given time interval, it will throw ‘NoSuchElementException' exception.
Useful Tips 3
With PageFactory, you can also locate a list of Elements
@FindBy(partialLinkText = "raghav")
List<WebElement> myLinks;
References
github.com/Sel...
www.selenium.d...
example.testpr...
Join this channel to get access to perks: www.youtube.co...
Hit Like and. Subscribe button, if you like this video. It gives me great motivation.
You can support my mission for education by sharing this knowledge and helping as many people as you can
If my work has helped you, consider helping animalaidunlim... or any animal welfare group near you, in any way you can.
_______ ONLINE COURSES TO LEARN _______
automationstep...
I really worried about how I missed your videos for these days. You are great teacher.
Great to know this helped Arun
I was thinking the same
You are a star man .. have been trying to understand the driver thing for so long and only to see your videos.. very good way of explanation..
So happy & humbled to know this Keerthi
Thank you so much, Raghav !! Learned a lot from this series. keep sharing the knowledge.
Most welcome Shashi
superb... learnt alot in this series... i started from scratch...
Great Sonali, all the best
simple-N-sweet-Explaination-Mr-Raghav-ji-Thank-You.
Most welcome Nagaraju
Thanks, Raghav, for one more great session. Very useful.
Most welcome Srikanth
Wish I discovered this video sooner, Great work thanks a mill Raghav🥳
Most welcome
Hi Raghav, this was a really great informative video, for some reason the steps i took were not working as the username and password steps didn't work and i had followed exactly your steps but I managed to solve the problem by modifying the constructor to
public LoginDemo_PF(WebDriver driver) {
PageFactory.initElements(driver, this);
}
Also i made all the WebElements in the PageFactory "public" and it seemed to work.
Anyways thanks for your help, these videos are the best on youtube right now!
So happy to know that you troubleshooted and resolved. This is the best way to learn
Hi Abdul, I was facing similar issue , but when I modified constructor as mentioned above , I was able to run the code thanks a lot bro.
And also Raghav sir thank you so much for creating and uploading this amazing video.
Thank you for your great job, Raghav!
Always welcome Svetlana
Awesome sir. Salute for making this video.
Most welcome Suchi
Thank you ,
It was a great Session , amazing content.
Always welcome
Excellent example. Good explanation.
Many thanks Ibrahim
At 14:40 , which driver is used in initielements parameter
this.driver=driver
Pagefactory.initelemnts (driver,this)
} the driver which is coming as parameter or the driver which is at class level ?
Abhijeet
The driver that is used in the `initElements()` method is the driver that is passed in as a parameter. The driver at the class level is not used.
This is because the `initElements()` method is used to initialize the WebElements on the page. The WebElements are specific to the driver that is used to open the page. Therefore, the `initElements()` method needs to be passed the driver that is used to open the page.
In your example, the driver that is passed in as a parameter is `driver`. This is the driver that will be used to initialize the WebElements on the page.
The driver at the class level is not used because it is not specific to the current page. It may be used to open multiple pages, and each page may have its own set of WebElements
Thank you so much, Raghav. Awsome Session!!
Most welcome Frank
Thanks for the demo !!!
Sir, i think @ 21:53 we should have "HomePage_PF.class" or "this" at line 18, if this is true , still code is running can u plz explain ?
Hi Akshay, I will check with the video and explain
Hi akshay, yes I also noticed that, and I had to change it from "LoginPage_PF" to "HomePage_PF.class" or this, otherwise my last method was not getting called. Also just like we have created an object of LoginPage_PF class through this statement-> login = new LoginPage_PF(driver); similarly I also had to create an object for HomePage_PF class, otherwise the method won't be called. So I inserted this statement -> home=new HomePage_PF(driver);
@@priyanshisaxena1822 good catch 👍. I faced the same issue while navigating from LoginPage to HomePage
You are just AMAZING
thanks a lot ...
You're most welcome Ashutosh
thank you Raghav really helped me understand
Most welcome
This is really great, I learned a lot. Thank you so much!
I have 2 small questions:
at 21:44, you forgot to change LoginPage_PF on line 18 to HomePage_PF.
at 25:26, what's the difference between using "LoginPage_PS.class" and "this"? I thought you mentioned earlier that both should work?
i will check this
very nicely explain keep uploading bro some more topic
Sure I will Amit
Thanks Raghav this is very useful session.
Always welcome
Hi Raghav, Your truly a gem brother.
Thanks a ton Girish, humbled
You are Amazing Raghav :) Thank you
Most welcome Aniruddha
Awesome helpful bro
Glad to hear that Shankar
Hello Raghav, I followed from 1st video everything worked great until this single step where I cannot figure out why it is happening to me. I followed the same as you. I get NullPointerException at this line: home.checkLogoutIsDisplayed(); But it works fine with driver.findElement(By.id("logout")).isDisplayed();
it is exactly similar to 24:07 when you got NullPointer for login page, but mine is for home page.
Never mind, this solved the problem: home = new HomePagePF(driver); (just like the login), but there should be a more efficient way instead of calling them each time, right?
Hi Noza, you will just need to create the page object once, You can also do it in static way and can use throughout the class
Hi Raghav,
All your sessions are great !!
Do you have any videos for webrtc quality testing like network impairment testing in automation?
Thanks Avni, not yet, you can find all here - automationstepbystep.com/
Thanks Raghav for such a wonderful session. If possible please do a video on steps definition reusability
Sure Pallav
This tutorial is very helpful to learn. I have One question:
we have multiple page factory pages like loginPage, HomePage and cartpage etc...
And lets say for cart feature required Login & Home both pages object to create in cart's definition file
so i need to create object for both page & also i need to do for both?
loginpf = new loginPage_PF(driver);
homepf = new HomePage_PF(driver);
Yes Akshay, you need to create objects for both the Login and Home pages in the Cart's definition file. You can do this by using the following code:
LoginPage loginPage = new LoginPage(driver);
HomePage homePage = new HomePage(driver);
@@RaghavPal thank you so much for your response
Hi raghav,Can you post the video for using the JavaScript executor method to click the button after logging in?
in Page Factory method.
I will check on this
very nice and informative!!
Glad you liked it Lovely
nice explanation 💙
Thanks Ahmed
Very Nice Session
Thanks a lot
Thank you so much, Raghav. Great Session. :)
Most welcome Rohit
@Raghav, The Ajaxelementfactory approach waits for all the webelements mentioned on page class to load.
But if any locator changes , then it will throw an exception and we would not be able to say execute some test cases which have correct locators
since it throwed an exception at class level and exiting whole suite.
So is it a good implementation to use? Suggestions
Hi Abhishek, depends on your application, if you are not able to proceed with the above issue, can try changing it
@RaghavPal I m confuse between page object and page factory. Can you please tell when to use what? seems like its up to the user how he code
Fatima
I'd be happy to help clarify the difference between Page Object and Page Factory, and provide guidance on when to use each.
Page Object:
A Page Object is a design pattern that represents a web page as an object. It's a way to model a web page as a class, where each element on the page is represented as a property of the class. The idea is to create a layer of abstraction between the test code and the web page, making it easier to write and maintain tests.
Here's an example of a simple Page Object in Java:
```java
public class LoginPage {
private WebDriver driver;
private By usernameInput = By.id("username");
private By passwordInput = By.id("password");
private By loginButton = By.id("login-button");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String username) {
driver.findElement(usernameInput).sendKeys(username);
}
public void enterPassword(String password) {
driver.findElement(passwordInput).sendKeys(password);
}
public void clickLoginButton() {
driver.findElement(loginButton).click();
}
}
```
Page Factory:
Page Factory is a way to initialize Page Objects using a factory pattern. It's a mechanism provided by Selenium WebDriver to create Page Objects more efficiently. Page Factory uses annotations to identify elements on a page and create instances of Page Objects.
Here's an example of a Page Object using Page Factory in Java:
```java
public class LoginPage {
private WebDriver driver;
@FindBy(id = "username")
private WebElement usernameInput;
@FindBy(id = "password")
private WebElement passwordInput;
@FindBy(id = "login-button")
private WebElement loginButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void enterUsername(String username) {
usernameInput.sendKeys(username);
}
public void enterPassword(String password) {
passwordInput.sendKeys(password);
}
public void clickLoginButton() {
loginButton.click();
}
}
```
When to use what:
* Use Page Object when:
+ You want to create a custom representation of a web page as an object.
+ You want to encapsulate the logic of interacting with a web page within a single class.
+ You want to make your test code more readable and maintainable.
* Use Page Factory when:
+ You want to automate the process of creating a Page Object.
+ You want to use annotations to identify elements on the page.
+ You want to simplify the process of initializing a Page Object.
-
Thank you for the video :)
Welcome!
Hi Raghav, I have noticed that after 21:46 you changed the constructor name for HomePage_PF after pasting it from LoginPage_PF in line 16 but for initElements in line 18 it still shows LoginPage_PF.class
So I’m confused as to how did the test run?
Shreya
So HomePage_PF is the constructor of the HomePage_PF class and inside this constructor we are calling LoginPage_PF class
@@RaghavPal I think what I was trying to ask is should we not initialize the elements of the HomePage_PF class like the logout button inside the constructor of the class? At 14:14 you mentioned that the initElements() is used to initialize elements mentioned under @FindBy. If we are calling LoginPage_PF.class from inside the HomePage_PF.class constructor then will we be able to use the btn_logout element inside the HomePage_PF class? I understand that we're not doing anything with that button in this test script for now but if we had to do anything - suppose logout after verifying .isDisplayed(), how would that go?
Yes Shreya, I will try to lay out the major points to use page factory. Let's say we have to test a scenario, so will will:
Step 1: Create Webpage Class:
Within the webpage package, create a class representing a specific webpage.
Use the @FindBy annotation to identify web elements (e.g., buttons, input fields).
Initialize these elements using PageFactory.initElements(driver, this) in the constructor.
Step 2: Create a Test Class:
In the test package, create a class for your test scenarios.
Instantiate the webpage class and interact with its elements using the initialized Page Factory objects.
You can do with with every webpage class
Thank you Raghav! I will try this.
Very Nice Session
And Thanks 🥰🥰
Always welcome
What is the difference between POM and PageFactory? You have created diff packages for both and doing same things in both. finding elements and writing methods on the xpath? not getting which to follow POM or Page factory.
Let's dive into the differences between Page Object Model (POM) and PageFactory:
1. Page Object Model (POM):
- POM is a design pattern used for creating an object repository for web elements on a web page.
- It helps organize your test automation code by separating page objects (representing web pages) from test scripts.
- In POM, you define a class (the "Page" class) that acts as an interface for a specific web page. This class encapsulates the web elements and methods to interact with them.
- POM uses the `By` annotation to define page objects (locators).
- It requires explicit initialization of every object.
- POM handles exceptions less efficiently.
- There is cache storage for performing tasks.
2. PageFactory:
- PageFactory is a class provided by Selenium WebDriver that simplifies the implementation of POM.
- Developers use the `@FindBy` annotation to define page objects (locators).
- It automatically initializes the web elements within the page object when you create an instance of it.
- PageFactory efficiently handles exceptions.
- There is no need for explicit object initialization.
In summary, while POM is a design approach, PageFactory is a class that implements POM. If you prefer a cleaner and more efficient way to manage your page objects, consider using PageFactory
--
@@RaghavPal Thank yo for the clarification. still need to watch videos again for full clarification. Thanks for your time Raghav.
Thank you very much raghav
Most welcome Saikiran
Without creating object to LoginPage_PF login, HomePage_PF home these variables how could you call the methods inside that particular claass in LoginDemoSteps_PF.
Could you please explain this dilemma to me How could it possible .Also how could the elements in the pagefactory will be initiated if you did not send driver instance through constructor
Hi Bhagyalakshmi, we first import class and create its object
Thanks Raghav for showing POM with BDD framework. Can you please show how to use "Select " and "Action" class in POM so we can use in step definition package.
Hi Khurram, I will do. You can elaborate the exact scenario you are looking at
Can u give example for findbys,find all in page factory ..
I will add more examples
Question: u have pointed login class in initmethods in logout pf class.. is that the right way or we need to map logout pf class factory itself ir this
You can check the initmethod call in logout pf class.. where u passed login pf class
Hi Sathish, I will need to check on this. Pls send me the exact time stamp to follow
Amazing video.Thank you so much.I have a query though . While troubleshooting you initialized login page's object and called the constructor. Why didnt you add the same for Homepage ? I can see you didnt initialize that class's object as well previously along with login class. Afterwards,you did for login class but not for homepage class.How come the code worked,then? I am a bit confused.
Hi Saheli
When using Page Factory in Selenium Java, we can use the @FindBy annotation to locate WebElements and initialize them in the page object. However, we don't need to initialize the page object itself explicitly.
In other words, we only need to initialize the page object when we want to use it in our test code. In the case of the homepage class, if we don't use any of its methods or WebElements in our test code, there's no need to initialize its object.
In the example you mentioned, it's possible that the test code only needs to interact with the login page and not with the homepage, so only the login page object is initialized. Alternatively, the homepage could be initialized in a separate method or in a different test case where it's needed.
It's important to note that initializing a page object involves creating a new instance of the class, which can be expensive in terms of time and memory. So, it's best to initialize only the necessary page objects as needed to avoid unnecessary overhead.
@@RaghavPal Hey, thanks for the prompt response. I get your point. But in the example you showed, we are using homepage's method also where we are verifying if logout button is displayed or not. So, if we do not call the Homepage constructor and pass the driver as the argument, how is it going to run then? It should also give the null pointer exception as it threw for the login page while running!
Not sure, why it should throw error. Anyways, I will check again in detail as I get some time. Meanwhile can check some online examples
@@sahelighosh4932 - there was no error because when Raghav created a constructor for HomePage, you can see that in initElements he used LoginPage_PF class..so when he initialised object in step 'user enters and ', the object was already created for the last step.
hi raghav tq for ur videos which r very simple and understandable can u upload manual testing videos too
I will try
Hi Ragahav, How can we use dynamic xpath in page Factory? if i have a scenario where based upon some condition i am generating the xpath dynamically.
Hi Amit, you just need to refer that xpath in your scripts, store the value of xpath in a variable and add a function in the objects class to get that and update the xpath
I came as a stranger to this channel and become as a student to you sir🥺🙏
So happy & humbled to know this Ajay, Best wishes
Thanks for all your videos! I've watched a number of your video playlist and you teach PageFactory. Is PageFactory Deprecated in for Java as it is in C#? I can code now with and without it, but want to make sure I don't look foolish in interviews if it is deprecated and not recommended.
Yes, PageFactory is deprecated
There are a few reasons why PageFactory was deprecated. First, it is not very flexible. It can be difficult to use with dynamic web pages, and it can be difficult to maintain if the page structure changes. Second, it can be slow. PageFactory uses proxies to find elements, and this can add a significant amount of overhead.
Instead of using PageFactory, the recommended approach is to use the Page Object Model design pattern without PageFactory. This involves creating Page Object classes where you declare WebElements and define methods to interact with those elements. You can still use the @FindBy annotations, but instead of relying on PageFactory to initialize the WebElements, you can manually initialize them in the constructor or using lazy initialization.
@@RaghavPal Thank you for the reply! So it is not recommended for both C# and Java. I did not know you could still use @FindBy without PageFactory so I replaced it in my code by using By ( eg. By myElement = By.ID("elementID"). Thanks! You the Best!!
Yes, you can use @FindBy
Hi Raghav, For two different features file I dont want to initiate browser again & again..Can you please help me with this.. Since In your code as well browser is opening twice,,
Hi, can use hooks and annotations www.tutorialspoint.com/cucumber/cucumber_hooks.htm
Why don't I see the 'cucumber feature' anymore while trying to run the script. I have cucumber plugin installed. I uninstalled and installed it again still it didn't work. This was working but after I exit from eclipse then relaunch and import the project it stopped working. Please help!!
Hi, try to reinstall the plugins
@@RaghavPal The issue resolved on using eclipse enterprise edition. Anyway, thanks for your reply.
The initialization of the elements in the homepage page factory you forgot to change the name inside the constructor but it still worked?
Anyways, i am learning a lot from you. Thank you for great videos ❤
Thanks for the info!
I got it from you Thanks man...
I think there is no need of making WebDriver driver as global inside POM class. Hence we don't need to initialize driver inside the constructor.
this.driver=driver; is not needed.
that is ok
Hi Raghav, Can i not create "login = new LoginPage_PF(driver);" in class area? do i have to only create it in a method?
Hi Tapas, can do
@@RaghavPal I tried that in class area just below the webdriver driver line but i got null pointer exception that this.driver is null.
@@tapaskhandai
WebDriver Driver;
LoginPage_PF loginpage;
HomePage_PF homepage;
@Given("browser is open")
public void browser_is_open() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Domin\\eclipse-workspace\\Cucumber\\src\\test\
esources\\Features\\Drivers\\chromedriver.exe");
Driver=new ChromeDriver();
Driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
Driver.manage().timeouts().pageLoadTimeout(40,TimeUnit.SECONDS);
Driver.manage().window().maximize();
loginpage= new LoginPage_PF(Driver);
homepage= new HomePage_PF(Driver);
}
@And("user is on login page")
public void user_is_on_login_page() {
Driver.navigate().to("example.testproject.io/web/");
}
@When("^user enters (.*) and (.*)$")
public void user_enters_username_and_password(String username,String password) {
loginpage.EnterUserName(username);
loginpage.EnterPassword(password);
}
@And("user clicks on login")
public void user_clicks_on_login() {
loginpage.ClickonLoginButton();
}
@Then("user is navigated to the home page")
public void user_is_navigated_to_the_home_page() {
homepage.CheckLogoutisDisplayed();
Driver.close();
Driver.quit();
}
you have to declare an instance of class object in class area, then assign a new object( new loginPage_PF) inside function -> for example that with browser set up. Driver is null when you only declare LoginPage_PF loginpage without loginpage= new LoginPage_PF(Driver);
I have followed the same for page factory, I'm still getting null pointer exception, could you please help on this
Hi Vishwaraj,
If you are using Page Factory in your Selenium Java Cucumber project and you are getting a null pointer exception, it could be due to several reasons. Here are a few things you can try:
Make sure you have initialized the Page Factory using the @FindBy annotation. You can do this by calling PageFactory.initElements(driver, this) in the constructor of your page object.
Check if the element you are trying to access is present on the page. You can do this by using the browser developer tools to inspect the page and find the element's ID or other attributes.
Check if you have correctly imported the PageFactory class and the FindBy annotation in your project.
Check if you have instantiated the WebDriver object before accessing the page object.
If none of the above solutions work, please share your code snippet, so that I can help you better.
Hi Rajiv, thanks for the wonderfull class, i have a query like how can I create another classes and get the reports. Like login in one class, searching or creating in some other class, similarly different steps in different class. How I should modify my feature file to run and validate all classes, in a flow with reports
Ponnu
Certainly! When working with Selenium, Cucumber, and Java, organizing your test automation code into separate classes and generating reports is a good practice. Let's break down the steps to achieve this:
1. Organizing Steps into Different Classes:
- In Cucumber, you can create separate step definition classes for different features or scenarios.
- Each step definition class corresponds to a specific feature file or a group of related scenarios.
- For example, you can have:
- `LoginSteps.java` for login-related steps.
- `SearchSteps.java` for search-related steps.
- `CreateSteps.java` for creating actions.
- Each step definition class should contain methods annotated with Cucumber step definitions (e.g., `@Given`, `@When`, `@Then`).
2. Feature File Modifications:
- In your feature files (`.feature`), you can organize scenarios by tagging them appropriately.
- Add tags to scenarios based on their functionality. For example:
```gherkin
@login
Scenario: User logs in successfully
Given the user is on the login page
When they enter valid credentials
Then they should be logged in
@search
Scenario: User performs a search
Given the user is logged in
When they search for a product
Then search results should be displayed
```
- Here, `@login` and `@search` are tags associated with specific scenarios.
3. Cucumber Runner Class:
- Create a Cucumber runner class (usually named `TestRunner` or similar).
- In this class, specify the features to run and the corresponding step definition packages.
- You can include multiple feature files or entire directories:
```java
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(
features = {"src/test/resources/features"}, // Path to your feature files
glue = {"com.yourpackage.steps"} // Package where your step definitions reside
)
public class TestRunner {
// Additional configuration if needed
}
```
4. Generating Reports:
- To generate reports, consider using Cucumber's built-in reporting tools or third-party plugins.
- Cucumber provides HTML, JSON, and other report formats.
- Add the appropriate plugins to your runner class:
```java
@CucumberOptions(
features = {"src/test/resources/features"},
glue = {"com.yourpackage.steps"},
plugin = {"pretty", "html:target/cucumber-reports"}
)
```
- After running your tests, check the `target/cucumber-reports` directory for the generated HTML report.
5. Running Tests:
- Execute your tests by running the `TestRunner` class.
- The runner will execute scenarios based on the specified tags and generate reports.
Remember to adjust the package names, paths, and other details according to your project structure.
all the best ..
@@RaghavPal Sorry that I missed your reply, Thankyou so much. That was a really great help. Stay blessed
Hello sir when I'm running cucumber project it's showing io.cucumber.core.cli.Main error despite of added all dependancies what can I do plzz suggest me.
hi, is it an error or warning, In case of warning, You can safely ignore this warning. All it means is that cucumber-eclipse has not yet been updated to use Cucumber's new package structure
check this can help
community.smartbear.com/t5/Cucumber-Open/deprecated-Main-class-error-while-using-Cucumber-6-1-1/m-p/206774#M97
stackoverflow.com/questions/57177823/exception-in-thread-main-after-updating-cucumber-version
A User Comment - I created a new project and added an additional maven plugin and JUnit dependency, it worked
Hi Raghav !!
Thanks for your videos but I'm getting null pointer exception for @when steps
pls help for this solution
Hi Sujeet, will need to see your code. Pls check again with my code and try all steps again
Hey! can you please tell why do I have to instantiate object of Page class in every step. my steps throw exceptions if I dont instantiate object in every step. login=new LoginPage()?
Hi Faiza, you can declare it globally and then use it anywhere
Thank you Raghav,
I have a doubt , When I try to run the Multipl feature file , it shows me an error feature file not fount though the feature file is present in the location .
can you make a video how to run multiple feature files
Hi Vijaya, I will, you can control that from Cucumber runner class
Hi Raghav, I'm getting JDK.internal.reflect.GeneratedConstructorAccessor9.newInstance(Unknown Source) error. Not able to figure out whats the issue. Copied from another code where it works fine, but in the new file its showing an error
Hi Reena, not very sure, have not encountered this, will need to take online help
@@RaghavPal The error seems to be in this line : PageFactory.initElements(driver,LoginPageWF.class);
the program runs continuously and have to stop the program from further running.
Looked on internet but was not able to figure out
will check
Thank you @raghav.
Most welcome Jagrat
Sir, In above video, data driven testing using excel is not shown, do you have video of data driven using excel ?
will check on this
Hi Raghav i just want to know how you create a object of a class. into another class by just importing that class. i also refered your basic java videos from your site. but i still have a doubt. can u pls explain it???
Hi Sanket, I will try to explain with a session, for now can try online examples
Hi raghav when i developed 2nd page class as same way am getting null pointer exeception how to solve that error could u help me once?
Hi Ranga, mostly issue with the way you are accessing it, take care of the path and try again, can check some online examples
thank you for the reply raghav
Hi Raghav,
Great session
i have a query regarding AjaxElementLocatorFactory
here we are providing wait for 30 seconds and suppose there is implicit wait of 10 seconds.
Then how the scenario will be handled
Hi Ankit,
The implicit wait works in case the object is not available on page load, so it will wait max for 10 sec in this case, but if you have 30 sec explicitly, the total duration is taken 30 and not 10+30
Hi Raghav, thanks making for such useful videos. It really helped a lot. I have a request, could you please make a video on "How we can fetch the appium capabilities of the connected device?" So that we do not need to use the static capabilities. Thanks in advance :)
Hi Siba, I will check on this
Hii Raghav , i just wanted to understand that when we initialise all the web element using page factory in this case there could be the chance that the web element is not there or the web element will be there after we do some action so in this condition it will throw exception of no element , what are we doing to overcome this issue
Hi, this can help stackoverflow.com/questions/53081906/how-to-handle-dynamic-elements-in-page-object-model-in-selenium
Another fantastic video! Easy to understand as usual... and I last touched Java over decades ago! Thanks!
Quick question... I may have missed something, but I fail to understand the advantage of using Page Factory over POM. POM seems easier to maintain and read. Please help me to understand why would one use Page Factory over POM?
Hi, Page Object Model (POM) is a design to keep objects and test scripts separate. Page Factory is a class in Selenium Library that facilitates POM design
Sir, For preparing script for Page Factory, good to prepare from scratch, to avoid confusion
Sure Ratish
@@RaghavPal, Am exploring for my project, where i need Page object model ,data driven using excel from scratch to avoid confusion
okay
Hi Raghav, I am getting null pointer exception java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "this.driver" is null
at pageObjects.LoginPage.doLogin(LoginPage.java:48)
Harsha
The `java.lang.NullPointerException` you're encountering indicates that the `this.driver` object is null when you attempt to invoke the `findElement` method on it. Let's troubleshoot this issue:
1. Root Cause:
- The error occurs because the `this.driver` object has not been properly initialized before you use it.
- In your code, the `doLogin` method in the `LoginPage` class is trying to find an element using the `driver`, but the `driver` is null.
2. Possible Solutions:
- Check Initialization:
- Ensure that you have correctly initialized the `driver` object before calling any methods on it.
- Verify that the `driver` is instantiated and assigned a value (usually by creating a new instance of the WebDriver, such as ChromeDriver or FirefoxDriver).
- Constructor or Setup Method:
- If you're using a constructor or a setup method (like `@BeforeTest`), make sure you initialize the `driver` there.
- For example:
```java
public class MyTest {
private WebDriver driver;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
}
@Test
public void myTest() {
// Use driver.findElement here
}
}
```
- Scope of Variables:
- Be cautious about variable scope. If you accidentally create a local `driver` variable within a method, it will shadow the class-level `driver` field.
- Ensure that you're using the correct `driver` (the class-level one) consistently.
- Debugging:
- Print debug statements to check the value of `this.driver` at various points in your code.
- Verify that it's not null when you call `findElement`.
3. Example Fix:
- Assuming you have a class-level `driver` field, make sure you initialize it properly:
```java
public class MyTest {
private WebDriver driver;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
}
@Test
public void myTest() {
// Use driver.findElement here
}
}
```
Remember to verify the initialization of the `driver` object and ensure it's not null before invoking any methods on it. Happy testing
SIr, Lots of people are learning from you , Can you prepare 1 more script using page factory from scratch using data driven ? as soon as possible
Sure, will plan Ratish
Hi Raghav I followed all your steps but I got an error - java.lang.IllegalArgumentException: Keys to send should be a not null CharSequence when I ran the feature file.
Hi Bjorn, pls check somewhere in your code prop.getProperty is getting null value
@@RaghavPal Hi Raghav, I seem to ind my mistakes, I forgot to include the variables inside the parenthesis in the class declarations.. My bad.
After running the code getting java.lang.NullPointerException, how to fix this?
Hi Anusha, will have to check detailed logs for this
Cannot invoke "pageFactory.HomePage_PF.checkLogoutDisplayed()" because "this.home" is null
Please tell me why it not run?
Hi Anh, pls debug your code and you will see some issue on your home object
@@RaghavPal because you forgot to create an instance at your code. You only did a loginpage on the video
Hi Raghav, how are you, I did one of the examples in the scenario outline with a incorrect password and I expected that this scenario to fail, because the button "logout" wasn't there. But the test for this scenario didn't failed.Why not?. Thanks
Hi Susel, pls check again if the assertions are correct, If you are not able to resolve, can show me the setup
I have created project like that and then i am getting chrome crashing error means when i am trying to run cucumber script then chrome is opening and closes
Hi Mamta, check the ver of chrome on your system and then check the ver of chromedriver you are using, Can try with same ver
@@RaghavPal I tried apart from that project other maven cucumber project is working fine but this is happening with one cucumber project only
Tried all possible things but didn’t work
Please help with this 🙏
Thank u
Welcome
By creating the cucumber framework google data browser n then normal browser opens
Hi Danish, check your script again, also see when happens when you run the next step, does it fail, in that case can check logs
Timing:21:56, Line 18. the wrong class is passed as the second argument? Please correct me if I'm wrong.
I will check Arun
I could easily follow all the previous videos but got stuck in this video. One simple doubt. In which file the xpath of 'txt_username' mentioned? I couldnt get it. My script is failing. The reason is that script is not able to identify what is XPath of txt_username. Plz help me
Hi Shaji, in the pages classes like LoginPage or HomePage, we have provided locators. Now it depends on the object properties available, you can create locators with id, name etc or xpath
Followed all the instructions to the letter--even did the tutorial twice--and whenever I ran the Feature file test scenario, failed with lots of different kinds of Unknown Source errors
Hi Laura, can check the project from GitHub - github.com/Raghav-Pal/SeleniumCucumberBDD
I think that you forgot to initiliazie an instance of homepage , that is why your browser wasn't closed at the end although should :)
Ok, will check, thanks for adding
Hi Thank you for the good work.
@Raghav Can we have GIT hub link for this video.
I will add and update the description Anil
Automation Step by Step - Raghav Pal Thanks
is selenium static tester or dynamic tester..?
Selenium is a library to interact with browser by automating browser actions
if we are copy/pasting the login page it gives an error of duplicate steps
Hi, yes, you will need to make some changes, it should not be exact copy else you can use the same test
namaste sir
can u login & logout facebook using page factory
Yes, Page Factory is a design pattern and a class provided by Selenium WebDriver to implement the Page Object Model (POM). It simplifies the process of initializing and managing web elements in a page object class.
So you can implement this for any scenario
Sir please make a video🙏
will plan Anil
Thank you sir🙏
Hi Raghav,
Thank you for the getting issue while doing the tutorial, we could know where things might go wrong.
In that context, I want to know why I am getting NullPointerException when creating the login object of LoginPage login = new LoginPage(driver); in the class and running successfully creating it in methods.
Hi Venu, will need to check the complete code, Where is driver being referred from.
Hello Raghav, 1st I want to thank you a lot for your work ;-)
2nd - I have a problem - when I run the project it stacks at entering username and password. I see some actions over and over again and in the console I see this (repeated multiple times):
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.openqa.selenium.support.PageFactory.instantiatePage(PageFactory.java:126)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:63)
at pageFactory.LoginPage_PF.(LoginPage_PF.java:23)
at jdk.internal.reflect.GeneratedConstructorAccessor8.newInstance(Unknown Source)
As I've said Eclipse stacks and I must force-terminate the run. Can you help me understand what goes wrong here?
Hi Sławomir, do you see any Caused by section in your logs
@@RaghavPal - unfortunately not. Every time I run the program I see this: www.screencast.com/t/lsVqAGNcZ
This can help examples.javacodegeeks.com/solving-slf4j-failed-load-class-org-slf4j-impl-staticloggerbinder/
stackoverflow.com/questions/7421612/slf4j-failed-to-load-class-org-slf4j-impl-staticloggerbinder
could you pls upload it to GITHUB
I will do Santhosh
Thank you soo much
Why you don't create one simple project with all this step by step then delete previous and upgrade with new it is a bit confusing, just create a simple project with UI maps class with StepDefinition LoginClass and connect them with the POM model and will be more clear than this.
I will check on this
Please upload Sir
I will add new sessions in some time Santhosh
.initElement(driver,classname.class) is giving error of infinite loop of creating driver. Changed it to” this “ and it worked
great, thanks for adding
Hello Raghav. First of all thank you for this amazing session.. I have been watching many of your courses and you have helped me a lot. I have been facing an issue regarding this session though. Step failed
java.lang.NullPointerException: Cannot invoke "pagefactory.HomePage_PF.checkLogoutIsDisplayed()" because "this.home" is null
at StepDefs.LoginDemoSteps_PF.user_is_navigated_to_the_home_page(LoginDemoSteps_PF.java:66)
at ?.user is navigated to the home page(file:///C:/Users/dnikola/Repos/CucumberJava/src/test/resources/Features/LoginDemo.feature:9).
I can't seem to understand what the issue is. Could you please help me?
Sure, I can help you with that.
The error message you are getting is a NullPointerException. This means that the variable `home` is null. This can happen if the `HomePage_PF` object has not been initialized yet.
To fix this, you need to make sure that the `HomePage_PF` object is initialized before you try to call the `checkLogoutIsDisplayed()` method. You can do this by adding the following code to your `LoginDemoSteps_PF` class:
```
public HomePage_PF home;
@Before
public void setUp() {
this.home = new HomePage_PF();
}
```
This code will initialize the `home` variable before the `user_is_navigated_to_the_home_page()` step is executed. Once the `home` variable is initialized, you should be able to call the `checkLogoutIsDisplayed()` method without getting a NullPointerException.
Here is the complete code for the `LoginDemoSteps_PF` class:
```
public class LoginDemoSteps_PF {
private HomePage_PF home;
@Before
public void setUp() {
this.home = new HomePage_PF();
}
@Given("I am on the login page")
public void i_am_on_the_login_page() {
home.open();
}
@When("I enter my username and password")
public void i_enter_my_username_and_password() {
home.enterUsername("johndoe");
home.enterPassword("password");
}
@When("I click on the login button")
public void i_click_on_the_login_button() {
home.clickLoginButton();
}
@Then("I am navigated to the home page")
public void i_am_navigated_to_the_home_page() {
home.checkLogoutIsDisplayed();
}
}
```
Once you have added this code, you should be able to run your Cucumber tests without getting a NullPointerException.
I hope this helps
@@RaghavPal Thank you so much for that.. Keep up the great work
Thank you so much, Raghav. Great Session. :)
Most welcome Mayank