We have implemented the Selenium Grid (Distributed Test) Concept with our existing framework, while implemented its produce an Null Pointer Exception
as of now i have an single package, with three class file (Baseclass, Loginclass, testcase)
Baseclass - getting my desired driver and navigate to application
class Baseclass {
public WebDriver myDriver;
public static String baseUrl;
// Explicit Constructors
public Baseclass() {
baseUrl = "https://example.com/";
}
public void Navigate(String url) {
String navigateToThisUrl = baseUrl + url;
myDriver.navigate().to(navigateToThisUrl);
}
public void GetDriver() throws MalformedURLException {
threadDriver = new ThreadLocal<RemoteWebDriver>();
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
FirefoxProfile fp = new FirefoxProfile();
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, fp);
desiredCapabilities.setBrowserName(DesiredCapabilities.firefox()
.getBrowserName());
myDriver = new RemoteWebDriver(new URL(
"http://localhost:5555/wd/hub"), desiredCapabilities);
}
}
and in Loginclass navigate to the location (either QA or UAT etc.,)
public class Loginclass extends Baseclass {
public Loginclass navigateToLogin() {
Navigate("qa");
return new Loginclass();
}
}
Testcase we have an test case and executed the same
public class TestcaseSearch extends Loginclass {
#BeforeTest
public final void Startup() throws MalformedURLException {
Baseclass baseClass = new Baseclass();
baseClass.GetDriver;
}
#Test
public void fieldsSearch(String username, String password)
throws Exception {
Loginclass loginClass = new Loginclass();
navigateToLogin();
}
}
While Execute the above its produce an Null Pointer Exception
Baseclass: idsDriver.navigate().to(navigateToThisUrl);
Loginclass :Navigate("qa");
Let me know how can i rectify this
Exception output
java.lang.NullPointerException
at com.Baseclass.Navigate(Baseclass.java:11)
at com.Loginclass.Navigate(Loginclass.java:1)
at com.TestcaseSearch.Navigate(TestcaseSearch.java:1)
at com.Loginclass.navigateToLogin(Loginclass.java:4)
at com.TestcaseSearch.fieldsSearch(TestcaseSearch.java:11)
Your myDriver instance is null because you create a new instance of Baseclass in Startup(), which sets myDriver on itself rather than the actual test class instance.
Similarly, you don't need to create a new Loginclass in fieldsSearch, because TestcaseSearch is a subclass of Loginclass:
public class TestcaseSearch extends Loginclass {
#BeforeTest
public final void Startup() throws MalformedURLException {
GetDriver();
}
#Test
public void fieldsSearch(String username, String password)
throws Exception {
navigateToLogin();
}
}
Related
public class CommonFunctions {
public static WebDriver driver;
public void openWebsite(String url) {
driver.get(url);
}
public void closeBrowser() {
driver.close();
}
}
public class TestCase {
CommonFunctions commonFunctions = new CommonFunctions();
#BeforeMethod
public void openWeb() {
homePage.openWeb();
}
#Test
public void navigateLoginPage() {
homePage.login();
}
#AfterMethod
public void closeBrowser() {
commonFunctions.closeBrowser();
}
}
I have two class (commonfunction,homepage and testcase). When I run code without "static" at "public static Webdriver driver", the code throw nullpointerexception at function "closeBrowser". How to fix this error. I don't want use method "public static Webdriver driver" as code.
You need to initialize your driver variable in your CommonFunctions class.
WebDriver driver = new WebDriver(... etc);
Or, write a constructor that initializes this variable.
public class CommonFunctions
{
public WebDriver driver;
public CommonFunctions() // Constructor
{
driver = new WebDriver();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I am new to this java Selenium.
I have 2 classes. 1 parent and 1 child.
I have some methods in the parent class.
I pass 2 of them to the child class.
The problem is only 1 method (from the parent) executes and the 2nd failed.
can you help me to understand why I am getting the error and how to resolve it please :
"java.lang.NullPointerException"
Parent class :
public class SignUp {
public WebDriver driver;
public void go(WebDriver driver)
{
driver.findElement(By.id("id_sign_up")).click();
}
#Test
public void signup(WebDriver driver)
{
driver.findElement(By.linkText("I’m an advertiser")).click();
}
public void FormSign (WebDriver driver)
{
driver.findElement(By.xpath("//span[#css='1']")).sendKeys("Miron");
}
}
Child class :
public class OpenBrowser extends SignUp{
#Test
public void Start() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://account.admitad.com/en/sign_in/");
SignUp sg = new SignUp();
sg.go(driver);
//sg.signup(driver);
}
#Test
public void miron ()
{
SignUp mi = new SignUp();
mi.signup(driver);
}
Can someone please help me?
Thanks in advance
Ans: WebDriver driver object is inside Start().
Object declaration should be defined out side. Then all methods can access driver obj.
public class SignUp {
public WebDriver driver;
public void go(WebDriver driver)
{
driver.findElement(By.id("id_sign_up")).click();
}
//#Test
public void signup(WebDriver driver)
{
driver.findElement(By.linkText("I’m an advertiser")).click();
}
public void FormSign (WebDriver driver)
{
driver.findElement(By.xpath("//span[#css='1']")).sendKeys("Miron");
}
}
/*******************/
public class OpenBrowser extends SignUp{
WebDriver driver = null;
#BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://account.admitad.com/en/sign_in/");
}
#Test
public void Start() throws InterruptedException
{
SignUp sg = new SignUp();
sg.go(driver);
//sg.signup(driver);
}
#Test
public void miron ()
{
SignUp mi = new SignUp();
mi.signup(driver);
}
}
I am using Java, Selenium, Cucumber and Page Objects to run my tests. I have StepDef file which looks like below:
public class stepDefinition extends Base{
#Given("^Navigate to Landing page$")
public void navigate_to_landing_page() throws Throwable {
driver= initializeDriver();
driver.get(prop.getProperty("url"));
}
#Then("^Landing page is rendered$")
public void landing_page_is_rendered() throws Throwable {
SomePage ep = new SomePage ();
sp.LandingPageLoaded();
}
#When("^Clicks Apply Now$")
public void clicks_apply_now() throws Throwable {
SomePage ep = new SomePage ();
sp.clickApplyNow();
}
And I want initialize object of SomePage only once on class level, and use in all methods inside my stepDefinition class, see below:
public class stepDefinition extends Base{
SomePage sp = new SomePage ();
#Given("^Navigate to Landing page$")
public void navigate_to_landing_page() throws Throwable {
driver= initializeDriver();
driver.get(prop.getProperty("url"));
}
#Then("^Landing page is rendered$")
public void landing_page_is_rendered() throws Throwable {
sp.LandingPageLoaded();
}
#When("^Clicks Apply Now$")
public void clicks_apply_now() throws Throwable {
sp.clickApplyNow();
}
But it throws me NullPointerException for sp.clickApplyNow(); if I'm not initializing object inside that method. Is there any way to initialize object only on class level. I am new to java.
I am new in Selenium and Java and I need help with base class. I have I base where I set methods for driver browsers and for its close. Problem is that when I call these method from main always web driver is called and browser is open many times. What is best practice if I don't want to have code duplication
and I want a good structure of project.
Main:
public class Main extends TestBase {
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
LoginTest LoginTest = new LoginTest();
LogofTest LogofTest = new LogofTest();
TestBase TestBase = new TestBase();
LoginTest.setUpBeforeTestMethod();
LoginTest.loginAsAdmin();
LogofTest.logofAsAdmin();
LoginTest.tearDownAfterTestClass();
}
}
TestBase:
public class TestBase {
String a = System.setProperty("webdriver.chrome.driver",
"path");
WebDriver driver = new ChromeDriver();
protected WebDriver setUpBeforeTestClass() {
return driver;
}
protected void setUpBeforeTestMethod() {
driver.get("website");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void tearDownAfterTestClass() {
driver.close();
}}
LoginTest:
public class LoginTest extends TestBase {
public void login() throws InterruptedException {
WebElement username = driver.findElement(By.name("username"));
username.sendKeys("username");
}
}
The main focus is that I don't want to write again
WebDriver driver = new ChromeDriver();
driver.get("website"); System.setProperty("webdriver.chrome,"path");
for each test in function or class. So I want to create base class and inherit from it.
Example Selenium Test with JUnit using the Page Object Model
TestBase
public class TestBase
{
private String a = System.setProperty("webdriver.chrome.driver", "path");
protected WebDriver driver;
#Before //Before each test case, use BeforeClass for before each test class
public static void setUpBeforeTestCase() {
driver = new ChromeDriver();
driver.get("website");
}
#After
public static void tearDownAfterTestCase() {
driver.Quit(); //driver.Close() closes the window, but doesn't properly dispose of the driver
}
}
LoginTest:
public class LoginTest extends TestBase {
#Test
public void loginAndOutAsAdmin(){
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
LandingPage landingPage = loginPage.login("adminUser", "adminPassword");
landingPage.logout();
//Do some sort of assert here that you are logged out
}
}
BasePage
public class BasePage
{
protected WebDriver driver;
//Other common stuff your Page Objects will do, like wait for an element
}
LoginPage
public class LoginPage extends BasePage
{
#FindBy(how = How.NAME, using = "username")
private WebElement usernameBox;
//something for passwordBox and loginButton
public LoginPage(WebDriver currentDriver)
{
driver = currentDriver;
}
public LandingPage login(String username, String password)
{
usernameBox.sendKeys(username);
passwordBox.sendKeys(password);
loginButton.click();
return PageFactory.initElements(driver, LandingPage.class);
}
}
I haven't tried to compile this, but that's the basic idea. I'll let you fill in the details.
I am running this class as testNG and getting error either make it static or add a no-args constructor. If I add no arg constructor, I get error: "implicit super constructor BaseClass() is undefined."
public class testmaven extends BaseClass{
public testmaven(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
#Test
public void myMethod() throws Exception {
logInPage.openApp("Chrome","http://url.com");
}
Here is the Base Class:
public class BaseClass {
public WebDriver driver;
public boolean isDisplay;
public LogInPage logInPage;
public WaitForObj wait;
public DashboardPage dashboardPage;
public Actions action;
public Util util;
public BaseClass(WebDriver driver){
this.driver = driver;
this.isDisplay = false;
logInPage = new LogInPage(driver);
wait = new WaitForObj(driver);
dashboardPage = new DashboardPage(driver);
util = new Util (driver);
action = new Actions(driver);
}
Here is the Login class
public class LogInPage extends BaseClass {
BrowserFactory browserfactory = new BrowserFactory();
public LogInPage(WebDriver driver){
super(driver);
}
public void openApp(String browserName, String env) throws Exception{
driver = browserfactory.getBrowser(browserName);
Log.info("Browser:" + browserName);
driver.manage().window().maximize();
driver.get(env);
Log.info("Env: " + env);
wait.wait(1);
}
You have to explain to TestNG how it is supposed to instanciate your test class.
A solution is using a #Factory.
Another solution, which is a more common pattern, is having an empty constructor and using #BeforeX and/or #AfterX methods for the initialisation of attributes.