Sakamoto Kazuma
Sakamoto Kazuma

Reputation: 2579

Passing Webdriver As An Instance

What I'm trying to do with this is to allow one section of the app to allow the user to run a few tests with webdriver. Then, without closing that window, making changes to the web app and then kicking off a separate method to perform other actions.

What I've created is class BrowserAgent that holds a Webdriver object like so:

 public class BrowserAgent
{
    private static BrowserAgent instance = new BrowserAgent();
    private boolean BrowserAgentBusy = false;
    private static boolean BrowserAgentActive = false;
    private static WebDriver driver;
...

Now when I get the instance of the driver I am simply calling BrowserAgent.getDriver() which is implemented like so:

public static WebDriver getDriver()
    {    
        if(BrowserAgentActive && driver != null)
        {
            return driver;
        }
        else
        {
            BrowserAgentActive = true;
            return new FirefoxDriver();
        }

    }

However, for some reason, every time I call getDriver(), a new window opens, and all of the context from the first window is now lost. What am I doing wrong?

Upvotes: 2

Views: 166

Answers (1)

Ron Jensen
Ron Jensen

Reputation: 652

You're never setting driver to anything, so it's always null and your code always takes the else{} branch.

This is the way I might do something like this:

using System;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

namespace DriverTesting
{
    [TestFixture]
    public class UnitTest1
    {
        [Test]
        public void TestMethod1()
        {
            IWebDriver myDriver = BrowserAgent.getDriver();
            myDriver.Navigate().GoToUrl("http://www.google.com/");
        }

        [Test]
        public void TestMethod2()
        {
            IWebDriver myDriver = BrowserAgent.getDriver();
            myDriver.Navigate().GoToUrl("http://www.yahoo.com/");
        }
    }
}

public class BrowserAgent
{
    private static IWebDriver driver;

    public static IWebDriver getDriver()
    {
        if (driver == null) {
            driver = new InternetExplorerDriver();
        }
        return driver;
    }
}

Upvotes: 1

Related Questions