logo
down
shadow

Passing the single instance of the driver object to all other classes (Testng framework)


Passing the single instance of the driver object to all other classes (Testng framework)

By : Jonathan
Date : November 18 2020, 03:49 PM
this one helps. I found a solution myself...When i read about the testng in detail i found that testng xml file calls the default constructor of all classes specified in the xml file.so even if we pass the object to another class we cannot perform the action through the object so null pointer exception occurs....i found two solutions first one is to use a pagefactory and second one is to use a common driver class for your Test suite...so that we can use the same driver instance in all classes
Common driver class
code :
public class Driver {

    public static WebDriver driver=null;



    public static WebDriver startdriver(String browser){


        if(browser.equalsIgnoreCase("Chrome")){

        System.setProperty("webdriver.chrome.driver", "/home/vicky/Documents/Jars/chromedriver");

        driver=new ChromeDriver();

        }else if(browser.equals("Firefox")){

        driver=new FirefoxDriver();

        }
        return driver;

        }

    }


Share : facebook icon twitter icon
How to run multiple test classes in testng suite with only one web driver instance?

How to run multiple test classes in testng suite with only one web driver instance?


By : michael
Date : March 29 2020, 07:55 AM
Hope this helps I have testng.xml file as below... , Try below new class
code :
public class Config extends Verification{

public static WebDriver driver;

public SoftwarePage softwarepage;
public LoginPage loginpage;

@BeforeSuite
public void setUp(){
    driver = DriverFactory.getDriverInstance();
}

@AfterSuite
public void tearDown(){

    if (driver != null) {
        driver.quit();
    }
}
public class SoftwareTest extends Config {

private Log log = LogFactory.getLog(SoftwareTest.class);

@BeforeClass(alwaysRun = true)
public void setup() throws InterruptedException {

    softwarepage = new SoftwarePage(driver);

}
How to run multiple test classes in testng suite with only one web driver instance?

How to run multiple test classes in testng suite with only one web driver instance?


By : Jesús
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The problem lies in your test code. @BeforeSuite is designed in TestNG to be invoked only once per . You are combining that logic along with inheritance and then relying on the @BeforeSuite method to initialize your WebDriver. So it will do it for the first class in your by from the second class onwards TestNG is not going to be invoking the @BeforeSuite and thus your second class onwards you start seeing the NullPointerException. You should instead consider relying on a ISuiteListener implementation as a listener and then wire it into your test execution.
Your tests would now start relying on a webdriver that is created in this manner and then work with it.
code :
package com.rationaleemotions.stackoverflow.qn46323434;

import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Listeners;

@Listeners(BrowserSpawner.class)
public class MyBaseClass {
    protected void launchPage(String url) {
        RemoteWebDriver driver = BrowserSpawner.getDriver();
        driver.get(url);
        System.err.println("Page Title :" + driver.getTitle());
    }
}
package com.rationaleemotions.stackoverflow.qn46323434;

import org.testng.annotations.Test;

public class MyFirstTestCase extends MyBaseClass {

    @Test
    public void testGooglePage() {
        launchPage("http://www.google.com");
    }

    @Test
    public void testFaceBookPage() {
        launchPage("http://www.facebook.com");
    }
}

package com.rationaleemotions.stackoverflow.qn46323434;

import org.testng.annotations.Test;

public class MySecondTestCase extends MyBaseClass {

    @Test
    public void testHerokkuPage() {
        launchPage("https://the-internet.herokuapp.com/");
    }

    @Test
    public void testStackOverFlowPage() {
        launchPage("http://stackoverflow.com/");
    }
}
package com.rationaleemotions.stackoverflow.qn46323434;

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestResult;
import org.testng.Reporter;

public class BrowserSpawner implements ISuiteListener {
    private static final String DRIVER = "driver";

    @Override
    public void onStart(ISuite suite) {
        RemoteWebDriver driver;
        String browserType = suite.getParameter("browserType");
        switch (browserType) {
            case "chrome":
                driver = new ChromeDriver();
                break;
            default:
                driver = new FirefoxDriver();
        }
        suite.setAttribute(DRIVER, driver);
    }

    @Override
    public void onFinish(ISuite suite) {
        Object driver = suite.getAttribute(DRIVER);
        if (driver == null) {
            return;
        }
        if (!(driver instanceof RemoteWebDriver)) {
            throw new IllegalStateException("Corrupted WebDriver.");
        }
        ((RemoteWebDriver) driver).quit();
        suite.setAttribute(DRIVER, null);
    }

    public static RemoteWebDriver getDriver() {
        ITestResult result = Reporter.getCurrentTestResult();
        if (result == null) {
            throw new UnsupportedOperationException("Please invoke only from within an @Test method");
        }
        Object driver = result.getTestContext().getSuite().getAttribute(DRIVER);
        if (driver == null) {
            throw new IllegalStateException("Unable to find a valid webdriver instance");
        }
        if (! (driver instanceof RemoteWebDriver)) {
            throw new IllegalStateException("Corrupted WebDriver.");
        }
        return (RemoteWebDriver) driver;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46323434_Suite" parallel="false" verbose="2">
    <parameter name="browserType" value="chrome"/>
    <test name="46323434_test1">
        <classes>
            <class name="com.rationaleemotions.stackoverflow.qn46323434.MyFirstTestCase"/>
        </classes>
    </test>
    <test name="46323434_test2">
        <classes>
            <class name="com.rationaleemotions.stackoverflow.qn46323434.MySecondTestCase"/>
        </classes>
    </test>
</suite>
...
... TestNG 6.12 by Cédric Beust (cedric@beust.com)
...
Starting ChromeDriver 2.32.498537 (cb2f855cbc7b82e20387eaf9a43f6b99b6105061) on port 45973
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
Sep 20, 2017 10:36:41 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Page Title :Facebook – log in or sign up
Page Title :Google
PASSED: testFaceBookPage
PASSED: testGooglePage

===============================================
    46323434_test1
    Tests run: 2, Failures: 0, Skips: 0
===============================================
Page Title :The Internet
Page Title :Stack Overflow - Where Developers Learn, Share, & Build Careers
PASSED: testHerokkuPage
PASSED: testStackOverFlowPage

===============================================
    46323434_test2
    Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
46323434_Suite
Total tests run: 4, Failures: 0, Skips: 0
===============================================
Selenium TestNG framework unable to call driver object in multiple test

Selenium TestNG framework unable to call driver object in multiple test


By : larskissel
Date : March 29 2020, 07:55 AM
With these it helps The class variable driver is never initialized, you're defining a new variable called driver inside the login method.
Use:
code :
public void login(){
    driver = new FirefoxDriver();
    ....
}
public void login(){
    WebDriver driver = new FirefoxDriver();
    ....
}
How can I use google guice DI outside of testNG test classes in a testNG based framework?

How can I use google guice DI outside of testNG test classes in a testNG based framework?


By : Aaron Lewkowiez
Date : March 29 2020, 07:55 AM
With these it helps I have create some general example for you - test with injection example
It works as you're expecting, I hope. It provides some test configs, injects them to driver and at last driver is injected in test component.
code :
import com.google.inject.Inject;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

@Guice(modules = {TestModule.class})
public class SimpleTest {

    @Inject
    ComponentUnderTest component;

    @Test
    public void sampleTest() {
        System.out.println(component.getParamToTest());
        System.out.println(component.param);
        System.out.println(component.elseone);
    }

}
TestNG parallel execution with single driver instance

TestNG parallel execution with single driver instance


By : user2941269
Date : March 29 2020, 07:55 AM
With these it helps In my test suite, I have a Base class in which I declare a static WebDriver, which is then generated as a ChromeDriver, FirefoxDriver, etc, in a method that opens a base url. This method is used in my BeforeMethod in all my test cases, therefore a single static instance of driver is used in every test execution, and throughout a range of reusable methods utilised within the test cases (for example, a log in method). , You can use threadlocal webdriver as given below.
code :
public class Base {


public static ThreadLocal<WebDriver> driver = new ThreadLocal<>();

//Input client under test
public static final String Client = "Client1";

//Input default environment under test
public static final String DefaultEnvironment = "Chrome_Hub";


//CALL WEB BROWSER AND OPEN WEBSITE
public static void openURL(String environment) throws InterruptedException, IOException {

    try{

        if(environment.equals("Chrome_Hub")) {
            System.setProperty("webdriver.chrome.driver", "/Users/rossdonohoe/Desktop/SeleniumJava/Drivers/chromedriver");
            driver.set(new ChromeDriver());
        }
        if(environment.equals("Firefox_Hub")) {
            System.setProperty("webdriver.gecko.driver", "/Users/rossdonohoe/Desktop/SeleniumJava/Drivers/geckodriver");
            driver.set(new FirefoxDriver());
        }

        driver.get(DataFinder.ReadData("front end url"));


    }
    catch(Exception E) {
        E.printStackTrace();
    }
}
}
public class LoginLogoutScript extends Base {


  @Test (priority = 2)
  public void login() throws InterruptedException, IOException {
        LoginLogout.loginFrontEnd();
        Assert.assertTrue(driver.getPageSource().contains("My Account") || driver.get().getPageSource().contains("My Dashboard"));
  }

  @Parameters({ "Environment" })
  @BeforeClass
  public void setUp(@Optional(DefaultEnvironment) String Environment) throws InterruptedException, IOException {
      Base.openURL(Environment);
  }

  @AfterClass public void tearDown() { 
      Base.driver.get().quit(); 
  }

}
Related Posts Related Posts :
  • How can I share props in ReasonReact?
  • Task.Delay is skipped
  • Parsley.js Password Confirm doesn‘t work
  • How to get all registred 'browser:resource' in Plone
  • Overriding page_list controller inside a package in Concrete5.6.1.2
  • Robolectric 2.x - dependent jars are downloading while running the tests
  • Setting Flyout to Main Frame Navigation(Windows 8.1 app store)
  • Build project - Nuget Error
  • How to recover admin password for SonarQube
  • perforce Tagging and labelling files
  • How to pass data from one window to another in Titanium?
  • TeamCity CI - Make custom build output folder
  • Multi-tenant ServiceStack API, same deployment to respond to requests on different hostnames?
  • How to show downshift + popper on top of material-ui dialog?
  • jQuery file upload and RequireJS configuration
  • How to send the result of a select query to a message body of a mail in oracle 10G
  • Worklight common build failing with "Failed to update main HTML file"
  • pg_listening_channels() is not returning the channels name
  • Asset management in ZF2
  • Does the Firefox add-on sdk allow direct modification of the http response byte stream?
  • How to remove menu hardware key from your android app
  • Identifying programming language
  • Use shell commands to find Makefile.am in configure.ac
  • Mono Compiler as Service or Microsoft Roselyn for a vb parser
  • How to add extra root nodes for not well formed XML structure?
  • which Uncrustify setting replaces blank lines with indenting spaces?
  • mac OSX Lion Homebrew install curl (77)
  • In Project Euler 47, why is 2^2 considered a prime number distinct from 2?
  • browserstack requesting localhost:45691
  • What was the real reason why Google is chosing RenderScript instead of OpenCL?
  • Mandrill Inbound Email routing
  • Prevent checkElementIndex() Guava function from concatenating additional response to existing error message
  • Arduino and Raspberry Pi Serial communication + multiple variables
  • convert a 960 grid based site to responsive
  • Should it be possible to have more than one DocuSign account (DEMO) with the same email address?
  • Is it possible to limit ammount of concurrent builds in Travis-CI
  • Selecting languages with specific ISO code
  • Deprecated vs Unsupported SDK
  • Verifying ClearCase files have been labeled properly
  • What's the difference between "Bag of Words" and "Bag of features" in computer vision?
  • Is there a way to tell Serde to use a struct field as a map's key?
  • ld:framework not found sfml
  • nice, go-idiomatic way of using a shared map
  • IzPack ChmodInstallerListener.jar
  • Breaking down tasks of user stories between developer and QA
  • Dropwizard service not starting properly
  • How to override devise invitable actions
  • Coded UI. How can I change TimeOut in Find() method
  • Why when I click on the update button error TypeError: r is undefined happen?
  • Visio Component Diagram - Required Interface
  • Lucene: fast(er) to get docs in bulk?
  • can I use windows 8 font (Segoe UI)for my web app?
  • Using Flask Session in Gevent Socket-IO
  • Difference between recommended and suggested cookbooks
  • Dynamic Forms (Formsets) in Flask / WTForms?
  • Image Servlet doesn't want to show image in browser (FireFox, IE..) but in Eclipse browser works?
  • Logback - how to get each logger logging to a separate log file?
  • In Crystal Reports, how do I keep a row from printing if the value is null?
  • iOS 6 Audio multi-route - use external microphone AND internal speaker simultaneously
  • Adding Comments in JasperReports template (jrxml)
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org